-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
45 lines (36 loc) · 1.03 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
import { NextResponse } from "next/server";
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
const isPublicRoute = createRouteMatcher([
"/sign-in(.*)",
"/sign-up(.*)",
"/",
"/api/webhook",
]);
export default clerkMiddleware((auth, req) => {
if (!isPublicRoute(req)) {
auth().protect();
} else {
if (auth().userId && isPublicRoute(req)) {
let path = "/select-org";
if (auth().orgId) {
path = `/organization/${auth().orgId}`;
}
const orgSelection = new URL(path, req.url);
return NextResponse.redirect(orgSelection);
}
if (!auth().userId && !isPublicRoute(req)) {
return auth().redirectToSignIn({ returnBackUrl: req.url });
}
if (
auth().userId &&
!auth().orgId &&
req.nextUrl.pathname !== "/select-org"
) {
const orgSelection = new URL("/select-org", req.url);
return NextResponse.redirect(orgSelection);
}
}
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};