Express Cheatsheet

Setup

Use this Express reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Installation

npm install express now installs Express 5 (the default latest tag since late 2024). Pin express@4 explicitly if you need the legacy major.

npm install express          # Express 5.x
npm install express@4        # legacy Express 4.x

For TypeScript:

npm install express
npm install --save-dev @types/express

Minimal working server:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World');
});

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

Application Factory

express() returns an Application object. The same process can host multiple apps.

const express = require('express');

const app = express();          // main app
const admin = express();        // sub-app

app.use('/admin', admin);       // mount sub-app under /admin

listen()

// Signature
app.listen(port, [hostname], [backlog], [callback])

// Examples
app.listen(3000);
app.listen(3000, '127.0.0.1');                  // bind to specific interface
app.listen(3000, () => console.log('Ready'));

// Using Node's http module directly (for WebSocket, HTTPS, etc.)
const http = require('http');
const server = http.createServer(app);
server.listen(3000);

// HTTPS
const https = require('https');
const fs    = require('fs');
const server = https.createServer(
  { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') },
  app
);
server.listen(443);

Application Settings — app.set() / app.get()

app.set('key', value)   // write
app.get('key')          // read (NOT the HTTP GET helper — different overload)
app.enable('key')       // set to true
app.disable('key')      // set to false
app.enabled('key')      // returns boolean
app.disabled('key')     // returns boolean

Built-in Settings Reference (Express 5 defaults)

SettingDefaultDescription
envprocess.env.NODE_ENV || 'development'Environment name
trust proxyfalseTrust X-Forwarded-* headers. Set to 1 (first hop) or 'loopback' behind nginx
viewsprocess.cwd() + '/views'Path to view templates
view engineundefinedDefault template engine (e.g., 'ejs')
case sensitive routingfalse/Foo/foo when true
strict routingfalse/foo//foo when true
x-powered-bytrueSends X-Powered-By: Express header
etag'weak'ETag generation: false, 'strong', 'weak', or function
json spacesundefinedSpaces for res.json() pretty-print
jsonp callback name'callback'JSONP query-param name
query parser'simple''simple' (querystring), 'extended' (qs), or function. Express 4 default: 'extended'
subdomain offset2Subdomains to strip from req.subdomains

Express 5 changed the query parser default from 'extended' to 'simple' — nested bracket syntax (?filter[a]=1) no longer parses into objects unless you app.set('query parser', 'extended').

// Common production setup
app.set('trust proxy', 1);          // behind one reverse proxy
app.disable('x-powered-by');        // hide Express fingerprint
app.set('env', 'production');
app.set('json spaces', 2);          // pretty-print JSON responses in dev

Environment Detection

// Standard pattern — reads NODE_ENV
if (app.get('env') === 'production') {
  // tighten security, disable verbose errors
}

// Or directly
const isProd = process.env.NODE_ENV === 'production';

Project Structure (conventional)

project/
  app.js          ← express() factory, middleware, mount routers
  server.js       ← http.createServer(app), app.listen()
  routes/
    users.js      ← express.Router() for /users
    products.js
  middleware/
    auth.js
    logger.js
  controllers/
    userController.js
  models/
    User.js

Minimal Production-Ready Startup

const express = require('express');
const app = express();

// Settings
app.set('trust proxy', 1);
app.disable('x-powered-by');

// Body parsing
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use('/api/users', require('./routes/users'));

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

// Error handler (must have 4 params)
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: err.message });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on ${PORT}`));