Spaces:
Running
Running
| import type { NextRequest } from 'next/server'; | |
| export const runtime = 'nodejs'; | |
| export const dynamic = 'force-dynamic'; | |
| type RouteContext = { | |
| params: Promise<{ path: string[] }>; | |
| }; | |
| const BACKEND_INTERNAL_URL = process.env.BACKEND_INTERNAL_URL || 'http://127.0.0.1:8000'; | |
| const HOP_BY_HOP_HEADERS = new Set([ | |
| 'connection', | |
| 'content-encoding', | |
| 'content-length', | |
| 'host', | |
| 'keep-alive', | |
| 'proxy-authenticate', | |
| 'proxy-authorization', | |
| 'te', | |
| 'trailer', | |
| 'transfer-encoding', | |
| 'upgrade', | |
| ]); | |
| async function proxyRequest(request: NextRequest, context: RouteContext): Promise<Response> { | |
| const { path } = await context.params; | |
| const upstream = new URL(`/${path.join('/')}`, BACKEND_INTERNAL_URL); | |
| upstream.search = request.nextUrl.search; | |
| const headers = new Headers(request.headers); | |
| for (const header of HOP_BY_HOP_HEADERS) { | |
| headers.delete(header); | |
| } | |
| const response = await fetch(upstream, { | |
| method: request.method, | |
| headers, | |
| body: request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body, | |
| cache: 'no-store', | |
| duplex: 'half', | |
| } as RequestInit & { duplex: 'half' }); | |
| const responseHeaders = new Headers(response.headers); | |
| for (const header of HOP_BY_HOP_HEADERS) { | |
| responseHeaders.delete(header); | |
| } | |
| return new Response(response.body, { | |
| status: response.status, | |
| statusText: response.statusText, | |
| headers: responseHeaders, | |
| }); | |
| } | |
| export const GET = proxyRequest; | |
| export const POST = proxyRequest; | |
| export const PUT = proxyRequest; | |
| export const PATCH = proxyRequest; | |
| export const DELETE = proxyRequest; | |
| export const HEAD = proxyRequest; | |
| export const OPTIONS = proxyRequest; | |