Initial commit: Full project structure
- Backend: NestJS with Docker - Frontend: Next.js with Docker - Nginx configuration for reverse proxy - PostgreSQL setup - Docker compose for orchestration - Development environment configuration
This commit is contained in:
41
frontend/src/middleware.ts
Normal file
41
frontend/src/middleware.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
|
||||
import { NextResponse } from 'next/server';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
const publicRoutes = ['/', '/login', '/register', '/terms', '/privacy', '/forgot-password'];
|
||||
const authOnlyRoutes = ['/login', '/register']; // routes that should NOT be accessed when logged in
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
const token = request.cookies.get('accessToken')?.value;
|
||||
const isAuthenticated = !!token;
|
||||
|
||||
// Always allow public routes first
|
||||
if (publicRoutes.includes(pathname)) {
|
||||
// If user is already logged in and tries to access login/register → redirect to dashboard
|
||||
if (isAuthenticated && authOnlyRoutes.includes(pathname)) {
|
||||
return NextResponse.redirect(new URL('/today', request.url));
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// Protected routes: redirect to login if no token
|
||||
if (!isAuthenticated) {
|
||||
// Prevent loop: if somehow redirecting to login from login, just continue
|
||||
if (pathname === '/login') {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
const loginUrl = new URL('/login', request.url);
|
||||
loginUrl.searchParams.set('from', pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [
|
||||
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user