-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
36 lines (31 loc) · 1.07 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
import {
AUTHENTICATED_PATH,
NON_AUTHENTICATED_PATH,
} from '@/constants/pathname';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
export async function middleware(req: NextRequest) {
const session = await getToken({ req });
const { pathname } = req.nextUrl;
const redirectToHome = NextResponse.redirect(new URL('/', req.url));
// If the user is on a path that requires authentication and doesn't have a session, redirect to home
if (
!session &&
AUTHENTICATED_PATH.some((path) => pathname.startsWith(path))
) {
return redirectToHome;
}
// If the user is on a path that should not be accessed by authenticated users and has a session, redirect to home
if (
session &&
NON_AUTHENTICATED_PATH.some((path) => pathname.startsWith(path))
) {
return redirectToHome;
}
// Continue with the response if none of the conditions above are met
return NextResponse.next();
}
export const config = {
matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)',
};