-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
50 lines (42 loc) · 1.41 KB
/
middleware.js
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
import { NextResponse } from 'next/server'
import jwt from 'jsonwebtoken'
// This function can be marked `async` if using `await` inside
export function middleware(request) {
const path = request.nextUrl.pathname;
const isPublicPath = path === '/login' || path === '/signup';
const isDashboardPath = path === '/dashboard' || path.startsWith('/dashboard/');
const isRootPath = path === '' || path === '/';
const token = request.cookies.get('token')?.value || '';
if (token) {
try {
const decodedToken = jwt.decode(token);
const currentTime = Math.floor(Date.now() / 1000);
if (decodedToken.exp < currentTime) {
const response = NextResponse.redirect(new URL('/login', request.url));
response.cookies.delete('token');
return response;
}
} catch (error) {
console.error('Error decoding token:', error);
}
}
if(isPublicPath && token){
return NextResponse.redirect(new URL('/dashboard', request.url))
}
if(isRootPath && token) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
if((isDashboardPath) && !token){
return NextResponse.redirect(new URL('/login', request.url))
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/',
'/login',
'/signup',
'/dashboard',
'/dashboard/:path*'
]
}