-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
37 lines (30 loc) · 979 Bytes
/
middleware.ts
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
// === middleware.ts ===
import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
// Define public paths that don't require authentication
const publicPaths = ['/', '/auth/signin', '/auth/signup'];
const isPublicPath = publicPaths.includes(path);
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
// Redirect authenticated users away from auth pages
if (isPublicPath && token) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
// Redirect unauthenticated users to signin
if (!isPublicPath && !token) {
return NextResponse.redirect(new URL('/auth/signin', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
'/',
'/dashboard/:path*',
'/auth/:path*'
]
};