From e092057dbe3d33db9d028abc789d5aaa1367a177 Mon Sep 17 00:00:00 2001 From: torbinus Date: Fri, 18 Sep 2026 10:22:53 +0200 Subject: [PATCH] Backend-Adresse zur Laufzeit statt fest im Image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Astro setzt PUBLIC_-Variablen beim Bauen ein, deshalb gehörte bisher jedes Frontend-Image zu genau einer Umgebung: Heimnetz, Testsystem und Produktion brauchten je einen eigenen Build. Jetzt liest der Server die Adresse beim Start aus der Umgebung und gibt sie als an den Browser weiter. MEDUSA_INTERNAL_URL erlaubt dem Frontend-Container zusätzlich den direkten Weg zum Backend, ohne Umweg über den Reverse Proxy. Ein Image passt damit überall, ein Adresswechsel ist eine Variable. Co-Authored-By: Claude Opus 5 (1M context) --- compose.prod.yml | 15 ++++++++- frontend/Dockerfile | 11 ++----- frontend/src/layouts/Layout.astro | 11 +++++++ frontend/src/lib/medusa.ts | 33 +++++++++++++++++-- frontend/src/pages/bestellung/danke.astro | 4 +-- .../src/pages/konto/bestellungen/[id].astro | 4 +-- 6 files changed, 63 insertions(+), 15 deletions(-) diff --git a/compose.prod.yml b/compose.prod.yml index 8c81e2b..99a6762 100644 --- a/compose.prod.yml +++ b/compose.prod.yml @@ -14,7 +14,12 @@ # sudo mkdir -p /srv/place4bees/{postgres,redis,uploads} # # Pflichtvariablen: IMAGE_TAG, POSTGRES_PASSWORD, JWT_SECRET, COOKIE_SECRET, -# MEDUSA_BACKEND_URL, STORE_CORS, ADMIN_CORS, AUTH_CORS +# MEDUSA_BACKEND_URL, PUBLISHABLE_KEY, +# STORE_CORS, ADMIN_CORS, AUTH_CORS +# +# MEDUSA_BACKEND_URL ist die Adresse, unter der der Browser das Backend +# erreicht. Sie steckt nicht mehr im Image — ein Wechsel ist nur noch eine +# Variable und ein Neustart des Stacks. name: place4bees @@ -113,5 +118,13 @@ services: restart: unless-stopped depends_on: - backend + environment: + # Die Adresse, die der Browser erreichen muss. Ein Wechsel ist damit + # eine Variable, kein neues Image. + PUBLIC_MEDUSA_BACKEND_URL: ${MEDUSA_BACKEND_URL} + PUBLIC_MEDUSA_PUBLISHABLE_KEY: ${PUBLISHABLE_KEY} + # Der Weg innerhalb des Stacks — spart den Umweg über den Reverse Proxy + # und funktioniert auch, wenn die öffentliche Adresse noch nicht steht. + MEDUSA_INTERNAL_URL: http://backend:9001 ports: - "${FRONTEND_PORT:-4321}:4321" diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 2ba215d..6f40ded 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -3,9 +3,9 @@ # Der Node-Adapter läuft im Modus "standalone", das Ergebnis ist also ein # eigener Server unter dist/server/entry.mjs. # -# Achtung bei der Backend-Adresse: Astro setzt PUBLIC_-Variablen schon beim -# Bauen fest ein, nicht erst beim Start. Ein Image gehört deshalb immer zu -# genau einer Umgebung — für Test und Produktion wird zweimal gebaut. +# Die Adresse des Backends steckt bewusst nicht im Image. Sie wird beim Start +# aus PUBLIC_MEDUSA_BACKEND_URL gelesen und an den Browser weitergereicht — +# ein Image passt damit für Heimnetz, Testsystem und Produktion. FROM node:22-bookworm-slim AS build WORKDIR /app @@ -13,11 +13,6 @@ WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci -ARG PUBLIC_MEDUSA_BACKEND_URL -ARG PUBLIC_MEDUSA_PUBLISHABLE_KEY -ENV PUBLIC_MEDUSA_BACKEND_URL=$PUBLIC_MEDUSA_BACKEND_URL -ENV PUBLIC_MEDUSA_PUBLISHABLE_KEY=$PUBLIC_MEDUSA_PUBLISHABLE_KEY - COPY . . RUN npm run build diff --git a/frontend/src/layouts/Layout.astro b/frontend/src/layouts/Layout.astro index 7cfee2d..57dba95 100644 --- a/frontend/src/layouts/Layout.astro +++ b/frontend/src/layouts/Layout.astro @@ -39,6 +39,14 @@ const isLoggedIn = Boolean(Astro.cookies.get("customer_jwt")?.value); // stable section path so both domains consolidate onto one indexable URL. const canonicalPath = pathname === "/" ? layers[layer].homeHref : pathname; const canonicalUrl = new URL(canonicalPath, PRIMARY_DOMAIN).toString(); + +// Die öffentliche Adresse des Backends — die, die der Browser erreichen muss. +// Sie wird zur Laufzeit gelesen und unten als mitgegeben, damit ein +// Image für jede Umgebung passt. MEDUSA_INTERNAL_URL gilt nur serverseitig. +const medusaPublicUrl = + process.env.PUBLIC_MEDUSA_BACKEND_URL ?? import.meta.env.PUBLIC_MEDUSA_BACKEND_URL ?? ""; +const medusaPublishableKey = + process.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? ""; --- @@ -48,6 +56,9 @@ const canonicalUrl = new URL(canonicalPath, PRIMARY_DOMAIN).toString(); {title} · {COMPANY_NAME} + {/* Woher der Browser seine Daten holt. Siehe medusaConfig() in lib/medusa.ts. */} + + diff --git a/frontend/src/lib/medusa.ts b/frontend/src/lib/medusa.ts index ddd391c..c7d586b 100644 --- a/frontend/src/lib/medusa.ts +++ b/frontend/src/lib/medusa.ts @@ -1,9 +1,38 @@ import { varietyName } from "./varieties"; -const BACKEND_URL = import.meta.env.PUBLIC_MEDUSA_BACKEND_URL; -const PUBLISHABLE_KEY = import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY; +/** + * Adresse und Schlüssel des Backends stehen bewusst nicht mehr fest im Build. + * Sonst gehört jedes Image zu genau einer Umgebung, und ein Adresswechsel + * heißt neu bauen, hochladen, neu ausrollen. + * + * Auf dem Server kommen die Werte aus der Umgebung, im Browser aus zwei + * -Tags, die das Layout mitschickt. Damit passt ein Image für Heimnetz, + * Testsystem und Produktion. + */ +function meta(name: string): string | undefined { + return document.querySelector(`meta[name="${name}"]`)?.content || undefined; +} + +export function medusaConfig(): { url: string; key: string } { + if (typeof document !== "undefined") { + return { + url: meta("medusa-backend-url") ?? "", + key: meta("medusa-publishable-key") ?? "", + }; + } + + const env = typeof process !== "undefined" ? process.env : ({} as Record); + return { + // Innerhalb des Containers geht es direkt zum Backend, ohne den Umweg + // über den Reverse Proxy. Fehlt der Wert, gilt die öffentliche Adresse. + url: env.MEDUSA_INTERNAL_URL || env.PUBLIC_MEDUSA_BACKEND_URL || import.meta.env.PUBLIC_MEDUSA_BACKEND_URL || "", + key: env.PUBLIC_MEDUSA_PUBLISHABLE_KEY || import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY || "", + }; +} export async function medusaFetch(path: string, init?: RequestInit) { + const { url: BACKEND_URL, key: PUBLISHABLE_KEY } = medusaConfig(); + const res = await fetch(`${BACKEND_URL}${path}`, { ...init, headers: { diff --git a/frontend/src/pages/bestellung/danke.astro b/frontend/src/pages/bestellung/danke.astro index ded24f6..05c3f15 100644 --- a/frontend/src/pages/bestellung/danke.astro +++ b/frontend/src/pages/bestellung/danke.astro @@ -58,8 +58,8 @@ import Layout from "../../layouts/Layout.astro"; // The invoice route needs the publishable API key header, which a // plain link click can't send — fetch it ourselves and open the // resulting PDF as a blob instead. - const backendUrl = import.meta.env.PUBLIC_MEDUSA_BACKEND_URL; - const key = import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY; + const backendUrl = document.querySelector('meta[name="medusa-backend-url"]').content; + const key = document.querySelector('meta[name="medusa-publishable-key"]').content; const res = await fetch(`${backendUrl}/store/orders/${order.id}/invoice`, { headers: { "x-publishable-api-key": key }, }); diff --git a/frontend/src/pages/konto/bestellungen/[id].astro b/frontend/src/pages/konto/bestellungen/[id].astro index c6dcfba..ec180da 100644 --- a/frontend/src/pages/konto/bestellungen/[id].astro +++ b/frontend/src/pages/konto/bestellungen/[id].astro @@ -185,8 +185,8 @@ const allLabels = order.fulfillments.flatMap((f) => f.labels); const displayId = invoiceButton.dataset.displayId; invoiceButton.disabled = true; try { - const backendUrl = import.meta.env.PUBLIC_MEDUSA_BACKEND_URL; - const key = import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY; + const backendUrl = document.querySelector('meta[name="medusa-backend-url"]').content; + const key = document.querySelector('meta[name="medusa-publishable-key"]').content; const res = await fetch(`${backendUrl}/store/orders/${orderId}/invoice`, { headers: { "x-publishable-api-key": key }, });