-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
50 lines (42 loc) · 1.41 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
import {
clerkClient,
clerkMiddleware,
createRouteMatcher,
} from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
const isProtectedRoute = createRouteMatcher(["/admin(.*)", "/user(.*)"]);
export default clerkMiddleware(
async (auth, request) => {
if (isProtectedRoute(request)) {
await auth.protect();
const { userId } = await auth();
const url = new URL(request.url);
const path = url.pathname;
if (userId) {
const client = await clerkClient();
const user = await client.users.getUser(userId);
const publicMetadata = user.publicMetadata;
const isNewUser =
publicMetadata?.isNew &&
(path.startsWith("/admin") || path.startsWith("/user"));
if (isNewUser && path !== "/user/profile") {
return NextResponse.redirect(new URL("/user/profile", request.url));
}
}
if (path === "/user") {
return NextResponse.redirect(new URL("/user/dashboard", request.url));
}
if (path === "/admin") {
return NextResponse.redirect(new URL("/admin/dashboard", request.url));
}
}
return NextResponse.next();
},
// { debug: process.env.NODE_ENV === "development" }
);
export const config = {
matcher: [
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/(api|trpc)(.*)",
],
};