-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
31 lines (25 loc) · 963 Bytes
/
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
import { NextRequest, NextResponse } from 'next/server'
export async function middleware(req: NextRequest) {
const cocov_auth_token = req.cookies.get('cocov_auth_token')?.value
const SigninPage = '/auth/signin'
const route = req.nextUrl.pathname
const isPublicPage = route === SigninPage
const response = NextResponse.next()
if (!cocov_auth_token && !isPublicPage) {
// REDIRECT UNLOGGED USER TO THE SIGNIN PAGE
return NextResponse.redirect(new URL(SigninPage, req.url))
} else if (isPublicPage) {
// REDIRECT TO THE SIGNIN PAGE IF THE AUTH TOKEN IS INVALID
const isInvalidToken = req.nextUrl.searchParams.has('invalid_token')
if (isInvalidToken) {
response.cookies.delete('cocov_auth_token')
} else if (cocov_auth_token) {
return NextResponse.redirect(new URL('/', req.url))
}
return response
}
return response
}
export const config = {
matcher: ['/:path((?!api|static|.*\\..*|_next).*)'],
}