Empty folder Express API
Show code for

Node.js and Express, from an empty folder

You already write JavaScript. This tutorial shows you how professional teams set up a Node.js and Express backend: every file, every command, and the reason each one exists.

16 lessons, about 3 hours. Work through them in order; each builds on the last.


          
A terminal creating a project, installing Express and nodemon, and starting the server.

How to use this tutorial

Use the switch at the top of the page to choose the code you want to see. Express 4 with CommonJS (require) is what you'll find in most existing codebases. Express 5 with ES modules (import) is the modern default for new projects. Every example on the page follows your choice, and lesson 7 explains the differences.

Blocks marked with a filename are files you create. Blocks marked Terminal are commands you run. Every block has a copy button.

What Node.js is, and why backends use it

Local only StackBlitz

JavaScript was created to run inside web browsers. Node.js is a program that runs JavaScript outside the browser, on a laptop or a server. It takes Google's V8 engine (the same one inside Chrome) and adds the things a server needs that a browser deliberately doesn't allow: reading and writing files, opening network ports, spawning processes, and reading environment variables.

Node is not a language and not a framework. It's a runtime: the environment your code runs in. The language is still JavaScript, which is the first reason teams choose it. One language across the frontend and backend means shared validation code, shared tooling, and developers who can move between both.

The event loop: why Node is good at servers

A web API spends most of its time waiting: for a database query, for a file read, for another API to respond. Many traditional servers dedicate a thread to each request, and that thread sits idle while it waits. Node takes a different approach. It runs your JavaScript on a single thread and hands slow I/O work to the operating system. When the work finishes, a callback is queued and the event loop runs it. While one request waits on the database, Node is free to handle hundreds of others.

Why this matters to you

Because there's only one JavaScript thread, blocking it blocks every user. A synchronous 2-second loop in a route handler freezes the whole server for 2 seconds. That's why Node APIs are asynchronous (async/await, promises, callbacks) and why CPU-heavy work like video encoding is usually moved to worker threads or a separate service.

Browser JavaScript vs Node.js

In the browserIn Node.js
Global objectwindow (or globalThis)global (or globalThis)
Page accessdocument, the DOM, eventsNone. There's no page.
System accessSandboxed for safetyFiles (fs), networking (http), processes, process.env
PackagesBundled by a build tool, or loaded from a CDNInstalled with npm into node_modules
Shared APIsfetch, setTimeout, URL, console, promises, and the whole language

What Express adds on top

Node ships with a built-in http module, so you can write a web server with no packages at all. Here is one. Notice how much routing you have to do by hand:

const http = require('node:http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello from plain Node');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not found');
  }
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});
import http from 'node:http';

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello from plain Node');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not found');
  }
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

That works, but every new URL means another if, and there's no built-in way to parse JSON bodies, read URL parameters, or share logic like authentication between routes. Express is a small, unopinionated framework built on top of http that gives you three things: routing (map a method and URL to a function), middleware (reusable steps every request passes through), and helpers on the request and response objects (req.params, res.json(), res.status()). It's the most widely used Node web framework, and frameworks like NestJS use it under the hood, so learning it pays off even if you move on later.

The node: prefix (node:http) marks a built-in module. It's optional, but it's the current convention because it makes it obvious the module isn't an npm package.

Install Node.js and verify it works

Local only

Installing Node also installs npm, the Node Package Manager, which you'll use for everything from creating the project to running scripts.

Pick an LTS version

Node releases a new major version every six months. Even-numbered versions (20, 22, 24…) become LTS (Long-Term Support): they receive security and bug fixes for about 30 months. Odd-numbered versions are short-lived. Production servers run LTS, so you should learn on LTS too. The nodejs.org download page labels the current LTS clearly.

Use a version manager, not a one-off installer

The industry-standard approach is to install Node through a version manager. Different projects often need different Node versions, and a version manager lets you switch per project with one command. It also installs Node inside your user folder, so you never need sudo to install global tools, which avoids a whole class of permission errors.

Install nvm (Node Version Manager). The install script URL contains a version number, so copy the current command from the nvm README. Then restart your terminal and run:

# Install and use the latest LTS release
nvm install --lts
nvm use --lts

