-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
36 lines (28 loc) · 1.13 KB
/
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
// In middleware.ts
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import type { NextRequest } from 'next/server';
export async function middleware(req: NextRequest) {
const token = await getToken({ req });
const isAuthenticated = !!token;
const protectedPaths = ['/dashboard/page', '/dashboard/settings', '/dashboard/style'];
const authPaths = ['/auth/signin', '/auth/signup', '/auth/verify-request'];
const isProtectedRoute = protectedPaths.some((path) =>
req.nextUrl.pathname.startsWith(path)
);
const isAuthRoute = authPaths.some((path) =>
req.nextUrl.pathname.startsWith(path)
);
// Redirect to dashboard if authenticated and trying to access auth routes
if (isAuthenticated && isAuthRoute) {
return NextResponse.redirect(new URL('/dashboard/page', req.url));
}
// Redirect to signin if not authenticated and trying to access protected routes
if (isProtectedRoute && !isAuthenticated) {
return NextResponse.redirect(new URL('/auth/signin', req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/auth/:path*', '/dashboard/:path*'],
};