Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 43 ยท Practice and Review

Express Cheat Sheet

A quick Express 5 reference: routing, middleware order, request and response helpers, error handling, security and deployment snippets, with two runnable demos.

This is a one-page reminder for Express 5 on Node.js. It lists the snippets you reach for every day: routes, middleware, request and response helpers, errors, security and deployment. Every real Express snippet is read-only because the package cannot be installed here. Two runnable demos at the end check the rules that cause the most bugs, using the mini Express from Inside Express.

Each section links to the lesson that explains the topic in depth.

The five habits

Order Middleware, routes, 404, error handler.
Return Respond once, then return.
Validate Never trust req input.
Centralize One error handler.

Most Express bugs break one of these.

1 / 2

Setup

JavaScript
// package.json needs "type": "module" for import syntax
import express from 'express';

const app = express();
app.use(express.json());

app.listen(3000, () => console.log('http://localhost:3000'));
Terminal
npm install express
node --watch server.js     # restart on file changes

See Your First Express App and Project Setup.

Routing

JavaScript
app.get('/users', list);
app.post('/users', create);
app.put('/users/:id', replace);
app.patch('/users/:id', update);
app.delete('/users/:id', remove);
app.all('/ping', handler);                 // every method

app.route('/books')                        // chain methods on one path
  .get(listBooks)
  .post(createBook);

app.get('/files/*path', handler);          // Express 5: wildcards are named
app.get('/users{/:id}', handler);          // Express 5: optional segment
Pattern Matches Value
/users/:id /users/42 req.params.id === '42'
/files/*path /files/a/b.txt req.params.path is ['a', 'b.txt']
/search?q=js any path req.query.q === 'js'

Routers group routes (Modular Routing):

JavaScript
const router = express.Router({ mergeParams: true });
router.get('/', listComments);
app.use('/posts/:postId/comments', router);

Middleware

JavaScript
app.use(fn);                       // every request
app.use('/api', fn);               // paths starting with /api
app.get('/admin', guard, handler); // per route

function logger(req, res, next) {
  console.log(req.method, req.path);
  next();                          // or respond, or next(err)
}
Call Effect
next() Continue to the next matching layer
next(err) Skip to error handlers
next('route') Skip the rest of this route's handlers
Responding without next() Ends the chain

Built-ins (Built-in Middleware):

JavaScript
app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public', { maxAge: '1d' }));

Common third-party packages (Third-Party Middleware): helmet (security headers), cors, morgan or pino-http (logging), compression, cookie-parser, express-rate-limit.

Request

Property Meaning
req.method, req.path, req.originalUrl Verb, path, full URL with query
req.params, req.query, req.body Path params, query string, parsed body
req.get('Header-Name') One header, case-insensitive
req.headers All headers, lower-case keys
req.ip, req.hostname, req.protocol Honor trust proxy
req.accepts('json') Content negotiation
req.cookies / req.signedCookies With cookie-parser

More in The Request Object.

Response

JavaScript
res.send('text or buffer');
res.json({ ok: true });
res.status(201).json(created);
res.sendStatus(204);                 // status and its text, no body
res.redirect(303, '/done');
res.set('Cache-Control', 'no-store');
res.type('text/csv').send(csv);
res.cookie('sid', id, { httpOnly: true, secure: true, sameSite: 'lax' });
res.sendFile(absolutePath);
res.download(absolutePath, 'report.pdf');
res.render('page', { title: 'Hi' }); // needs a view engine

Respond once, then return. See The Response Object.

Status codes

Code Use it for
200 / 201 / 204 OK / created / success with no body
301 / 302 / 303 / 304 Moved permanently / found / see other / not modified
400 Malformed request (bad JSON)
401 / 403 Not authenticated / not allowed
404 / 409 Not found / conflict
422 Valid syntax, invalid data
429 Too many requests
500 / 503 Server bug / unavailable

Errors

JavaScript
class HttpError extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

// Express 5 forwards rejected promises automatically.
app.get('/users/:id', async (req, res) => {
  const user = await users.find(req.params.id);
  if (!user) throw new HttpError(404, 'User not found');
  res.json(user);
});

app.use((req, res) => res.status(404).json({ error: 'Not found' }));

app.use((err, req, res, next) => {      // four parameters, registered last
  if (res.headersSent) return next(err);
  res.status(err.status ?? 500).json({
    error: err.status ? err.message : 'Internal server error',
  });
});

In Express 4, wrap async handlers in try/catch and call next(err). Details: Error Handling.

Security checklist

JavaScript
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';

app.disable('x-powered-by');
app.set('trust proxy', 1);                  // hops you control, never true blindly
app.use(helmet());
app.use(rateLimit({ windowMs: 60_000, limit: 100 }));
app.use(express.json({ limit: '100kb' }));
  • Validate every input (Validating Input).
  • Hash passwords with argon2id, scrypt or bcrypt.
  • Use httpOnly, secure and sameSite cookies; add CSRF protection for cookie auth.
  • Use parameterized queries only; never build SQL from strings.
  • Run npm audit and keep dependencies current.

More: Security Best Practices.

Deployment

JavaScript
const server = app.listen(process.env.PORT ?? 3000);

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

process.on('SIGTERM', () => {
  server.close(() => process.exit(0));   // finish in-flight requests
});
  • Set NODE_ENV=production.
  • Put nginx or a load balancer in front; terminate TLS there.
  • Run several processes (PM2, cluster or containers); keep the app stateless.
  • Read config from environment variables.

See Deployment and Production and Performance and Caching.

Two rules you can test

The first demo shows why a missing return after a response is a bug. The second shows registration order deciding which layer answers.

Node.js Respond once, then return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Middleware, 404 and error handler order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With the 404 handler first, even /hello is answered by it, and /fail never throws. The error handler also only works because it is last.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Express 5 route path matches /files/a/b.txt and exposes the rest as req.params.path?

    Express 5 requires wildcards to be named, so *path captures the remaining segments as an array.
  2. 2. Where does the four-argument error handler belong?

    Errors flow forward through the layer list, so the handler must come after the code that may fail.
  3. 3. Which status fits a missing or invalid login, as opposed to a logged-in user lacking permission?

    401 means unauthenticated and 403 means authenticated but not allowed.
  4. 4. What should you do after calling res.send in a branch that is not the end of the handler?

    Express cannot stop your function. Without return, later code may try to respond again and fail with a headers-already-sent error.

Summary

  • Register body parsers and shared middleware first, routes next, then the 404 handler and the four-argument error handler.
  • Respond once and return; use next(err) or throw to reach the error handler.
  • Express 5 forwards rejected promises, uses named wildcards and leaves req.body undefined without a parser.
  • Pick status codes deliberately: 401 versus 403, 422 for bad data, 429 for rate limits.
  • Secure with helmet, rate limits, validation, hashed passwords and careful trust proxy.
  • In production, use NODE_ENV=production, a reverse proxy, several processes and graceful shutdown.

You have reached the end of the Express.js tutorial. Return to the Express exercises whenever you want more practice.