# Make it the default for new terminals
nvm alias default lts/*

Prefer something faster? fnm and Volta are popular alternatives that do the same job.

Verify the install

Open a new terminal (so it picks up the updated PATH) and check both tools respond:

node -v
npm -v
v22.12.0
10.9.0

Then prove Node can actually run code, two ways:

# Run a one-line script
node -e "console.log('Node works:', process.version)"

# Start the interactive REPL (type .exit or press Ctrl+C twice to leave)
node

The REPL (Read-Eval-Print Loop) is a JavaScript console in your terminal. It's handy for checking how a built-in behaves: try typeof window (it's 'undefined') or process.platform.

Troubleshooting: "command not found: node"

The shell can't find Node on your PATH. Close and reopen the terminal first. If that doesn't help, check that the version manager's setup lines were added to your shell profile (~/.zshrc, ~/.bashrc, or your PowerShell profile). which node (macOS and Linux) or where node (Windows) shows which binary, if any, is being picked up.

Pin the Node version for your team with .nvmrc

Add a .nvmrc file to the project root containing a version like 22. Anyone who clones the repo can run nvm use (or fnm use) and get the same major version you developed on. It's a one-line file that prevents a lot of "works on my machine" bugs.

node -v | cut -d. -f1 | tr -d v > .nvmrc

Start a project with npm init

Local only StackBlitz

A Node project is just a folder with a package.json file at its root. That file is the project's manifest: its name, the packages it depends on, and the commands used to run it. npm init creates it.

mkdir my-express-api
cd my-express-api
git init
npm init

We run git init straight away because version control should cover the project from its first file. npm init then asks a series of questions. Here's what each one means:

package name
Defaults to the folder name. Must be lowercase, with no spaces; use hyphens (my-express-api).
version
Defaults to 1.0.0. Fine to accept.
description
One sentence about the project. Shows up in search if you ever publish.
entry point
Becomes the main field. We'll change it to src/server.js later.
test command
Becomes scripts.test. Leave blank for now.
git repository, keywords, author
Metadata. Fill in what you know.
license
Defaults to ISC. MIT is the most common open-source choice; private company code often uses UNLICENSED.
type
Newer npm versions ask this. commonjs or module; lesson 7 explains the choice.

To skip the questions and accept every default, use the -y flag. Most developers do this and edit the file afterwards:

npm init -y
{
  "name": "my-express-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

That's a working project. It has no code yet, but npm now knows where the project root is, and every npm install from this folder will be recorded here.

Set your own defaults for future projects

If you always use the same author and license, tell npm once and npm init -y will fill them in:

npm config set init-author-name "Your Name"
npm config set init-license "MIT"

package.json, field by field

StackBlitz Local only

Here's what package.json looks like for a real Express API after a few installs. Read it, then read the field notes below.

{
  "name": "my-express-api",
  "version": "1.0.0",
  "description": "A REST API for managing users",
  "main": "src/server.js",
  "private": true,
  "scripts": {
    "start": "node src/server.js",
    "dev": "nodemon src/server.js",
    "lint": "eslint .",
    "test": "jest"
  },
  "engines": {
    "node": ">=18"
  },
  "author": "Your Name",
  "license": "MIT",
  "dependencies": {
    "dotenv": "^16.4.7",
    "express": "^4.21.2"
  },
  "devDependencies": {
    "eslint": "^9.17.0",
    "jest": "^29.7.0",
    "nodemon": "^3.1.9",
    "supertest": "^7.0.0"
  }
}
{
  "name": "my-express-api",
  "version": "1.0.0",
  "description": "A REST API for managing users",
  "main": "src/server.js",
  "type": "module",
  "private": true,
  "scripts": {
    "start": "node src/server.js",
    "dev": "nodemon src/server.js",
    "lint": "eslint .",
    "test": "vitest run"
  },
  "engines": {
    "node": ">=20"
  },
  "author": "Your Name",
  "license": "MIT",
  "dependencies": {
    "dotenv": "^16.4.7",
    "express": "^5.1.0"
  },
  "devDependencies": {
    "eslint": "^9.17.0",
    "nodemon": "^3.1.9",
    "supertest": "^7.0.0",
    "vitest": "^3.0.0"
  }
}
name
The package's identifier. Lowercase, URL-safe, up to 214 characters. For an app you never publish, it's mostly a label, but tools and logs display it.
version
Follows semantic versioning: MAJOR.MINOR.PATCH. Bump PATCH for bug fixes, MINOR for new backwards-compatible features, MAJOR for breaking changes. Understanding this matters mostly for reading other packages' versions (see the ^ note under dependencies).
description
A one-line summary for humans.
main
The file that's loaded when someone requires this package. For a library, it's critical. For an application like ours, nobody imports it, so it's documentation: it tells readers where the app starts. Keep it pointing at the real entry file.
type
Tells Node how to interpret .js files. Missing or "commonjs" means require/module.exports. "module" means import/export. This one field changes how every file in your project is parsed; lesson 7 covers it in depth.
private
true makes npm publish refuse to run. Applications aren't meant to be published to the public registry, so this is a cheap guard against leaking company code.
scripts

Named commands for your project. Run them with npm run <name>. Two names are special and don't need run: npm start and npm test.

Scripts are the project's shared vocabulary. A new teammate doesn't need to know you use nodemon, Jest, or ESLint; they run npm run dev, npm test, and npm run lint. Deployment platforms also run npm start by default, so it should start the app with plain node, never a dev tool.

When a script runs, npm adds node_modules/.bin to the PATH. That's why "dev": "nodemon src/server.js" works even though nodemon isn't installed globally: npm finds the project's local copy.

engines
Declares which Node versions the project supports. npm only warns on a mismatch by default, but many hosting platforms read this field to pick the Node version for deployment. Express 5 requires Node 18 or newer, so a project on Express 5 should never say less than that.
dependencies and devDependencies

The packages your project needs, split by when they're needed (lesson 5). npm writes these for you when you install; you rarely edit them by hand.

Version ranges use semver operators. "^4.21.2" (caret, npm's default) means "4.21.2 or any newer 4.x", because minor and patch releases shouldn't break you. "~4.21.2" (tilde) allows only patch updates, 4.21.x. "4.21.2" with no operator means exactly that version. The lockfile (lesson 6) records what was actually installed.

author, license, keywords, repository
Metadata. Worth filling in for anything shared; no effect on how the code runs.

The version numbers in these examples will be older than what you get. That's expected: when you run npm install express, npm writes the latest matching version for you. You never need to type version numbers into package.json yourself.

Script hooks: pre and post

npm automatically runs pre<name> before and post<name> after any script. With "pretest": "npm run lint", every npm test lints first. Use sparingly: hidden steps can confuse teammates.

dependencies vs devDependencies

StackBlitz Local only

Every package you install goes into one of two lists. The rule for deciding is a single question:

Does the running application need this package in production?

If your server code requires or imports it while handling requests, it's a dependency. If it's only used while you write, check, test, or build the code, it's a devDependency.

PackageGoes inWhy
expressdependenciesThe server can't start without it.
dotenvdependenciesYour code calls it at startup. If it's missing in production, the require/import line crashes.
cors, helmet, morgandependenciesMiddleware that runs on live requests.
Database drivers and ORMs (pg, mongoose, prisma client)dependenciesUsed on every query in production.
nodemondevDependenciesRestarts the server when you save a file. Production never restarts on file changes.
eslint, prettierdevDependenciesCheck and format code before it ships. Not used at runtime.
jest, vitest, supertestdevDependenciesTests run in development and CI, not on the live server.
typescript, @types/*devDependenciesOnly needed to compile. Production runs the compiled JavaScript.

Why the split matters

When you deploy, you install with devDependencies left out:

npm ci --omit=dev

That gives you a smaller install (test frameworks and linters are often most of node_modules), faster deploys and container builds, and fewer packages in production that could contain security vulnerabilities. It also documents intent: a reader can see at a glance what the app actually runs on.

The mistake to watch for

Putting a runtime package in devDependencies works perfectly on your machine, because locally you install everything. It only breaks in production, with Error: Cannot find module 'dotenv'. If you require/import it in src/, it belongs in dependencies.

What about global installs like npm install -g nodemon?

Older tutorials install tools globally. The current convention is to install them per project as devDependencies and run them through npm scripts or npx. Global tools aren't listed in package.json, so teammates and CI servers don't get them, and different projects can't use different versions. A local devDependency solves both.

Installing packages, the lockfile, and node_modules

StackBlitz Local only

The commands you'll use every day:

# Runtime dependencies (saved to "dependencies" by default)
npm install express@4 dotenv

# Development-only tools (saved to "devDependencies")
npm install --save-dev nodemon eslint jest supertest

# Short forms: i = install, -D = --save-dev
npm i -D nodemon
# Runtime dependencies (saved to "dependencies" by default)
npm install express dotenv

# Development-only tools (saved to "devDependencies")
npm install --save-dev nodemon eslint vitest supertest

# Short forms: i = install, -D = --save-dev
npm i -D nodemon

npm install express installs the version tagged latest on npm, which is Express 5. To stay on Express 4, ask for it explicitly with express@4.

CommandWhat it does
npm installInstalls everything listed in package.json. Run it after cloning a project.
npm ciClean install from the lockfile exactly. Deletes node_modules first and fails if package.json and the lockfile disagree. Use it in CI and deployments.
npm uninstall <pkg>Removes a package and its entry in package.json.
npm outdatedLists packages with newer versions available.
npm updateUpdates packages within the ranges allowed in package.json.
npm ls expressShows which version is installed and what depends on it.
npm auditChecks installed packages against known security advisories.
npx <tool>Runs a package's command: the local copy if installed, otherwise a temporary download.

What happens when you install

npm reads the version range, asks the registry which versions exist, picks the newest one that fits, and then does the same for every package that package depends on, all the way down. Express alone pulls in a few dozen packages. npm then writes three things:

  1. The files, into node_modules/.
  2. The range you asked for, into package.json (for example "express": "^5.1.0").
  3. The exact versions of everything it installed, into package-lock.json.

package-lock.json: commit it

package.json says "any 5.x is fine". The lockfile says "we are using 5.1.0, and its dependency body-parser is exactly 2.2.0, downloaded from this URL, with this integrity hash". It records the entire installed tree.

That precision is the point. Without it, two developers who install a week apart could get different sub-dependency versions and see different bugs. With it, everyone (and every server) running npm ci gets byte-for-byte the same packages, and the integrity hashes guarantee nothing was tampered with. Always commit package-lock.json. Never edit it by hand.

node_modules: never commit it

node_modules is where the installed code lives. It's regularly tens of thousands of files and hundreds of megabytes. Keep it out of Git because:

  • It's fully reproducible. package.json plus the lockfile is a complete recipe; npm ci rebuilds it exactly.
  • Some packages compile native binaries for the machine they're installed on. A node_modules built on a Mac can break on a Linux server.
  • It would bury your real changes in noise and bloat the repository permanently.

Tell Git to ignore it by creating a .gitignore file in the project root before your first commit:

# Dependencies (rebuilt with npm ci)
node_modules/

# Secrets and local config
.env
.env.local

# Logs and generated output
npm-debug.log*
coverage/
dist/

# OS and editor files
.DS_Store
.vscode/*
!.vscode/extensions.json
git add .
git commit -m "Initialize project"

If you accidentally committed node_modules already, adding it to .gitignore isn't enough, because Git keeps tracking files it already knows about. Run git rm -r --cached node_modules and commit.

CommonJS vs ES modules, Express 4 vs Express 5

Playground StackBlitz

You'll meet two separate choices in the Node ecosystem, and older tutorials rarely explain either. This lesson untangles them.

Two module systems

CommonJS (CJS) is Node's original module system, from 2009, long before JavaScript had modules of its own. ES modules (ESM) are the official JavaScript standard, added to the language in 2015 and the same syntax browsers use. Node supports both, and decides per file:

  • .js files are CommonJS, unless the nearest package.json has "type": "module", in which case they're ESM.
  • .cjs files are always CommonJS. .mjs files are always ESM.

CommonJS

function add(a, b) {
  return a + b;
}

module.exports = { add };
const express = require('express');
const { add } = require('./math');

console.log(add(2, 3));

ES modules

export function add(a, b) {
  return a + b;
}
import express from 'express';
import { add } from './math.js';

console.log(add(2, 3));
CommonJSES modules
Importconst x = require('x')import x from 'x'
Exportmodule.exports = …export / export default
Relative pathsExtension optional: './math'Extension required: './math.js'
Folder imports'./routes' finds routes/index.jsMust write './routes/index.js'
When it loadsSynchronously, when the line runsAll imports are resolved before any code runs (hoisted)
__dirnameAvailableNot defined; use import.meta.dirname (Node 20.11+)
Top-level awaitNot allowedAllowed
StandardNode-specificJavaScript language standard; same as the browser

Mixing them in the wrong place produces errors you'll see often, so learn to recognize them:

SyntaxError: Cannot use import statement outside a module
ReferenceError: require is not defined in ES module scope, you can use import instead

The fix is never to rewrite the error; it's to make the syntax match the "type" field. Try it: the playground raises the same errors when your code doesn't match the style chosen at the top of the page.

Two major versions of Express

Express 4 was the stable release from 2014 until Express 5.0 shipped in late 2024. Express 5 is now what npm install express gives you. The core API (app.get, app.use, req, res) is almost identical, and most tutorials still work. The differences that matter day to day:

Express 4Express 5
Minimum NodeVery old versions still supportedNode 18+
Errors in async handlersNot caught. You must try/catch and call next(err), or the request hangs.Rejected promises are passed to your error handler automatically.
Wildcards'/files/*'Must be named: '/files/*filepath'
Optional params'/posts/:page?''/posts{/:page}'
req.body with no parser match{} after express.json()undefined
Invalid status codesAccepted silentlyres.status() throws
Removedapp.del(), req.param(), res.send(status), res.sendfile() (use sendFile)

An important clarification

The module system and the Express version are independent. Express 5 works with require, and Express 4 works with import. This tutorial pairs them because that's the pattern you'll actually encounter: older codebases tend to be Express 4 with CommonJS, and new projects tend to start on Express 5 with ES modules. Learning both pairings prepares you for both kinds of job.

Which should you use?

Express 4 with CommonJS

  • You're joining or maintaining an existing codebase that uses it.
  • You're following a course, book, or library documentation written for it.
  • You depend on an older package that only works with require.

Express 5 with ES modules

  • You're starting a new project today. This is the default recommendation.
  • You want async error handling without boilerplate.
  • You want the same module syntax you use in the browser and in TypeScript.

Migrating from 4 to 5 is usually small: update the path patterns, remove the removed methods, and delete your async error wrappers. The Express team publishes a migration guide and a codemod that automates most of it.

Your first Express server

Playground StackBlitz Local only

Starting from the project you created in lesson 3, install Express and nodemon:

npm install express@4
npm install --save-dev nodemon
mkdir src
npm install express
npm install --save-dev nodemon
npm pkg set type=module
mkdir src

npm pkg set type=module adds "type": "module" to package.json without opening the file.

Create the entry file. By convention, application code lives in src/, and the file that starts the server is called server.js (you'll also see index.js and app.js; lesson 11 explains why we eventually use both app.js and server.js).

const express = require('express');

// Create the application object
const app = express();

// Use the PORT environment variable if set, otherwise 3000
const PORT = process.env.PORT || 3000;

// Parse JSON request bodies into req.body
app.use(express.json());

// A route: when a GET request arrives for "/", run this function
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', uptime: process.uptime() });
});

// Start listening for HTTP requests
app.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`);
});
import express from 'express';

// Create the application object
const app = express();

// Use the PORT environment variable if set, otherwise 3000
const PORT = process.env.PORT || 3000;

// Parse JSON request bodies into req.body
app.use(express.json());

// A route: when a GET request arrives for "/", run this function
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', uptime: process.uptime() });
});

// Start listening for HTTP requests
app.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`);
});

What each piece does

express()
Creates an application: an object that holds your routes and middleware, and is itself a request handler function that Node's http server can call.
app.get(path, handler)
Registers a route. When a request's method is GET and its path matches, Express calls your handler with req and res.
req
The incoming request: req.method, req.path, req.params, req.query, req.body, req.get('header-name').
res
Your reply. res.send() sends text or HTML, res.json() sends JSON with the right Content-Type, res.status(code) sets the status. Every request must end with exactly one response, or the client waits until it times out.
app.listen(port)
Creates the HTTP server and starts accepting connections. Nothing is reachable until this runs.
process.env.PORT || 3000
Hosting platforms tell your app which port to use through the PORT environment variable. Reading it (with a local fallback) makes the same code run everywhere.

Add scripts and run it

Add these to the scripts section of package.json, and update main to match:

"main": "src/server.js",
"scripts": {
  "start": "node src/server.js",
  "dev": "nodemon src/server.js"
}
npm run dev

Open http://localhost:3000 in a browser, or test from a second terminal:

curl http://localhost:3000/api/health

Now edit the message in src/server.js and save. nodemon notices the change and restarts the server, so a refresh shows the new text. Without it you'd stop and restart by hand after every edit. npm start runs plain node with no watching, which is what production uses.

Node 22 and later include a built-in watcher: "dev": "node --watch src/server.js". It does the same job with no extra package. nodemon remains common because it's more configurable and works on older Node versions.

Run this server without installing anything, and send it requests.

Routing

Playground StackBlitz

A route is the combination of an HTTP method and a path, mapped to a handler. REST APIs use the method to say what to do and the path to say what to do it to. Paths name resources with plural nouns; the method is the verb.

Method and pathMeaningTypical success status
GET /api/usersList users200 OK
GET /api/users/42Get one user200 OK (404 if missing)
POST /api/usersCreate a user201 Created
PUT /api/users/42Replace a user200 OK
PATCH /api/users/42Update some fields200 OK
DELETE /api/users/42Delete a user204 No Content

Avoid verbs in paths like /getUsers or /deleteUser/42. The method already carries the verb, and consistent URLs make an API predictable for everyone who uses it.

Three ways to receive data

// 1. Route parameters: part of the path, for identifying a resource
// GET /api/users/42  ->  req.params.id === '42'
app.get('/api/users/:id', (req, res) => {
  const id = Number(req.params.id); // params are always strings
  res.json({ id });
});

// 2. Query string: after the "?", for filtering, sorting, paging
// GET /api/users?role=admin&page=2  ->  req.query.role === 'admin'
app.get('/api/users', (req, res) => {
  const { role, page = '1' } = req.query;
  res.json({ role, page: Number(page) });
});

// 3. Request body: for sending data to create or update
// POST /api/users with JSON {"name":"Ada"}  ->  req.body.name === 'Ada'
// Requires app.use(express.json()) earlier in the file
app.post('/api/users', (req, res) => {
  const { name } = req.body;
  res.status(201).json({ id: 3, name });
});
// 1. Route parameters: part of the path, for identifying a resource
// GET /api/users/42  ->  req.params.id === '42'
app.get('/api/users/:id', (req, res) => {
  const id = Number(req.params.id); // params are always strings
  res.json({ id });
});

// 2. Query string: after the "?", for filtering, sorting, paging
// GET /api/users?role=admin&page=2  ->  req.query.role === 'admin'
app.get('/api/users', (req, res) => {
  const { role, page = '1' } = req.query;
  res.json({ role, page: Number(page) });
});

// 3. Request body: for sending data to create or update
// POST /api/users with JSON {"name":"Ada"}  ->  req.body.name === 'Ada'
// Requires app.use(express.json()) earlier in the file.
// In Express 5, req.body is undefined when no JSON was sent, so default it.
app.post('/api/users', (req, res) => {
  const { name } = req.body ?? {};
  res.status(201).json({ id: 3, name });
});

Grouping routes with express.Router

Putting every route in one file stops scaling after a dozen endpoints. A router is a mini application that holds a group of related routes. You mount it at a path prefix, and the routes inside it are written relative to that prefix:

const express = require('express');

const router = express.Router();

// These paths are relative to wherever the router is mounted
router.get('/', (req, res) => res.json([]));          // GET /api/users
router.get('/:id', (req, res) => res.json({}));       // GET /api/users/:id
router.post('/', (req, res) => res.status(201).json({})); // POST /api/users

module.exports = router;
const usersRouter = require('./routes/users.routes');

app.use('/api/users', usersRouter);
import { Router } from 'express';

const router = Router();

// These paths are relative to wherever the router is mounted
router.get('/', (req, res) => res.json([]));          // GET /api/users
router.get('/:id', (req, res) => res.json({}));       // GET /api/users/:id
router.post('/', (req, res) => res.status(201).json({})); // POST /api/users

export default router;
import usersRouter from './routes/users.routes.js';

app.use('/api/users', usersRouter);

If you ever decide the API should live under /api/v2/users, you change one line. That's the payoff.

Path syntax that changed in Express 5

Express 4

app.get('/files/*', handler);
// req.params[0] === 'a/b.txt'

app.get('/posts/:page?', handler);

Express 5

app.get('/files/*filepath', handler);
// req.params.filepath === ['a', 'b.txt']

app.get('/posts{/:page}', handler);

Express 5 throws an error at startup if it sees the old syntax, so these problems show up immediately rather than as silent routing bugs. The playground reproduces that check.

Experiment with params, query strings, and bodies against an in-memory users API.

Middleware

Playground StackBlitz

Middleware is the idea that makes Express Express. A middleware function receives the request, can inspect or change req and res, and then either ends the request by sending a response, or passes it on by calling next(). Your app is a pipeline of these functions, run in the order you registered them.

  1. Request
  2. express.json()parses the body
  3. loggerrecords the request
  4. requireAuthmay reply 401 and stop
  5. route handlersends the response
  6. errorHandleronly runs if something failed
Each step calls next() to continue, sends a response to finish, or calls next(err) to jump to the error handler.

Route handlers are middleware too; they're simply the last step and usually don't call next(). Seeing everything as one pipeline explains most Express behavior, including why order matters: express.json() must be registered before the routes that read req.body, and a 404 handler must come after every route.

Writing your own

// Logs method, path, status, and how long the request took
function requestLogger(req, res, next) {
  const start = Date.now();

  // 'finish' fires after the response has been sent
  res.on('finish', () => {
    const ms = Date.now() - start;
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
  });

  next(); // hand off to the next middleware
}

module.exports = requestLogger;
// Rejects requests without the right x-api-key header
function requireApiKey(req, res, next) {
  if (req.get('x-api-key') !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Invalid or missing API key' });
  }
  next();
}

module.exports = requireApiKey;
// Logs method, path, status, and how long the request took
export default function requestLogger(req, res, next) {
  const start = Date.now();

  // 'finish' fires after the response has been sent
  res.on('finish', () => {
    const ms = Date.now() - start;
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
  });

  next(); // hand off to the next middleware
}
// Rejects requests without the right x-api-key header
export default function requireApiKey(req, res, next) {
  if (req.get('x-api-key') !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Invalid or missing API key' });
  }
  next();
}

Note the return before res.status(401). Without it, the function would send a 401 and then call next() anyway, and the route would try to send a second response, which crashes with Cannot set headers after they are sent to the client.

Where middleware can be attached

// Every request
app.use(requestLogger);

// Only requests whose path starts with /admin
app.use('/admin', requireApiKey);

// Only this one route (middleware listed before the handler)
app.delete('/api/users/:id', requireApiKey, deleteUser);

// Every route in a router
router.use(requireApiKey);
// Every request
app.use(requestLogger);

// Only requests whose path starts with /admin
app.use('/admin', requireApiKey);

// Only this one route (middleware listed before the handler)
app.delete('/api/users/:id', requireApiKey, deleteUser);

// Every route in a router
router.use(requireApiKey);

Built-in and third-party middleware

MiddlewareSourceWhat it does
express.json()Built inParses JSON bodies into req.body
express.urlencoded()Built inParses HTML form submissions
express.static('public')Built inServes files like images and CSS from a folder
helmet()npm i helmetSets security-related HTTP headers
cors()npm i corsAllows browsers on other origins to call your API
morgan('dev')npm i morganRequest logging, a ready-made version of our logger

Error-handling middleware and 404s

Express recognizes an error handler by its four parameters: (err, req, res, next). It's skipped during normal requests and runs only when something calls next(err) or throws. Register it last, after a catch-all 404 handler:

// No route matched: reply 404
app.use((req, res) => {
  res.status(404).json({ error: `Not found: ${req.method} ${req.originalUrl}` });
});

// Something failed: reply with the error's status, or 500
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: err.message });
});

In Express 4, errors thrown inside async functions are not caught. You must catch them and forward them yourself:

app.get('/api/users', async (req, res, next) => {
  try {
    const users = await db.findUsers();
    res.json(users);
  } catch (err) {
    next(err); // forward to the error handler
  }
});

Forget the try/catch and a failed database call leaves the request hanging, with an UnhandledPromiseRejection warning in the console. Many Express 4 codebases use a small wrapper (or the express-async-errors package) to avoid repeating this.

// No route matched: reply 404
app.use((req, res) => {
  res.status(404).json({ error: `Not found: ${req.method} ${req.originalUrl}` });
});

// Something failed: reply with the error's status, or 500
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: err.message });
});

In Express 5, a rejected promise from an async handler is forwarded to the error handler automatically, so handlers stay clean:

app.get('/api/users', async (req, res) => {
  const users = await db.findUsers(); // if this throws, the error handler runs
  res.json(users);
});

Watch requests flow through a pipeline, get rejected by auth, and hit the error handler.

Folder structure and naming conventions

StackBlitz Local only

Express doesn't enforce any structure. That freedom is why teams converge on a common one: when every project looks roughly the same, a new developer knows where to find a route or a database query on their first day. This is the layout you'll see most often:

my-express-api/
├── src/
│   ├── config/
│   │   └── index.js              Reads and validates environment variables
│   ├── controllers/
│   │   └── users.controller.js   Handles requests: reads input, sends responses
│   ├── middleware/
│   │   ├── errorHandler.js       Central error responses
│   │   └── notFound.js           Catch-all 404
│   ├── models/
│   │   └── user.model.js         Data shape and database access
│   ├── routes/
│   │   ├── index.js              Mounts every router under /api
│   │   └── users.routes.js       Maps URLs to controller functions
│   ├── app.js                    Builds and exports the Express app
│   └── server.js                 Starts the app listening on a port
├── tests/
│   └── users.test.js
├── .env                          Your local secrets. Never committed.
├── .env.example                  Template of required variables. Committed.
├── .gitignore
├── eslint.config.js
├── package.json
├── package-lock.json
└── README.md

What each part is responsible for

src/
All application source code. Keeping it separate from config files, tests, and docs at the root makes the root easy to scan and makes build and lint configuration simpler.
routes/
Only URL-to-function mapping. A routes file should read like a table of contents for that resource, with no business logic.
controllers/
The HTTP layer. Reads req.params, req.query, and req.body, calls the model or service, and chooses the status code and response.
models/
Data: its shape, validation rules, and the code that talks to the database. Controllers shouldn't contain SQL or ORM queries.
middleware/
Reusable pipeline steps: auth, logging, validation, error handling.
config/
The one place that reads process.env. Everything else imports settings from here.
services/ (optional)
Business logic that doesn't belong to one request, such as sending emails or calculating an invoice. Add it when controllers start getting long.
tests/
Automated tests. Some teams instead put users.test.js next to the file it tests; both are common.
README.md
How to install, configure, run, and test the project. The first file anyone reads.

Why split app.js and server.js?

app.js creates and configures the app and exports it. server.js imports it and calls listen(). The split lets tests import the app and send it requests with Supertest without opening a real network port, and it keeps startup concerns (ports, graceful shutdown, clustering) out of your app configuration.

A request's path through the layers

GET /api/users/2 enters app.js, passes through global middleware, is matched by routes/index.js to the users router, which calls usersController.getUser, which asks User.findById(2) for data and sends it back as JSON. Each layer knows about the layer below it, never above. That one-way flow is what makes each piece easy to test and replace. Swapping the in-memory model for PostgreSQL later touches only models/.

Naming conventions

  • Lowercase file names. macOS and Windows treat User.js and user.js as the same file; Linux servers don't. A casing mismatch in an import works on your laptop and fails in production.
  • A consistent pattern for multi-word names. Kebab-case (request-logger.js) and camelCase (requestLogger.js) are both widespread. Pick one per project and stick to it.
  • Role suffixes are optional but helpful: users.controller.js, users.routes.js, user.model.js. When five editor tabs are all named users.js, you'll appreciate them.
  • Plural for collections, singular for models: the users routes and controller deal with many users; the User model describes one.
  • Test files mirror their subject: users.test.js or users.spec.js. Test runners find them by that suffix.
  • Dotfiles at the root (.env, .gitignore, .nvmrc) are configuration for tools. The leading dot hides them in most file listings.
Structuring by feature instead of by layer

Larger codebases often group by feature: src/users/ contains users.routes.js, users.controller.js, and user.model.js together. Everything about users is in one folder, so features can be added or removed as a unit. Layer-based structure (above) is easier to learn and is still the most common in small and medium Express apps. The responsibilities of each file are identical in both.

Environment variables and .env

Playground StackBlitz Local only

Your app needs settings that change between environments: the port, the database URL, API keys for other services. Those values must not be written into the code, for two reasons. Secrets in code end up in Git, and anyone with repository access (or a leaked copy) can read them forever. And the same code must run in several places: your laptop, a teammate's laptop, CI, staging, production, each with different values.

The standard answer is environment variables: key-value pairs the operating system passes to a process. Node exposes them as process.env. Values are always strings.

PORT=4000 node src/server.js

Using a .env file locally

Typing variables before every command gets old. The dotenv package reads a file named .env and copies its values into process.env when your app starts. Production platforms set real environment variables instead, and dotenv never overwrites a variable that's already set, so the same code works in both places.

npm install dotenv
# Server
PORT=3000
NODE_ENV=development

# Secrets: never commit this file
API_KEY=dev-only-change-me
DATABASE_URL=postgres://localhost:5432/my_express_api

Format rules: one KEY=value per line, no spaces around =, uppercase names with underscores, # for comments. Quotes are optional unless the value contains spaces or #.

Load it before anything reads it

require('dotenv').config(); // must run before any code reads process.env

const express = require('express');

console.log(process.env.PORT); // '3000'

With CommonJS, require calls run in order from top to bottom, so putting config() first is enough.

import 'dotenv/config'; // must be the first import

import express from 'express';

console.log(process.env.PORT); // '3000'

With ES modules, all imports are loaded before any of the file's own code runs. If you wrote import dotenv from 'dotenv' and then called dotenv.config() on a later line, every imported module would already have run, and any of them that read process.env at load time would have seen undefined. The side-effect import 'dotenv/config' loads the file as part of the import phase, in order.

Centralize it in config/

Scattering process.env.X across the codebase makes it hard to know which variables the app needs, and a typo silently produces undefined. The professional pattern is one config module that loads, converts, and validates everything, and fails at startup if something required is missing:

require('dotenv').config();

function required(name) {
  const value = process.env[name];
  if (value === undefined || value === '') {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

const config = {
  env: process.env.NODE_ENV || 'development',
  port: Number(process.env.PORT) || 3000,
  apiKey: required('API_KEY'),
};

config.isProduction = config.env === 'production';

module.exports = config;
import 'dotenv/config';

function required(name) {
  const value = process.env[name];
  if (value === undefined || value === '') {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

const config = {
  env: process.env.NODE_ENV || 'development',
  port: Number(process.env.PORT) || 3000,
  apiKey: required('API_KEY'),
};

config.isProduction = config.env === 'production';

export default config;

Crashing on startup sounds harsh, but it's the kind outcome: you find out in the first second of a deploy, instead of when the first user hits the route that needed the missing key.

Commit a .env.example, never the .env

.env is in .gitignore (lesson 6). So how does a new teammate know which variables to set? You commit a template with the same keys and safe placeholder values:

PORT=3000
NODE_ENV=development
API_KEY=
DATABASE_URL=postgres://localhost:5432/my_express_api
cp .env.example .env
# then fill in the real values

If a secret is ever committed

Deleting the file in a new commit doesn't help; the secret is still in the Git history. Treat it as leaked: revoke and regenerate the key with the provider, then clean the history if needed.

Node's built-in alternative: --env-file

Node 20.6 and later can load a .env file with no package: node --env-file=.env src/server.js. It's a good choice for new projects on a recent Node version. dotenv remains the most common approach because it works on every Node version and in every tool (test runners, scripts) without changing how they're launched.

Also note: dotenv version 17 and later print a one-line message when loading. Pass { quiet: true } to config() to silence it.

See what happens when .env is loaded, loaded too late, or not loaded at all.

Put it all together

StackBlitz Local only

Here is the complete project from lesson 11, every file, following every convention in this tutorial. Build it yourself file by file (recommended; typing it teaches more than reading), or open it in StackBlitz to run the finished version.

Opens all the files below as a real Node project in a new tab.

1. Create the project

mkdir my-express-api && cd my-express-api
git init
npm init -y
npm install express@4 dotenv
npm install --save-dev nodemon eslint @eslint/js globals jest supertest
mkdir -p src/config src/controllers src/middleware src/models src/routes tests
mkdir my-express-api && cd my-express-api
git init
npm init -y
npm pkg set type=module
npm install express dotenv
npm install --save-dev nodemon eslint @eslint/js globals vitest supertest
mkdir -p src/config src/controllers src/middleware src/models src/routes tests

On Windows PowerShell, create the folders with mkdir src/config, src/controllers, src/middleware, src/models, src/routes, tests.

2. Project configuration files

{
  "name": "my-express-api",
  "version": "1.0.0",
  "description": "A REST API for managing users",
  "main": "src/server.js",
  "private": true,
  "scripts": {
    "start": "node src/server.js",
    "dev": "nodemon src/server.js",
    "lint": "eslint .",
    "test": "jest"
  },
  "engines": {
    "node": ">=18"
  },
  "license": "MIT",
  "dependencies": {
    "dotenv": "^16.4.7",
    "express": "^4.21.2"
  },
  "devDependencies": {
    "@eslint/js": "^9.17.0",
    "eslint": "^9.17.0",
    "globals": "^15.14.0",
    "jest": "^29.7.0",
    "nodemon": "^3.1.9",
    "supertest": "^7.0.0"
  }
}
{
  "name": "my-express-api",
  "version": "1.0.0",
  "description": "A REST API for managing users",
  "main": "src/server.js",
  "type": "module",
  "private": true,
  "scripts": {
    "start": "node src/server.js",
    "dev": "nodemon src/server.js",
    "lint": "eslint .",
    "test": "vitest run"
  },
  "engines": {
    "node": ">=20"
  },
  "license": "MIT",
  "dependencies": {
    "dotenv": "^16.4.7",
    "express": "^5.1.0"
  },
  "devDependencies": {
    "@eslint/js": "^9.17.0",
    "eslint": "^9.17.0",
    "globals": "^15.14.0",
    "nodemon": "^3.1.9",
    "supertest": "^7.0.0",
    "vitest": "^3.0.0"
  }
}
node_modules/
.env
.env.local
npm-debug.log*
coverage/
dist/
.DS_Store
PORT=3000
NODE_ENV=development

Copy .env.example to .env after creating it.

3. Configuration

require('dotenv').config();

const config = {
  env: process.env.NODE_ENV || 'development',
  port: Number(process.env.PORT) || 3000,
};

config.isProduction = config.env === 'production';

module.exports = config;
import 'dotenv/config';

const config = {
  env: process.env.NODE_ENV || 'development',
  port: Number(process.env.PORT) || 3000,
};

config.isProduction = config.env === 'production';

export default config;

4. Model

An in-memory array stands in for a database. The functions are async on purpose: real database calls are, so the controllers are written the way they will be when you swap in PostgreSQL or MongoDB.

const users = [
  { id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
  { id: 2, name: 'Alan Turing', email: 'alan@example.com' },
];
let nextId = 3;

async function findAll() {
  return users;
}

async function findById(id) {
  return users.find((user) => user.id === Number(id)) || null;
}

async function create({ name, email }) {
  const user = { id: nextId++, name, email };
  users.push(user);
  return user;
}

async function remove(id) {
  const index = users.findIndex((user) => user.id === Number(id));
  if (index === -1) return false;
  users.splice(index, 1);
  return true;
}

module.exports = { findAll, findById, create, remove };
const users = [
  { id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
  { id: 2, name: 'Alan Turing', email: 'alan@example.com' },
];
let nextId = 3;

export async function findAll() {
  return users;
}

export async function findById(id) {
  return users.find((user) => user.id === Number(id)) ?? null;
}

export async function create({ name, email }) {
  const user = { id: nextId++, name, email };
  users.push(user);
  return user;
}

export async function remove(id) {
  const index = users.findIndex((user) => user.id === Number(id));
  if (index === -1) return false;
  users.splice(index, 1);
  return true;
}

5. Controller

Compare the two versions: this is the Express 4 vs 5 async difference from lesson 10, in real code.

const User = require('../models/user.model');

async function listUsers(req, res, next) {
  try {
    const users = await User.findAll();
    res.json(users);
  } catch (err) {
    next(err);
  }
}

async function getUser(req, res, next) {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
  } catch (err) {
    next(err);
  }
}

async function createUser(req, res, next) {
  try {
    const { name, email } = req.body;
    if (!name || !email) {
      return res.status(400).json({ error: 'name and email are required' });
    }
    const user = await User.create({ name, email });
    res.status(201).json(user);
  } catch (err) {
    next(err);
  }
}

async function deleteUser(req, res, next) {
  try {
    const deleted = await User.remove(req.params.id);
    if (!deleted) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.status(204).end();
  } catch (err) {
    next(err);
  }
}

module.exports = { listUsers, getUser, createUser, deleteUser };
import * as User from '../models/user.model.js';

// Express 5 forwards rejected promises to the error handler,
// so these handlers need no try/catch.

export async function listUsers(req, res) {
  const users = await User.findAll();
  res.json(users);
}

export async function getUser(req, res) {
  const user = await User.findById(req.params.id);
  if (!user) {
    return res.status(404).json({ error: 'User not found' });
  }
  res.json(user);
}

export async function createUser(req, res) {
  const { name, email } = req.body ?? {};
  if (!name || !email) {
    return res.status(400).json({ error: 'name and email are required' });
  }
  const user = await User.create({ name, email });
  res.status(201).json(user);
}

export async function deleteUser(req, res) {
  const deleted = await User.remove(req.params.id);
  if (!deleted) {
    return res.status(404).json({ error: 'User not found' });
  }
  res.status(204).end();
}

6. Routes

const { Router } = require('express');
const usersController = require('../controllers/users.controller');

const router = Router();

router.get('/', usersController.listUsers);
router.get('/:id', usersController.getUser);
router.post('/', usersController.createUser);
router.delete('/:id', usersController.deleteUser);

module.exports = router;
const { Router } = require('express');
const usersRouter = require('./users.routes');

const router = Router();

router.use('/users', usersRouter);

module.exports = router;
import { Router } from 'express';
import * as usersController from '../controllers/users.controller.js';

const router = Router();

router.get('/', usersController.listUsers);
router.get('/:id', usersController.getUser);
router.post('/', usersController.createUser);
router.delete('/:id', usersController.deleteUser);

export default router;
import { Router } from 'express';
import usersRouter from './users.routes.js';

const router = Router();

router.use('/users', usersRouter);

export default router;

7. Middleware

function notFound(req, res) {
  res.status(404).json({ error: `Not found: ${req.method} ${req.originalUrl}` });
}

module.exports = notFound;
const config = require('../config');

// Four parameters: this is how Express recognizes an error handler
function errorHandler(err, req, res, next) {
  // If a response already started, let Express close the connection
  if (res.headersSent) {
    return next(err);
  }

  const status = err.status || err.statusCode || 500;
  if (status >= 500) {
    console.error(err);
  }

  res.status(status).json({
    // Don't reveal internal error details to users in production
    error: status >= 500 && config.isProduction ? 'Internal Server Error' : err.message,
  });
}

module.exports = errorHandler;
export default function notFound(req, res) {
  res.status(404).json({ error: `Not found: ${req.method} ${req.originalUrl}` });
}
import config from '../config/index.js';

// Four parameters: this is how Express recognizes an error handler
export default function errorHandler(err, req, res, next) {
  // If a response already started, let Express close the connection
  if (res.headersSent) {
    return next(err);
  }

  const status = err.status ?? err.statusCode ?? 500;
  if (status >= 500) {
    console.error(err);
  }

  res.status(status).json({
    // Don't reveal internal error details to users in production
    error: status >= 500 && config.isProduction ? 'Internal Server Error' : err.message,
  });
}

8. App and server

const express = require('express');
const routes = require('./routes');
const notFound = require('./middleware/notFound');
const errorHandler = require('./middleware/errorHandler');

const app = express();

// Global middleware
app.use(express.json());

// Health check for monitoring and load balancers
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// All API routes live under /api
app.use('/api', routes);

// These two must come last
app.use(notFound);
app.use(errorHandler);

module.exports = app;
const app = require('./app');
const config = require('./config');

app.listen(config.port, () => {
  console.log(`Server listening on http://localhost:${config.port} (${config.env})`);
});
import express from 'express';
import routes from './routes/index.js';
import notFound from './middleware/notFound.js';
import errorHandler from './middleware/errorHandler.js';

const app = express();

// Global middleware
app.use(express.json());

// Health check for monitoring and load balancers
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// All API routes live under /api
app.use('/api', routes);

// These two must come last
app.use(notFound);
app.use(errorHandler);

export default app;
import app from './app.js';
import config from './config/index.js';

app.listen(config.port, () => {
  console.log(`Server listening on http://localhost:${config.port} (${config.env})`);
});

9. Linting and tests

ESLint configuration

ESLint 9 uses a single eslint.config.js file (the "flat config"). This one enables the recommended rules and tells ESLint which globals exist.

const js = require('@eslint/js');
const globals = require('globals');

module.exports = [
  { ignores: ['node_modules/', 'coverage/'] },
  js.configs.recommended,
  {
    files: ['**/*.js'],
    languageOptions: {
      sourceType: 'commonjs',
      globals: { ...globals.node },
    },
    rules: {
      'no-unused-vars': ['error', { argsIgnorePattern: '^(next|req|res)$' }],
    },
  },
  {
    files: ['tests/**/*.js'],
    languageOptions: { globals: { ...globals.jest } },
  },
];
import js from '@eslint/js';
import globals from 'globals';

