-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
41 lines (32 loc) · 1.46 KB
/
middleware.ts
File metadata and controls
41 lines (32 loc) · 1.46 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Public routes that don't require authentication
const publicRoutes = ["/", "/login"];
const isPublicRoute = publicRoutes.some(route => pathname === route || pathname.startsWith(route));
// API routes and static files
const isApiRoute = pathname.startsWith("/api");
const isStaticFile = pathname.startsWith("/_next") || pathname.includes(".");
// Skip middleware for API routes and static files
if (isApiRoute || isStaticFile) {
return NextResponse.next();
}
// Check for session cookie (simple check - actual auth happens in pages)
const hasSessionToken = request.cookies.has("authjs.session-token") ||
request.cookies.has("__Secure-authjs.session-token");
// Redirect to login if trying to access protected route without session
if (!hasSessionToken && !isPublicRoute) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
// Redirect to dashboard if authenticated user tries to access login
if (hasSessionToken && pathname === "/login") {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};