33 lines
1 KiB
Markdown
33 lines
1 KiB
Markdown
# Patroon: Middleware (route protection)
|
|
|
|
```ts
|
|
// middleware.ts
|
|
import { NextResponse } from 'next/server'
|
|
import type { NextRequest } from 'next/server'
|
|
import { getIronSession } from 'iron-session'
|
|
import { SessionData, sessionOptions } from '@/lib/session'
|
|
|
|
const protectedRoutes = ['/dashboard', '/products', '/todos', '/settings']
|
|
const authRoutes = ['/login', '/register']
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const response = NextResponse.next()
|
|
const session = await getIronSession<SessionData>(request.cookies, sessionOptions)
|
|
|
|
const isProtected = protectedRoutes.some(r => request.nextUrl.pathname.startsWith(r))
|
|
const isAuthRoute = authRoutes.some(r => request.nextUrl.pathname.startsWith(r))
|
|
|
|
if (isProtected && !session.userId) {
|
|
return NextResponse.redirect(new URL('/login', request.url))
|
|
}
|
|
if (isAuthRoute && session.userId) {
|
|
return NextResponse.redirect(new URL('/dashboard', request.url))
|
|
}
|
|
|
|
return response
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
|
|
}
|
|
```
|