xpeditis2.0/apps/frontend/middleware.ts
David-Henri ARNAUD b31d325646 feature phase 2
2025-10-10 15:07:05 +02:00

37 lines
1.0 KiB
TypeScript

/**
* Middleware
*
* Protects routes that require authentication
*/
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const publicPaths = ['/', '/login', '/register', '/forgot-password', '/reset-password', '/verify-email'];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if path is public
const isPublicPath = publicPaths.some((path) => pathname.startsWith(path));
// Get token from cookies or headers
const token = request.cookies.get('accessToken')?.value;
// Redirect to login if accessing protected route without token
if (!isPublicPath && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Redirect to dashboard if accessing public auth pages while logged in
if (isPublicPath && token && pathname !== '/') {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};