-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
47 lines (39 loc) · 1.25 KB
/
middleware.ts
File metadata and controls
47 lines (39 loc) · 1.25 KB
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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { auth } from "./lib/auth/config";
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const protectedRoutes = ["/dashboard", "/projects", "/settings"];
const isProtectedRoute = protectedRoutes.some(
(route) => pathname.startsWith(route) || pathname === route,
);
if (isProtectedRoute) {
const session = await auth.api.getSession({
headers: request.headers,
});
if (!session?.user) {
const redirectUrl = new URL("/login", request.url);
redirectUrl.searchParams.set("callbackUrl", request.url.toString());
return NextResponse.redirect(redirectUrl);
}
}
if (pathname === "/login") {
const session = await auth.api.getSession({
headers: request.headers,
});
if (session?.user) {
const callbackUrl = request.nextUrl.searchParams.get("callbackUrl");
const redirectUrl = new URL(callbackUrl || "/dashboard", request.url);
return NextResponse.redirect(redirectUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
"/dashboard/:path*",
"/projects/:path*",
"/settings/:path*",
"/login",
],
};