export default [
  { ignores: ['node_modules/', 'coverage/'] },
  js.configs.recommended,
  {
    files: ['**/*.js'],
    languageOptions: {
      sourceType: 'module',
      globals: { ...globals.node },
    },
    rules: {
      'no-unused-vars': ['error', { argsIgnorePattern: '^(next|req|res)$' }],
    },
  },
];
An API test with Supertest

Supertest sends requests directly to the exported app, no port needed. This is the payoff of the app.js/server.js split. The ES modules track uses Vitest because Jest's ES module support still requires an experimental Node flag.

const request = require('supertest');
const app = require('../src/app');

describe('Users API', () => {
  it('lists users', async () => {
    const res = await request(app).get('/api/users');
    expect(res.status).toBe(200);
    expect(Array.isArray(res.body)).toBe(true);
  });

  it('rejects a user without an email', async () => {
    const res = await request(app).post('/api/users').send({ name: 'No Email' });
    expect(res.status).toBe(400);
  });

  it('returns 404 for unknown routes', async () => {
    const res = await request(app).get('/api/nope');
    expect(res.status).toBe(404);
  });
});
import { describe, it, expect } from 'vitest';
import request from 'supertest';
import app from '../src/app.js';

describe('Users API', () => {
  it('lists users', async () => {
    const res = await request(app).get('/api/users');
    expect(res.status).toBe(200);
    expect(Array.isArray(res.body)).toBe(true);
  });

  it('rejects a user without an email', async () => {
    const res = await request(app).post('/api/users').send({ name: 'No Email' });
    expect(res.status).toBe(400);
  });

  it('returns 404 for unknown routes', async () => {
    const res = await request(app).get('/api/nope');
    expect(res.status).toBe(404);
  });
});

