Cookies can only be written in Server Actions or Route Handlers. Moved the write to proxy.ts where NextResponse.cookies.set is allowed. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
45 lines
1.4 KiB
TypeScript
45 lines
1.4 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import type { NextRequest } from 'next/server'
|
|
import { sessionOptions } from '@/lib/session'
|
|
|
|
const protectedRoutes = ['/dashboard', '/products', '/todos', '/settings', '/solo']
|
|
const authRoutes = ['/login', '/register']
|
|
|
|
const SOLO_ROUTE = /^\/products\/([^/]+)\/solo$/
|
|
const THIRTY_DAYS_SECONDS = 60 * 60 * 24 * 30
|
|
|
|
export function proxy(request: NextRequest) {
|
|
const path = request.nextUrl.pathname
|
|
const isProtected = protectedRoutes.some(r => path.startsWith(r))
|
|
const isAuthRoute = authRoutes.some(r => path.startsWith(r))
|
|
|
|
// Check cookie existence only — full session validation happens in layout.tsx
|
|
const hasSession = !!request.cookies.get(sessionOptions.cookieName)?.value
|
|
|
|
if (isProtected && !hasSession) {
|
|
return NextResponse.redirect(new URL('/login', request.url))
|
|
}
|
|
|
|
if (isAuthRoute && hasSession) {
|
|
return NextResponse.redirect(new URL('/dashboard', request.url))
|
|
}
|
|
|
|
const response = NextResponse.next()
|
|
|
|
// Remember last visited product for /solo redirect
|
|
const soloMatch = path.match(SOLO_ROUTE)
|
|
if (soloMatch) {
|
|
response.cookies.set('lastProductId', soloMatch[1], {
|
|
httpOnly: true,
|
|
sameSite: 'lax',
|
|
maxAge: THIRTY_DAYS_SECONDS,
|
|
path: '/',
|
|
})
|
|
}
|
|
|
|
return response
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
|
|
}
|