Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Pro

Deploying Node apps to production

Code that works on your laptop is half the job. In production it must stay up, log what happens, shut down cleanly, scale under load and stay secure. This lesson is a checklist of what changes when real users arrive, ending with a capstone project.

Configuration for production

bash
NODE_ENV=production PORT=8080 DATABASE_URL=… JWT_SECRET=… node src/server.js
  • NODE_ENV=production makes Express and many libraries skip development-only work (detailed error pages, extra checks). Never show stack traces to users in production.
  • Read every setting from environment variables, and validate them at startup (see the validation lesson).
  • Install only what's needed: npm ci --omit=dev installs exactly what the lock file says, without dev tools.

Logging

console.log is fine for learning. In production you want structured logs (one JSON object per line) that log platforms (Grafana Loki, Datadog, CloudWatch, Elastic) can search and filter:

Node.js · editable

Real projects use pino (very fast) or winston, which add levels, timestamps and request IDs. Log events and IDs, never passwords, tokens or full card numbers.

Health checks

Load balancers and container platforms check a URL to decide whether your app is alive and ready for traffic:

Node.js · editable

Graceful shutdown

When you deploy a new version, the platform sends your process a SIGTERM signal. A well-behaved server stops accepting new requests, lets in-flight requests finish, closes database connections and then exits:

js
const server = app.listen(port);

function shutdown(signal) {
  console.log(`${signal} received, shutting down…`);
  server.close(async () => {          // stop accepting connections, wait for open requests
    await db.close();
    process.exit(0);
  });
  setTimeout(() => process.exit(1), 10_000).unref();   // force exit if it takes too long
}

process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));        // Ctrl+C

Crashes

An uncaught exception leaves the process in an unknown state. Log it and exit, letting the process manager restart a clean process. Don't try to keep running:

js
process.on('uncaughtException', (err) => {
  logger.error('Uncaught exception', { error: err.message, stack: err.stack });
  process.exit(1);
});

Keeping it running

Something must start your app, restart it when it crashes and start it on boot:

Option When
Docker container on a platform (Fly.io, Render, Railway, Google Cloud Run, AWS ECS, Kubernetes) The most common choice today
PM2 (pm2 start server.js -i max) A plain Linux server (VM)
systemd service A plain Linux server, no extra tools
Serverless (AWS Lambda, Vercel/Netlify functions) Spiky traffic, small handlers

A production Dockerfile

dockerfile
FROM node:26-slim
WORKDIR /app
ENV NODE_ENV=production

COPY package*.json ./
RUN npm ci --omit=dev

COPY src ./src
USER node
EXPOSE 8080
CMD ["node", "src/server.js"]

Copying package*.json and running npm ci before copying the source lets Docker cache the dependency layer, so rebuilding after a code change takes seconds. Running as the node user instead of root limits the damage if the app is compromised. (The Docker track covers images and containers in depth.)

Performance and scaling

  • Node uses one CPU core per process. To use a whole machine, run several processes behind a load balancer: several containers, pm2 -i max, or node:cluster.
  • Keep the app stateless: store sessions, uploads and caches in shared services (Redis, a database, object storage), not in memory or local files, so any process can handle any request.
  • Cache expensive results (Redis), add database indexes, and paginate large lists.
  • Compress responses (most load balancers and CDNs do this for you).
  • Measure before optimising: node --cpu-prof, clinic.js, and application monitoring (OpenTelemetry) show where time actually goes.

Security checklist

  • helmet() for security headers; strict cors origins.
  • Validate every input (Zod); parameterised SQL queries only.
  • Rate-limit authentication and expensive routes.
  • npm audit and automated dependency updates (Dependabot, Renovate).
  • Secrets only in environment variables or a secrets manager; never in Git.
  • Run as a non-root user; keep Node on a supported LTS version.
  • Serve everything over HTTPS (usually terminated at the load balancer or CDN).

🎓 Node.js track complete!

You've learned how Node runs JavaScript, modules and npm, files, async code and the event loop, events and streams, HTTP servers, Express routing and middleware, databases, validation and configuration, authentication with JWT, testing, and running Node in production.

Capstone project: an online bookshop API

Build a production-style REST API with Express:

  1. Structure: app.js, server.js, routes/, middleware/, services/, db.js, plus .env.example.
  2. Data: SQLite (node:sqlite) or PostgreSQL with tables for users, books, orders and order_items, created by a setup script.
  3. Auth: register and log in with bcrypt + JWT; customer and admin roles.
  4. Endpoints: public GET /books (search, filter by author, pagination), admin-only POST/PATCH/DELETE /books, customer POST /orders (in a transaction that checks and reduces stock) and GET /orders/me.
  5. Quality: Zod validation on every body and query, a central error handler, structured logging with request IDs, /healthz.
  6. Tests: node --test integration tests for the happy paths and for 400, 401, 403 and 404 cases.
  7. Ship it: a Dockerfile, graceful shutdown, and a GitHub Actions workflow that runs the tests on every push.
✎ Check your understanding

1.What should a server do when it receives SIGTERM?

2.How do you use all 8 CPU cores of a server with Node?

3.Why run npm ci --omit=dev in production images?

← Testing APIs