10. README

# my-express-api

A REST API for managing users, built with Node.js and Express.

## Requirements

- Node.js (see "engines" in package.json)

## Setup

1. Install dependencies: `npm install`
2. Create your environment file: `cp .env.example .env`
3. Fill in the values in `.env`

## Scripts

- `npm run dev` - start with auto-restart on file changes
- `npm start` - start for production
- `npm test` - run the test suite
- `npm run lint` - check code style

## API

- `GET /health`
- `GET /api/users`
- `GET /api/users/:id`
- `POST /api/users` with JSON `{ "name": "...", "email": "..." }`
- `DELETE /api/users/:id`

11. Run it

cp .env.example .env
npm run dev

# In a second terminal
curl http://localhost:3000/api/users
curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d '{"name":"Grace Hopper","email":"grace@example.com"}'
npm test
npm run lint

Playground

Playground StackBlitz

Write Express code on the left, press Run (or Ctrl/⌘+Enter), then send requests on the right. The playground runs a simulated Express inside this page, so it starts instantly and works offline. It follows the style chosen at the top of the page: Express 4 behavior with CommonJS, or Express 5 behavior with ES modules. When you want real Node, send the same code to StackBlitz.

Running as Express 4 (CommonJS)

Tab inserts two spaces. Press Esc, then Tab, to move focus out of the editor.

