DEV Community

Cover image for # Serving React as Static Files from NestJS — Te Underrated Production Pattern
César Zoleko
César Zoleko

Posted on

# Serving React as Static Files from NestJS — Te Underrated Production Pattern

Most tutorials about NestJS and React (or Vue, Angular, Svelte — pick your SPA) assume you'll deploy them separately: a Node server for the API, a CDN or Nginx for the frontend, maybe a reverse proxy gluing them together. That setup works fine, but it comes with real operational overhead — two services to monitor, two deploy pipelines to maintain, and a whole category of bugs that only exist because your frontend and backend live on different origins.

There's a simpler path. NestJS can serve your compiled SPA as static files, making the whole thing a single deployable unit. It's not widely discussed, and I think it deserves more attention.

Quick note on scope: this pattern works with any Single Page Application — React, Vue 3, Angular, Svelte, SolidJS, you name it. The moment your framework's build step produces a static dist/ folder (which they all do), NestJS can serve it. I'll use React + Vite throughout this article as a concrete example, but every concept applies directly to any other SPA.


What "serving static files" actually means here

When you run npm run build on any modern SPA (React, Vue, Angular, Svelte…), you get a dist/ folder containing index.html, bundled JS, CSS, and assets. That's it — no server required. Any HTTP server capable of serving files can host it.

NestJS ships with @nestjs/serve-static, a module that turns your NestJS app into exactly that kind of server. You point it at your build output, and NestJS handles the rest: serving index.html for unknown routes (client-side routing support), caching headers, MIME types, everything.

The result: one process, one port, one deployment.

Browser
  │
  ▼
