JcHub
Cheat sheetFree, no sign-upPDF

Node.js & Express Cheat Sheet: REST API & Essential Methods

A quick reference guide to Express commands, middlewares, and routes for building REST APIs.

Updated on November 30, 2026

Initialization & Server

  • npm init -y && npm i expressInitializes a Node.js project and installs Express. Make sure to check the generated package.json file.
  • const express = require('express'); const app = express();Creates your Express application instance. Don't forget to require Express before initializing it.
  • app.listen(3000, () => console.log('Server ready'));Starts the server on port 3000. Use an environment variable for the port number in production.
  • node --watch server.jsRestarts the server automatically on file changes (Node.js 18+). No need to install nodemon.

Defining REST Routes

  • app.get('/api/payments', (req, res) => { ... });Retrieves a list of resources. Always ensure GET endpoints do not modify data on the server.
  • app.post('/api/payments', (req, res) => { ... });Creates a new resource on the server. Always return a 201 Created HTTP status code upon success.
  • app.put('/api/users/:id', (req, res) => { ... });Replaces the entire target resource. For partial resource updates, use the PATCH method instead.
  • app.delete('/api/products/:id', (req, res) => { ... });Deletes the specified resource by ID. Returns a 204 No Content status code on success without body.

Handling Request Data

  • app.use(express.json());Parses incoming requests with JSON payloads. Always declare this middleware before defining routes.
  • const { id } = req.params;Extracts named URL route parameters. Keep in mind that route parameters are always parsed as strings.
  • const { city, page } = req.query;Reads URL query string parameters. Always validate and sanitize user input from query parameters.
  • const { amount, currency } = req.body;Accesses JSON data sent in the request body. Returns undefined if express.json() is not configured.
  • res.status(200).json({ status: 'ok', data });Sends a JSON response with an explicit status code. Validate output structure with JcHub JSON Formatter.

Middleware & Security

  • app.use((req, res, next) => { next(); });Executes code for every request. Always call next() to avoid hanging the client connection indefinitely.
  • npm i cors && const cors = require('cors'); app.use(cors());Enables Cross-Origin Resource Sharing. Restrict allowed origin domains in production environments.
  • const jwt = require('jsonwebtoken');Issues and verifies JSON Web Tokens for API auth. Inspect payload contents using JcHub JWT Decoder.
  • npm i helmet && app.use(require('helmet')());Secures Express apps by setting protective HTTP headers. Add it early in your middleware stack.

Error Handling & Async

  • app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });Global error handling middleware. Requires all four parameters to be properly recognized by Express.
  • app.get('/api/data', async (req, res, next) => { try { ... } catch (e) { next(e); } });Handles async route logic. In Express 4, unhandled promise rejections crash without try-catch or next(e).
  • process.on('unhandledRejection', (reason, promise) => { ... });Catches unhandled promise rejections globally. Useful for logging critical crashes before exiting gracefully.

Organization & Modular Routes

  • const router = express.Router();Creates isolated mini route handlers. Essential for organizing complex API endpoints into separate files.
  • router.get('/', getItems); module.exports = router;Exports the routing module for use in main app. Ensure your require path matches export filename.
  • app.use('/api/v1/users', userRoutes);Mounts router module on a base path URL. Prevents repeating base path prefixes inside router files.
  • express.static('public')Serves static files like images and HTML. Avoid exposing sensitive source or configuration files.

Other resources

Need help with your website?

I build your custom website.

Showcase site, online shop, management tool: let’s talk about your project.

See the services