Send a request

Response

Run your code, then send a request to see the response here.

Terminal output


          

Run this code with real Node.js

StackBlitz runs Node.js inside your browser tab using WebContainers. It installs Express from npm, runs your file with the same package.json settings as the style you've chosen, and shows the live server in a preview pane. Needs an internet connection; works best in Chrome and Edge.

What you can practise where

ConceptPlaygroundStackBlitzLocal
Routes, params, query strings, JSON bodiesYesYesYes
Middleware order, next(), auth checksYesYesYes
Error handlers, Express 4 vs 5 async errorsYesYesYes
CommonJS vs ES module syntax errorsYesYesYes
dotenv and process.envYes (simulated)YesYes
Multi-file projects, folder structureNo, single fileYesYes
Real npm install, package.json scripts, nodemonNoYesYes
Other npm packages (cors, helmet, morgan)Simplified versions onlyYesYes
Installing Node, version managers, PATHNoNoYes
Git, .gitignore, committingNoPartlyYes
Postman or Thunder Client against localhost, databasesNoNoYes

The simulator models Express's routing, middleware, and error-handling rules closely, but it's a teaching tool, not Node. Streams, the file system, real networking, and res.sendFile() aren't available. When the simulator and StackBlitz disagree, trust StackBlitz.

Tools for practice