NestJS (port 4200)
  ├── /api/*    → NestJS controllers (your REST API)
  └── /*        → React static files (index.html + assets)
Enter fullscreen mode Exit fullscreen mode

Setting it up

1. Install the module

npm install @nestjs/serve-static
Enter fullscreen mode Exit fullscreen mode

2. Configure the React build output

With Vite, point the build output directly into your NestJS project so the compiled app is always in the right place:

// front-app/vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: path.resolve(__dirname, '../back-app/client'),
    emptyOutDir: true,
  },
})
Enter fullscreen mode Exit fullscreen mode

3. Register ServeStaticModule in NestJS

// app.module.ts
import { Module } from '@nestjs/common'
import { ServeStaticModule } from '@nestjs/serve-static'
import { join } from 'path'

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'client'),
      renderPath: '/*',       // serve index.html for any unmatched route
      exclude: ['/api/(.*)'], // keep /api/* routed to controllers
    }),
    // ... your other modules
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

4. Prefix all your API routes

This is the critical step. Every NestJS controller must live under a common prefix so it never conflicts with static file serving:

// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  app.setGlobalPrefix('api')

  await app.listen(4200)
}
bootstrap()
Enter fullscreen mode Exit fullscreen mode

Your React app then calls /api/orders, /api/products — same origin, no CORS needed.

5. Development workflow — keep Vite's HMR

You still want two separate processes during development. Vite's HMR is too valuable to give up. Run NestJS on port 4200 and Vite on port 3000, with Vite proxying /api requests to the backend:

// vite.config.ts (dev only)
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:4200',
        changeOrigin: true,
      },
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

In development, Vite serves the frontend. In production, NestJS serves the compiled output. The code itself — every fetch('/api/...') call — stays identical.


The advantages that actually matter in production

Same-origin requests — cookies and CSRF just work

This is the biggest win and the one most people overlook.

When your frontend and backend share the same origin (https://yourdomain.com), cookies are sent automatically with every request. Session-based authentication, CSRF double-submit patterns, SameSite: strict cookies — all of it works without any extra configuration.

With a split deployment you need to:

  • Configure CORS (Access-Control-Allow-Origin, credentials: true)
  • Align cookie domains and SameSite policies across origins
  • Set credentials: 'include' on every fetch call
  • Accept that SameSite: strict is off the table

Each one of these is a potential footgun. A concrete example: in a session + CSRF setup (like csrf-csrf), the token validation ties the CSRF token to the session ID. With same-origin, the session cookie arrives with every request automatically. With cross-origin, you're one misconfigured allowedOrigins away from a 403 in production that only manifests after a page refresh.

One service to deploy and monitor

A typical split setup means:

  • Two Docker images, two build pipelines
  • Two services in docker-compose.yml or Kubernetes manifests
  • A reverse proxy (Nginx, Traefik) sitting in front of both
  • Logs and metrics spread across multiple services

With the unified approach:

# docker-compose.yml — that's the whole file
services:
  app:
    build: .
    ports:
      - "4200:4200"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=${DATABASE_URL}
Enter fullscreen mode Exit fullscreen mode

One image. One service. One set of logs. One health check endpoint.

A clean multi-stage Dockerfile

FROM node:20-alpine AS frontend-build
WORKDIR /app/front-app
COPY front-app/package*.json ./
RUN npm ci
COPY front-app/ .
RUN npm run build
# Vite outputs to ../back-app/client (configured in vite.config.ts)

FROM node:20-alpine AS backend-build
WORKDIR /app/back-app
COPY back-app/package*.json ./
RUN npm ci
COPY back-app/ .
COPY --from=frontend-build /app/back-app/client ./client
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=backend-build /app/back-app/dist ./dist
COPY --from=backend-build /app/back-app/client ./client
COPY --from=backend-build /app/back-app/node_modules ./node_modules
COPY back-app/package.json .

EXPOSE 4200
CMD ["node", "dist/main"]
Enter fullscreen mode Exit fullscreen mode

No Nginx config. No reverse proxy. The Node process handles everything.

No environment-specific frontend builds

In a split deployment, your React app needs to know the API URL at build time — a VITE_API_URL env variable baked into the bundle. That URL must match wherever you actually deployed the backend. Get it wrong and you're shipping a build that points at the wrong server, or worse, at localhost.

With unified serving, the API is always at the same origin. No VITE_API_URL to manage:

// same line, every environment — staging, preprod, production
const response = await fetch('/api/orders')
Enter fullscreen mode Exit fullscreen mode

The same build artifact works everywhere. No environment-specific rebuilds.

Static asset caching with Vite's content hashes

Vite hashes all asset filenames by default (main.a3f2b1.js). This means you can apply aggressive caching headers safely — browsers will only re-fetch when the content actually changes:

ServeStaticModule.forRoot({
  rootPath: join(__dirname, '..', 'client'),
  serveStaticOptions: {
    setHeaders: (res, filePath) => {
      if (/\.(js|css|png|jpg|svg|woff2)$/.test(filePath)) {
        res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
      }
    },
  },
}),
Enter fullscreen mode Exit fullscreen mode

index.html gets no cache header (or a short one), so deployments propagate immediately while assets stay cached on the client indefinitely.


When to use it — and when not to

Scenario Recommendation
Single NestJS app + single React frontend ✅ Unified serving
Session-based auth or strict CSRF ✅ Unified serving (same-origin is a hard win)
Small to medium team, monolith deployment ✅ Unified serving
Multiple frontend apps sharing the same backend ❌ Split deployment
Frontend needs global CDN edge caching ❌ Split deployment
Microservices backend ❌ Split deployment
Independent scaling of frontend and backend ❌ Split deployment

Why you don't see this pattern often

The industry default of "separate everything" made sense when teams were large, traffic was high, and independent scaling was a priority from day one. That mindset spread, became the tutorial default, and stuck.

There's also a perception issue: serving static files from an API server feels wrong to people who think of Node as "not a real web server." That mental model is outdated. Node handles static file serving perfectly well for the vast majority of projects, and @nestjs/serve-static is built exactly for this use case.

The result is that a genuinely useful, operationally simple pattern gets overlooked in favour of more complex setups that most projects don't need.


Closing thoughts

Serving React from NestJS removes an entire class of cross-origin problems, collapses your deployment to a single container, and makes local-to-production parity easy to maintain. The @nestjs/serve-static module handles the hard parts. The rest is pointing it at a dist/ folder.

It's not the flashiest architecture. In production, that's usually the point.


Have you tried this pattern in a real project? Curious about the tradeoffs you ran into — drop a comment below.


Tags: #nestjs #react #vue #angular #spa #typescript #webdev #nodejs #devops #javascript

Top comments (0)