Scrum4Me/proxy.ts
Madhura68 1abbd4e5e4 fix: set lastProductId cookie in proxy instead of Server Component
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>
2026-04-26 17:25:17 +02:00

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).*)'],
}