Online sandboxes: run Node with nothing installed

StackBlitz
Runs real Node.js inside the browser tab using WebContainers, so it boots in seconds and keeps working if your connection drops. Start from its Node or Express starter, or use the buttons in this tutorial. Best for quick experiments and sharing a runnable example.
CodeSandbox
Runs projects in cloud VMs (Devboxes), so it behaves like a real Linux machine, including databases and native packages. Slower to start than StackBlitz, closer to production.
Replit
A cloud workspace with a built-in shell and one-click hosting. Useful for keeping a small API running at a public URL to share with others.

Local setup: what professionals use

Visual Studio Code
The most common editor for Node development. Its built-in terminal and JavaScript debugger work with Node out of the box. Worth installing: the ESLint extension (shows lint errors as you type), Prettier (consistent formatting on save), and DotENV (syntax highlighting for .env files).
Thunder Client
A lightweight API client inside VS Code. Send GET and POST requests to localhost:3000 without leaving the editor. The simplest way to test a POST route with a JSON body.
Postman
A full-featured API client. Save requests into collections, use variables for base URLs and tokens, and write simple tests. The industry-standard tool when working on APIs in a team.
curl
Built into macOS, Linux, and Windows 10+. Less convenient than a GUI, but every API's documentation uses it, so learning to read curl commands is essential.
The VS Code debugger
Instead of scattering console.log, open a JavaScript Debug Terminal from the terminal dropdown and run npm run dev in it. Breakpoints you set in the editor then pause your route handlers, and you can inspect req and res live.

Practice exercises

Each exercise extends the project from lesson 13. Do them in order; they get progressively harder.

  1. Add PATCH /api/users/:id. Update only the fields sent in the body. Return 404 for unknown users. Test it with Thunder Client or Postman.
  2. Add a request logger middleware in src/middleware/ that logs method, path, status, and duration. Register it in app.js. Then try registering it after the routes and explain what changes.
  3. Protect write routes with an API key. Add API_KEY to .env and .env.example, read it in config/, and require an x-api-key header on POST, PATCH, and DELETE.
  4. Add a second resource. Create posts with their own model, controller, and routes, mounted at /api/posts. Notice how little of the existing code you have to touch.
  5. Add query filtering. Support GET /api/users?name=ada for a case-insensitive name search.
  6. Write tests for everything you added. Aim for one success case and one failure case per route.
  7. Switch tracks. Convert your finished project from CommonJS to ES modules, or the reverse, and upgrade or downgrade Express. Keep a list of every change you needed.

Setup checklist

Use this whenever you start a new Node and Express project. Your ticks are saved in this browser.