From 7b6735be0efc0b1ae14b655179c6da44cbe002f7 Mon Sep 17 00:00:00 2001 From: seaznCode Date: Sun, 30 Nov 2025 19:50:33 +0100 Subject: [PATCH] feat: add middleware to protect admin routes with authentication check --- middleware.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 middleware.ts diff --git a/middleware.ts b/middleware.ts new file mode 100644 index 0000000..66921a7 --- /dev/null +++ b/middleware.ts @@ -0,0 +1,24 @@ +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*'], +}