Files
app-admin/middleware.ts
2026-03-24 15:46:27 +03:00

33 lines
954 B
TypeScript

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const adminSession = request.cookies.get('admin_session');
// Allow requests to /login and static assets
if (
pathname.startsWith('/login') ||
pathname.startsWith('/_next') ||
pathname.startsWith('/api') ||
pathname === '/favicon.ico'
) {
// If already logged in and trying to access login page, redirect to home
if (pathname.startsWith('/login') && adminSession) {
return NextResponse.redirect(new URL('/', request.url));
}
return NextResponse.next();
}
// Redirect to /login if no session exists
if (!adminSession) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};