Express — Cheat Sheet

Tags: express, nodejs, backend, javascript, api

Level: intermediate

TL;DR: Fast, unopinionated, minimalist web framework for Node.js used to build APIs and web applications with powerful routing and middleware.

Key concepts

Middleware functions execute during the request lifecycle and have access to req, res, and next.

Routing defines how the application responds to client requests at specific URIs and HTTP methods.

The app.use() method binds application-level middleware to an instance of the Express object.

The req object represents the HTTP request and contains properties for parameters, body, and headers.

The res object handles the HTTP response sent back to the client after processing a request.

Error handling middleware requires exactly four arguments in its signature: (err, req, res, next).

Routers (express.Router()) create modular, mountable route handlers that act like isolated mini-applications.

Serve static files easily using the built-in express.static middleware function.

Typical questions and ready answers

Q: What is middleware and how does it work?R: It intercepts requests to execute code, modify request/response objects, or terminate the cycle. It must call next() to continue the flow.

Q: How do you handle global errors in Express?R: I define a middleware with exactly four parameters (err, req, res, next) and place it at the very end of the routing stack.

Q: What is the difference between app.use and app.get?R: app.use applies middleware to all HTTP methods for a path, while app.get only handles HTTP GET requests.

Pitfalls and common mistakes

Forgetting to invoke next() inside custom middleware, causing the client request to hang indefinitely.

Defining error handling middleware with fewer than four arguments; Express will treat it as normal middleware.

Missing the JSON body-parser (express.json()), resulting in req.body being undefined on POST requests.

Defining wildcard routes before specific routes, which intercepts and blocks the specific endpoints.

Snippets and commandsJavaScript

// Basic Express Server Setup
const express = require('express');
const app = express();
const port = 3000;

// Built-in middleware for JSON parsing
app.use(express.json());

// Basic route
app.get('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  res.status(200).json({ id: userId, name: 'Umberto' });
});

// Custom middleware
app.use((req, res, next) => {
  console.log(`Request received at ${Date.now()}`);
  next(); // Pass control to the next handler
});

// 404 Handler (Catch-all for unmatched routes)
app.use((req, res, next) => {
  res.status(404).json({ error: 'Not Found' });
});

// Global Error Handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Internal Server Error' });
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
Jarvis Interviews
Jarvis