From a9e06a1b8915bbaf679ed5873f9bb1412d8ba333 Mon Sep 17 00:00:00 2001 From: Jakub Swierczek Date: Fri, 8 Mar 2024 10:49:48 +0100 Subject: [PATCH] Refactor server rewrites to accept function API URL as parameter The server rewrite rules are updated to use a provided "functionApiUrl" parameter instead of directly accessing the environment variable. This is achieved by getting the "functionApiUrl" from the request cookies. If no such cookie exists, it falls back to using the environment variable. This allows for more flexibility when setting the functions API URL. --- server/rewrites.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/server/rewrites.ts b/server/rewrites.ts index dc430e172a..a7933237c1 100644 --- a/server/rewrites.ts +++ b/server/rewrites.ts @@ -1,18 +1,18 @@ import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' -const rewriteRules = () => [ +const rewriteRules = (functionsApiUrl: string) => [ { source: '/api/triggers/:path*', - destination: `${process.env.FUNCTIONS_API_URL}/api/triggers/:path*`, + destination: `${functionsApiUrl}/api/triggers/:path*`, }, { source: '/api/triggers', - destination: `${process.env.FUNCTIONS_API_URL}/api/triggers`, + destination: `${functionsApiUrl}/api/triggers`, }, { source: '/api/migrations', - destination: `${process.env.FUNCTIONS_API_URL}/api/migrations`, + destination: `${functionsApiUrl}/api/migrations`, }, // ... other rules ] @@ -46,7 +46,10 @@ export function handleRewrite(request: NextRequest): NextResponse | null { if (!request.nextUrl.pathname.startsWith('/api')) { return null } - const rules = rewriteRules() + const functionApiUrlCookie = request.cookies.get('functionApiUrl') + + const functionApiUrl = functionApiUrlCookie?.value ?? process.env.FUNCTIONS_API_URL ?? '' + const rules = rewriteRules(functionApiUrl) for (const rule of rules) { const { regex, names } = parsePattern(rule.source) const matches = regex.exec(request.nextUrl.pathname)