-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
28 lines (22 loc) · 885 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
import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
export const middleware = async (request: NextRequest) => {
const publicRoutes = [/\/invoices\/view/];
const token = await getToken({ req: request });
const isRootRoute = request.nextUrl.pathname === '/';
const excludePattern =
/^\/(?!api|auth|api\/register|_next\/static|_next\/image|images|assets|favicon.ico|invoices\/view\/[a-zA-Z0-9]{12}).*/;
if (!excludePattern.test(request.nextUrl.pathname) || isRootRoute) {
return NextResponse.next();
}
if (publicRoutes.some(pattern => pattern.test(request.nextUrl.pathname))) {
return NextResponse.next();
}
if (!token) {
const url = request.nextUrl.clone();
url.searchParams.set('callbackUrl', url.pathname);
url.pathname = '/auth/sign-in';
return NextResponse.redirect(url);
}
return NextResponse.next();
};