How do you build and serve a React or Vue frontend in production?
IntermediateConceptNode.js builds (npm, package.json)
Answer
Short answer
Run npm ci && npm run build, which compiles and bundles the app into static files (dist/ or build/). Those files are served by a web server or CDN — Nginx, S3 + CloudFront, Azure Static Web Apps. No Node.js process is needed at runtime.
Docker example
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ARG VITE_API_URL
RUN npm run build
FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
server {
listen 80;
root /usr/share/nginx/html;
location / { try_files $uri $uri/ /index.html; } # single-page app routing
location /assets/ { expires 1y; add_header Cache-Control "public, immutable"; }
}
Two things that catch people out
- Build-time env vars —
VITE_*/REACT_APP_*values are baked in duringnpm run build. Changing them needs a rebuild (or a runtimeconfig.jstrick). - SPA routing — without
try_files ... /index.html, refreshing/orders/42returns 404.
What to say in the interview
"Frontends compile to static assets. We build with Node in one stage and serve dist with Nginx or push it to S3 + CloudFront. I configure SPA fallback to index.html and long cache headers on hashed assets, and remember that frontend env vars are build-time."
More on Node.js builds (npm, package.json)
What is package.json and what does it contain?BeginnerHow do you build and run a Node.js application?BeginnerWhat is the difference between npm install and npm ci?BeginnerWhy must package-lock.json be committed to Git?BeginnerWhat is the difference between dependencies and devDependencies?BeginnerWhat do the ^ and ~ symbols mean in package.json versions?Beginner