-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
42 lines (36 loc) · 1.02 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
import { authMiddleware, clerkClient } from "@clerk/nextjs";
import { NextResponse } from "next/server";
export default authMiddleware({
publicRoutes: [
"/",
"/signin(.*)",
"/signup(.*)",
"/sso-callback(.*)",
"/about(.*)",
"/contact(.*)",
"/terms(.*)",
"/privacy(.*)",
"/api(.*)",
],
async afterAuth(auth, req) {
if (auth.isPublicRoute) {
// For public routes, we don't need to do anything
return NextResponse.next();
}
const url = new URL(req.nextUrl.origin);
if (!auth.userId) {
// If user tries to access a private route without being authenticated,
// redirect them to the sign in page
url.pathname = "/signin";
return NextResponse.redirect(url);
}
// Set the user's role to user if it doesn't exist
const user = await clerkClient.users.getUser(auth.userId);
if (!user) {
throw new Error("User not found.");
}
},
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};