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)
}
}