Feat: Auto-resolve backend API base URL so Swarm redeploys no longer break proxied requests (fetch failed)

This commit is contained in:
ypratama committed 2026-09-02 11:15:16 +07:00
1 parent 856acdb6da
commit d492adb1ff
2 files changed
+86 -6

No files matched your search

+11 -6
View File
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from 'next/server';
import { getApiBase, resetApiBase } from '@/lib/api-base';
export async function GET(req: NextRequest, props: { params: Promise<{ route: string[] }> }) {
return handleProxy(req, props);
@@ -27,9 +28,10 @@ async function handleProxy(req: NextRequest, { params }: { params: Promise<{ rou
const url = new URL(req.url);
// INTERNAL_API_URL is read at RUNTIME (not baked at build time like NEXT_PUBLIC_*)
// This allows Docker Swarm / Portainer to set the backend URL dynamically
const localBase = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:3001';
// INTERNAL_API_URL is read at RUNTIME (not baked at build time like NEXT_PUBLIC_*).
// getApiBase() probes configured URLs and transparently falls back to the stable
// Swarm service alias if the configured one (e.g. task hostname ...-0) is unreachable.
const localBase = await getApiBase();
const destinationUrl = `${localBase}/api/${route}${url.search}`;
// Prepare headers
@@ -67,7 +69,7 @@ async function handleProxy(req: NextRequest, { params }: { params: Promise<{ rou
headers,
body: body,
cache: 'no-store', // Prevent Next.js from aggressively caching the backend response
// @ts-ignore
// @ts-expect-error - `duplex` is required for streaming bodies in older fetch typings
duplex: hasBody ? 'half' : undefined,
});
@@ -93,8 +95,11 @@ async function handleProxy(req: NextRequest, { params }: { params: Promise<{ rou
}
return nextResponse;
} catch (error: any) {
} catch (error) {
// Backend may have been redeployed (task hostname changed) — re-resolve next request.
resetApiBase();
console.error('[Proxy Error]', error);
return NextResponse.json({ ok: false, message: error.message }, { status: 500 });
const message = error instanceof Error ? error.message : 'Unknown proxy error';
return NextResponse.json({ ok: false, message }, { status: 500 });
}
}