import type { NextRequest } from 'next/server'; /** * Single origin proxy: the browser only ever talks to the web origin, and everything * under /api is forwarded to the API container. Cookies stay first party, so there is * no CORS anywhere in v1. * * SPEC-GAP: SPEC.md section 2 specifies Next rewrites for this. Next bakes rewrite * destinations into the build manifest, which would make API_INTERNAL_URL a build time * value and stop one image from running in both compose and k8s. A route handler reads * it per request instead, which is what "all configuration via .env" requires. */ export const dynamic = 'force-dynamic'; /** Set by the proxy or the runtime, never forwarded verbatim. */ const STRIPPED_REQUEST_HEADERS = new Set([ 'host', 'connection', 'content-length', 'transfer-encoding', 'accept-encoding', ]); const STRIPPED_RESPONSE_HEADERS = new Set(['content-encoding', 'content-length', 'transfer-encoding']); function apiBaseUrl(): string { return (process.env['API_INTERNAL_URL'] ?? 'http://localhost:4000').replace(/\/$/, ''); } async function proxy(request: NextRequest): Promise { const incoming = new URL(request.url); const target = `${apiBaseUrl()}${incoming.pathname}${incoming.search}`; const headers = new Headers(); request.headers.forEach((value, key) => { if (!STRIPPED_REQUEST_HEADERS.has(key.toLowerCase())) headers.set(key, value); }); const hasBody = request.method !== 'GET' && request.method !== 'HEAD'; const upstream = await fetch(target, { method: request.method, headers, redirect: 'manual', ...(hasBody ? { body: request.body, duplex: 'half' } : {}), } as RequestInit & { duplex?: 'half' }); const responseHeaders = new Headers(); upstream.headers.forEach((value, key) => { const name = key.toLowerCase(); if (name === 'set-cookie') return; if (!STRIPPED_RESPONSE_HEADERS.has(name)) responseHeaders.set(key, value); }); // Session and CSRF cookies arrive as several Set-Cookie headers and must stay separate. for (const cookie of upstream.headers.getSetCookie()) { responseHeaders.append('set-cookie', cookie); } return new Response(upstream.body, { status: upstream.status, headers: responseHeaders }); } export const GET = proxy; export const POST = proxy; export const PUT = proxy; export const PATCH = proxy; export const DELETE = proxy; export const HEAD = proxy; export const OPTIONS = proxy;