/** * Next.js middleware to protect admin routes. * - Runs for paths matched by the config `matcher` (see bottom). * - Checks for the `refreshToken` cookie; if missing, redirects to `/login` before any page renders. * - No manual import/use needed—Next.js automatically executes this for matching requests. */ import { NextRequest, NextResponse } from 'next/server' // Move accessToken to HttpOnly cookie in future for better security // Backend sets 'refreshToken' cookie on login; use it as auth presence const AUTH_COOKIES = ['refreshToken'] export function middleware(req: NextRequest) { const { pathname } = req.nextUrl // Only guard admin routes if (pathname.startsWith('/admin')) { const hasAuthCookie = AUTH_COOKIES.some((name) => !!req.cookies.get(name)?.value) if (!hasAuthCookie) { const loginUrl = new URL('/login', req.url) return NextResponse.redirect(loginUrl) } } return NextResponse.next() } export const config = { matcher: ['/admin/:path*'], }