-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
74 lines (61 loc) · 1.76 KB
/
middleware.ts
File metadata and controls
74 lines (61 loc) · 1.76 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { MiddlewareConfig, NextRequest, NextResponse } from 'next/server';
const publicRoutes = [
{
path: '/',
whenAuthenticated: 'next',
},
{
path: '/sign-in',
whenAuthenticated: 'redirect',
},
{
path: '/product',
whenAuthenticated: 'next',
},
{
path: '/category',
whenAuthenticated: 'next',
},
{
path: '/about',
whenAuthenticated: 'next',
},
] as const;
const REDIRECT_WHEN_AUTHENTICATED = '/sign-in';
export function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
if (path.match(/\.(jpg|jpeg|png|gif|svg|webp|css|js|ico|json)$/i)) {
return NextResponse.next();
}
const publicRoute = publicRoutes.find((route) => {
if (path.startsWith('/product/') || path.startsWith('/category')) {
return path.startsWith(route.path);
}
return route.path === path;
});
const authToken = request.cookies.get('access_token');
if (!authToken && publicRoute) {
return NextResponse.next();
}
if (!authToken && !publicRoute) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = REDIRECT_WHEN_AUTHENTICATED;
return NextResponse.redirect(redirectUrl);
}
if (
authToken &&
publicRoute &&
publicRoute.whenAuthenticated === 'redirect'
) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = '/';
return NextResponse.redirect(redirectUrl);
}
if (authToken && !publicRoute) {
return NextResponse.next();
}
return NextResponse.next();
}
export const config: MiddlewareConfig = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};