Add Next.js API route proxy to handle client-side API requests to backend

This commit is contained in:
TheMaddax 2025-10-28 08:01:22 -06:00
parent 6df5bd193a
commit cecfcfb620

View file

@ -0,0 +1,87 @@
import { NextRequest, NextResponse } from 'next/server';
// This catch-all API route proxies all /api/* requests to the backend
export async function GET(
request: NextRequest,
{ params }: { params: { path: string[] } }
) {
return proxyToBackend(request, params.path);
}
export async function POST(
request: NextRequest,
{ params }: { params: { path: string[] } }
) {
return proxyToBackend(request, params.path);
}
export async function PUT(
request: NextRequest,
{ params }: { params: { path: string[] } }
) {
return proxyToBackend(request, params.path);
}
export async function DELETE(
request: NextRequest,
{ params }: { params: { path: string[] } }
) {
return proxyToBackend(request, params.path);
}
async function proxyToBackend(request: NextRequest, pathSegments: string[]) {
const path = pathSegments.join('/');
const backendUrl = `http://backend:3001/api/${path}`;
// Get the search params from the original request
const searchParams = request.nextUrl.searchParams.toString();
const url = searchParams ? `${backendUrl}?${searchParams}` : backendUrl;
try {
// Forward the request to the backend
const headers: HeadersInit = {};
// Copy relevant headers
request.headers.forEach((value, key) => {
if (!key.startsWith('host') && !key.startsWith('connection')) {
headers[key] = value;
}
});
const options: RequestInit = {
method: request.method,
headers,
};
// Add body for POST, PUT, PATCH requests
if (['POST', 'PUT', 'PATCH'].includes(request.method)) {
const contentType = request.headers.get('content-type');
if (contentType?.includes('application/json')) {
options.body = JSON.stringify(await request.json());
} else if (contentType?.includes('multipart/form-data')) {
options.body = await request.formData();
} else {
options.body = await request.text();
}
}
const response = await fetch(url, options);
// Get response body
const data = await response.text();
// Return response with same status and headers
return new NextResponse(data, {
status: response.status,
headers: {
'Content-Type': response.headers.get('content-type') || 'application/json',
},
});
} catch (error) {
console.error('Proxy error:', error);
return NextResponse.json(
{ success: false, message: 'Failed to connect to backend' },
{ status: 500 }
);
}
}