-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
37 lines (29 loc) · 1.14 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
37
import { NextRequest, NextResponse } from 'next/server';
export const middleware = async (request: NextRequest) => {
const publicRoutes = ['/sign-in'];
const excludePattern = /^\/(?!api\/public|_next\/static|_next\/image|images|favicon.ico).*/;
if (!excludePattern.test(request.nextUrl.pathname)) {
return NextResponse.next();
}
const isRootRoute = request.nextUrl.pathname === '/';
const token = request.cookies.get('token')?.value;
// console.log('Middleware Token :>>', token);
if (isRootRoute || publicRoutes.includes(request.nextUrl.pathname)) {
return NextResponse.next();
}
if (!token) {
const url = request.nextUrl.clone();
url.searchParams.set('next', url.pathname);
url.pathname = '/sign-in';
return NextResponse.redirect(url);
}
// Verify token...
const authResponse = await fetch(`${request.nextUrl.protocol}//${request.nextUrl.host}/api/public/validateToken?token=${token}`);
if (!authResponse.ok) {
const url = request.nextUrl.clone();
url.searchParams.set('next', url.pathname);
url.pathname = '/sign-in';
return NextResponse.redirect(url);
}
return NextResponse.next();
}