-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
35 lines (30 loc) · 1.39 KB
/
Copy pathmiddleware.js
File metadata and controls
35 lines (30 loc) · 1.39 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
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { sessionOptions } from 'util/server-only/iron-session'
const isMaintenanceMode = process.env.NEXT_PUBLIC_MAINTENANCE_MODE === 'true'
export async function middleware(request) {
if (isMaintenanceMode) return NextResponse.redirect(`${request.nextUrl.origin}/maintenance`)
const authenticatedRoutes = ['/dashboard', '/settings']
const unauthenticatedRoutes = ['/login']
const session = await getIronSession(await cookies(), sessionOptions)
const token = session.token
const nextUrlPathname = request.nextUrl.pathname
const isAuthenticatedRoute = authenticatedRoutes.includes(nextUrlPathname)
const isUnauthenticatedRoute = unauthenticatedRoutes.includes(nextUrlPathname)
const isLoggedIn = Boolean(token)
// Don't redirect if session is empty (might be loading/transitioning)
// Only redirect if we have a definitive session that shows user is not logged in
if (isAuthenticatedRoute && !isLoggedIn && Object.keys(session).length > 0) {
return NextResponse.redirect(`${request.nextUrl.origin}/`, 302)
}
if (isUnauthenticatedRoute && isLoggedIn) {
return NextResponse.redirect(`${request.nextUrl.origin}/dashboard`, 302)
}
}
export const config = {
matcher: [
'/',
'/((?!api|_next/static|_next/image|favicon.ico|maintenance).*)',
]
}