-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
47 lines (38 loc) · 1.28 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
38
39
40
41
42
43
44
45
46
47
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyJWT } from '@/utils/jwt'
const publicPaths = ['/api/auth/login', '/api/auth/register', "/api/auth/guest", '/api/wallpapers', "/api/weather", "/api/quotes"]
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname
if (publicPaths.includes(path)) {
return NextResponse.next()
}
if (path.startsWith('/api/')) {
const token = request.cookies.get('token')?.value
if (!token) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
)
}
try {
const decoded = await verifyJWT(token)
const requestHeaders = new Headers(request.headers)
requestHeaders.set('userId', decoded.userId)
return NextResponse.next({
request: {
headers: requestHeaders,
},
})
} catch (error) {
return NextResponse.json(
{ error: 'Invalid or expired token' },
{ status: 401 }
)
}
}
return NextResponse.next()
}
export const config = {
matcher: ['/api/:path*']
}