-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
26 lines (21 loc) · 877 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
import { getIronSession } from 'iron-session/edge'
import { ironOptions } from 'lib/ironSession'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export const middleware = async (req: NextRequest) => {
const res = NextResponse.next()
const session = await getIronSession(req, res, ironOptions)
const { pathname } = req.nextUrl
const { user } = session
const isApiRoute = pathname.includes('/api')
const isAuth = pathname.includes('/auth/')
const isUnauthorized = pathname.includes('/unauthorized')
if (!isAuth && !user && !isUnauthorized) {
if (isApiRoute) return NextResponse.redirect(new URL('/api/unauthorized', req.url))
else return NextResponse.redirect(new URL(`/auth/login?redirect=${pathname}`, req.url))
}
return res
}
export const config = {
matcher: ['/((?!_next|static|favicon.ico).*)']
}