forked from Osama-Yusouf/BDIE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
53 lines (47 loc) · 1.67 KB
/
Copy pathmiddleware.ts
File metadata and controls
53 lines (47 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
/**
* Next.js Edge Middleware for route protection.
* Redirects unauthenticated users to /login and authenticated users away from auth pages.
*/
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const accessToken = req.cookies.get('access_token')?.value;
// 1. Define protected and public routes
const isAuthPage = pathname === '/login' || pathname === '/register' || pathname === '/';
const isDashboardPage = pathname.startsWith('/dashboard') ||
pathname.startsWith('/users') ||
pathname.startsWith('/simulations') ||
pathname.startsWith('/analysis') ||
pathname.startsWith('/notifications') ||
pathname.startsWith('/audit') ||
pathname.startsWith('/settings');
// 2. Redirect logic
if (!accessToken && isDashboardPage) {
const url = new URL('/login', req.url);
// Remember where they were trying to go
url.searchParams.set('callbackUrl', encodeURI(pathname));
return NextResponse.redirect(url);
}
if (accessToken && isAuthPage) {
return NextResponse.redirect(new URL('/dashboard', req.url));
}
return NextResponse.next();
}
/**
* Configure middleware to run on specific paths.
*/
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - screenshots (README screenshots)
* - public (static assets)
*/
'/((?!api|_next/static|_next/image|favicon.ico|screenshots|public).*)',
],
};