-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
44 lines (37 loc) · 1.34 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
const isPublicRoute = createRouteMatcher([
"/sign-in",
"/sign-up",
"/",
"/home"
])
const isPublicApiRoute = createRouteMatcher([
"/api/video",
"/api/user/signup"
])
export default clerkMiddleware((auth, req) => {
const {userId} = auth();
const currentUrl = new URL(req.url)
const isAccessingDashboard = currentUrl.pathname === "/home"
const isApiRequest = currentUrl.pathname.startsWith("/api")
// If user is logged in and accessing a public route but not the dashboard
if(userId && isPublicRoute(req) && !isAccessingDashboard) {
return NextResponse.redirect(new URL("/home", req.url))
}
//not logged in
if(!userId){
// If user is not logged in and trying to access a protected route
if(!isPublicRoute(req) && !isPublicApiRoute(req) ){
return NextResponse.redirect(new URL("/sign-in", req.url))
}
// If the request is for a protected API and the user is not logged in
if(isApiRequest && !isPublicApiRoute(req)){
return NextResponse.redirect(new URL("/sign-in", req.url))
}
}
return NextResponse.next()
})
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};