Add global API prefix and route remapping for health checks in main.ts

This commit is contained in:
Первов Артем
2026-04-20 23:08:21 +03:00
parent c9eb7b0908
commit 20241b6ce1

View File

@@ -1,5 +1,6 @@
import { ValidationPipe } from '@nestjs/common';
import { RequestMethod, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import type { NextFunction, Request, Response } from 'express';
import { AppModule } from './app.module';
async function bootstrap() {
@@ -21,6 +22,25 @@ async function bootstrap() {
}),
);
// Prefer a stable `/api/*` surface in all environments.
// Some deployments/proxies may strip `/api` (e.g. nginx rewrite), so we also
// accept legacy non-prefixed routes by internally re-mapping them.
app.setGlobalPrefix('api', {
exclude: [{ path: 'health', method: RequestMethod.ALL }],
});
app.use((req: Request, _res: Response, next: NextFunction) => {
if (req.url === '/health' || req.url.startsWith('/health?') || req.url.startsWith('/api/')) {
return next();
}
if (req.url === '/api' || req.url.startsWith('/api?')) {
req.url = req.url.replace(/^\/api/, '/api/');
return next();
}
req.url = `/api${req.url.startsWith('/') ? '' : '/'}${req.url}`;
return next();
});
await app.listen(process.env.PORT ?? 3000);
}