From 84171928cb67cf717ccdf1e843a6d67911f5db3b Mon Sep 17 00:00:00 2001 From: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Date: Tue, 10 Jun 2025 14:04:25 +0300 Subject: [PATCH] chore: enable disable rewrite for apiv2 selfhost (#21742) --- apps/api/v2/.env.example | 6 +++++- apps/api/v2/src/env.ts | 2 ++ .../api/v2/src/middleware/app.rewrites.middleware.ts | 12 +++++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/api/v2/.env.example b/apps/api/v2/.env.example index 6b5f3b8763..79dc011fc1 100644 --- a/apps/api/v2/.env.example +++ b/apps/api/v2/.env.example @@ -37,4 +37,8 @@ AXIOM_TOKEN= # INFO: 1 # WARN: 2 # ERROR: 3 -LOGGER_BRIDGE_LOG_LEVEL="1" \ No newline at end of file +LOGGER_BRIDGE_LOG_LEVEL="1" + +# 1: Rewrite /api/v2 to /v2 +# 0: Don't rewrite +REWRITE_API_V2_PREFIX="1" \ No newline at end of file diff --git a/apps/api/v2/src/env.ts b/apps/api/v2/src/env.ts index ac41f1d853..a2d289ab94 100644 --- a/apps/api/v2/src/env.ts +++ b/apps/api/v2/src/env.ts @@ -32,6 +32,8 @@ export type Environment = { AXIOM_TOKEN: string; STRIPE_TEAM_MONTHLY_PRICE_ID: string; IS_TEAM_BILLING_ENABLED: boolean; + // Used to enable/disable the rewrite of /api/v2 to /v2, active by default. + REWRITE_API_V2_PREFIX: string; }; export const getEnv = (key: K, fallback?: Environment[K]): Environment[K] => { diff --git a/apps/api/v2/src/middleware/app.rewrites.middleware.ts b/apps/api/v2/src/middleware/app.rewrites.middleware.ts index a69505797f..f80503de61 100644 --- a/apps/api/v2/src/middleware/app.rewrites.middleware.ts +++ b/apps/api/v2/src/middleware/app.rewrites.middleware.ts @@ -1,10 +1,11 @@ +import { getEnv } from "@/env"; import { Injectable, NestMiddleware } from "@nestjs/common"; import { Request, Response } from "express"; @Injectable() export class RewriterMiddleware implements NestMiddleware { use(req: Request, res: Response, next: () => void) { - if (req.url.startsWith("/api/v2")) { + if (shouldRewriteApiV2Prefix() && req.url.startsWith("/api/v2")) { req.url = req.url.replace("/api/v2", "/v2"); } if (req.url.startsWith("/v2/ee")) { @@ -16,3 +17,12 @@ export class RewriterMiddleware implements NestMiddleware { next(); } } + +const shouldRewriteApiV2Prefix = () => { + try { + // rewrite is active even if REWRITE_API_V2_PREFIX is not set + return getEnv("REWRITE_API_V2_PREFIX", "1") === "1"; + } catch (error) { + return true; + } +};