fix: add Next.js API route handler to proxy with correct host headers

This commit is contained in:
Erik Silva
2025-12-09 02:24:56 -03:00
parent 9ece6e88fe
commit fc310c0616
3 changed files with 112 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ package middleware
import (
"context"
"log"
"net/http"
"strings"
@@ -17,7 +18,16 @@ const SubdomainKey tenantContextKey = "subdomain"
func TenantDetector(tenantRepo *repository.TenantRepository) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := r.Host
// Get host from X-Forwarded-Host header (set by Next.js proxy) or Host header
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Header.Get("X-Original-Host")
}
if host == "" {
host = r.Host
}
log.Printf("TenantDetector: host = %s (from headers), path = %s", host, r.RequestURI)
// Extract subdomain
// Examples:
@@ -39,6 +49,8 @@ func TenantDetector(tenantRepo *repository.TenantRepository) func(http.Handler)
}
}
log.Printf("TenantDetector: extracted subdomain = %s", subdomain)
// Add subdomain to context
ctx := context.WithValue(r.Context(), SubdomainKey, subdomain)
@@ -46,7 +58,10 @@ func TenantDetector(tenantRepo *repository.TenantRepository) func(http.Handler)
if subdomain != "" && subdomain != "dash" && subdomain != "api" && subdomain != "localhost" {
tenant, err := tenantRepo.FindBySubdomain(subdomain)
if err == nil && tenant != nil {
log.Printf("TenantDetector: found tenant %s for subdomain %s", tenant.ID.String(), subdomain)
ctx = context.WithValue(ctx, TenantIDKey, tenant.ID.String())
} else {
log.Printf("TenantDetector: tenant not found for subdomain %s (err=%v)", subdomain, err)
}
}

View File

@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest, { params }: { params: { path: string[] } }) {
const path = params.path?.join("/") || "";
const token = req.headers.get("authorization");
const host = req.headers.get("host");
try {
const response = await fetch(`http://backend:8080/api/${path}${req.nextUrl.search}`, {
method: "GET",
headers: {
"Authorization": token || "",
"Content-Type": "application/json",
"X-Forwarded-Host": host || "",
"X-Original-Host": host || "",
},
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
console.error("API proxy error:", error);
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}
export async function PUT(req: NextRequest, { params }: { params: { path: string[] } }) {
const path = params.path?.join("/") || "";
const token = req.headers.get("authorization");
const host = req.headers.get("host");
const body = await req.json();
try {
const response = await fetch(`http://backend:8080/api/${path}${req.nextUrl.search}`, {
method: "PUT",
headers: {
"Authorization": token || "",
"Content-Type": "application/json",
"X-Forwarded-Host": host || "",
"X-Original-Host": host || "",
},
body: JSON.stringify(body),
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
console.error("API proxy error:", error);
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}
export async function POST(req: NextRequest, { params }: { params: { path: string[] } }) {
const path = params.path?.join("/") || "";
const token = req.headers.get("authorization");
const host = req.headers.get("host");
const body = await req.json();
try {
const response = await fetch(`http://backend:8080/api/${path}${req.nextUrl.search}`, {
method: "POST",
headers: {
"Authorization": token || "",
"Content-Type": "application/json",
"X-Forwarded-Host": host || "",
"X-Original-Host": host || "",
},
body: JSON.stringify(body),
});
const data = await response.json();
return NextResponse.json(data, { status: response.status });
} catch (error) {
console.error("API proxy error:", error);
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}

View File

@@ -10,10 +10,29 @@ const nextConfig: NextConfig = {
{
source: "/api/:path*",
destination: "http://backend:8080/api/:path*",
has: [
{
type: "header",
key: "X-Forwarded-Host",
},
],
},
],
};
},
headers: async () => {
return [
{
source: "/api/:path*",
headers: [
{
key: "X-Forwarded-For",
value: "127.0.0.1",
},
],
},
];
},
};
export default nextConfig;