middleware.ts (1247B)
1 import { NextResponse } from "next/server"; 2 import type { NextRequest } from "next/server"; 3 import { User } from "./lib/auth"; 4 5 export function middleware(req: NextRequest) { 6 const session = req.cookies.get("d4all_session"); 7 8 // If not root url check if the session cookie is set, and check if the session expired. If it did redirect to /refresh 9 if (req.nextUrl.pathname !== "/" && session) { 10 console.log("Session cookie found:", session.value); 11 const sessionData: User = JSON.parse(session.value); 12 const currentTime = Math.floor(Date.now() / 1000); // Current time in seconds 13 14 // Check if the session has expired 15 if (sessionData.openidExpiration && sessionData.openidExpiration < currentTime) { 16 console.log("Session expired, redirecting to /refresh"); 17 return NextResponse.redirect(new URL("/refresh", req.url)); 18 } 19 } 20 21 // Redirect to login if session is missing on protected routes 22 if (!session && req.nextUrl.pathname.startsWith("/dashboard")) { 23 return NextResponse.redirect(new URL("/login", req.url)); 24 } 25 26 return NextResponse.next(); 27 } 28 29 export const config = { 30 matcher: ["/dashboard/:path*"], // Add other protected routes here 31 };