-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
54 lines (44 loc) · 1.81 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
45
46
47
48
49
50
51
52
53
54
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
const isPublicRoute = createRouteMatcher([
"/sign-in",
"/sign-up",
"/",
"/home",
]);
const isPublicApiRoute = createRouteMatcher(["/api/videos"]);
export default clerkMiddleware(async (auth, req) => {
const userId = await auth();
//console.log("userId is ", userId);
//console.log(!userId.userId);
const currentUrl = new URL(req.url);
//if user is accessing root page, redirect to Homepage
const isAccessingRoot = currentUrl.pathname === "/";
if (isAccessingRoot) {
return NextResponse.redirect(new URL("/home", 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.userId && isPublicRoute(req) && !isAccessingDashboard) {
return NextResponse.redirect(new URL("/home", req.url));
}
//not logged in
if (!userId.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();
});
// This middleware code will only run on routes that match the patterns below. Any other routes will skip the middleware.
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
//matcher: ["/)"],
};