-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.ts
58 lines (45 loc) · 1.81 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
48
49
50
51
52
53
54
55
56
57
58
import cookie from 'cookie'
import { jwtDecode } from 'jwt-decode'
import { NextRequest, NextResponse } from 'next/server'
import { requestBeryxApiToken } from '@/api-client/auth'
import { cookieAuthExpirationInSeconds, cookieAuthTokenName, cookieAuthTokenPreName } from '@/config/config'
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
let authToken: string | null
try {
const parsedCookies = cookie.parse(request.headers.get('cookie') ?? '')
if (process.env.NEXT_PUBLIC_BERYX_ENV === 'pre') {
authToken = parsedCookies[cookieAuthTokenPreName]
} else {
authToken = parsedCookies[cookieAuthTokenName]
}
const decoded = jwtDecode(authToken)
const currentTimestamp = Math.floor(Date.now() / 1000)
// Check if the decoded token has expired
if (!decoded || !('exp' in decoded) || decoded.exp === undefined || decoded.exp < currentTimestamp) {
// If the token has expired or decoded is null, clear it, so it is automatically renewed
authToken = null
}
} catch (error) {
authToken = null
}
if (!authToken) {
// Get a new token for this user
authToken = await requestBeryxApiToken()
const response = NextResponse.next()
// Set the cookie to expire in 12 hours
const expiryDate = new Date()
expiryDate.setSeconds(expiryDate.getSeconds() + cookieAuthExpirationInSeconds)
if (process.env.NEXT_PUBLIC_BERYX_ENV === 'pre') {
response.cookies.set(cookieAuthTokenPreName, authToken, { expires: expiryDate })
} else {
response.cookies.set(cookieAuthTokenName, authToken, { expires: expiryDate })
}
return response
}
return NextResponse.next()
}
// // See "Matching Paths" below to learn more
// export const config = {
// matcher: '/about/:path*',
// }