fix: add SPA fallback for client-side routing
Some checks failed
CI / Lint, Typecheck, Test & Build (push) Has been cancelled

NestJS was returning 404 JSON for SPA routes like /dashboard/search
because ServeStaticModule couldn't find a matching file and the request
fell through to NestJS router. Add explicit catch-all GET handler after
app.init() to serve index.html for non-API routes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-05 14:22:08 +00:00
parent f2b387850e
commit 90ad75701d

View File

@@ -3,12 +3,14 @@ import "./telemetry/tracing"; // MUST be first — instruments modules before th
import { NestFactory } from "@nestjs/core";
import { ConfigService } from "@nestjs/config";
import helmet from "helmet";
import { join } from "path";
import type { Request, Response, NextFunction } from "express";
import type { NestExpressApplication } from "@nestjs/platform-express";
import { AppModule } from "./app.module";
import { fileUploadValidation } from "./common/middleware/file-upload-validation.middleware";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>("port", 4000);
@@ -52,6 +54,18 @@ async function bootstrap() {
next();
});
await app.init();
// SPA fallback: serve index.html for non-API GET requests
const webDistPath = join(__dirname, "..", "..", "web", "dist");
const expressApp = app.getHttpAdapter().getInstance();
expressApp.get("*", (req: Request, res: Response, next: NextFunction) => {
if (req.path.startsWith("/api")) {
return next();
}
res.sendFile(join(webDistPath, "index.html"));
});
await app.listen(port);
console.log(`API running on http://localhost:${port}`);
}