forked from boundlessfi/boundless
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
50 lines (41 loc) · 1.56 KB
/
middleware.ts
File metadata and controls
50 lines (41 loc) · 1.56 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
import { auth } from '@/auth';
import { NextResponse } from 'next/server';
// Define protected routes that require authentication
const protectedRoutes = ['/dashboard', '/user', '/projects', '/admin'];
// Define auth routes (routes that should redirect to dashboard if already authenticated)
const authRoutes = ['/auth/signin', '/auth/signup', '/auth/forgot-password'];
export default auth(req => {
const { pathname } = req.nextUrl;
const isAuthenticated = !!req.auth;
// Check if the route is protected
const isProtectedRoute = protectedRoutes.some(route =>
pathname.startsWith(route)
);
// Check if the route is an auth route
const isAuthRoute = authRoutes.some(route => pathname.startsWith(route));
// Redirect authenticated users away from auth routes
if (isAuthRoute && isAuthenticated) {
return NextResponse.redirect(new URL('/user', req.url));
}
// Redirect unauthenticated users to signin for protected routes
if (isProtectedRoute && !isAuthenticated) {
const signinUrl = new URL('/auth/signin', req.url);
signinUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(signinUrl);
}
// Allow all other requests to proceed
return NextResponse.next();
});
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)
* - public folder
*/
'/((?!api|_next/static|_next/image|favicon.ico|public).*)',
],
};