Express.js Cheat Sheet
Covers building routes, applying middleware, handling errors in async handlers, and key Express request/response methods.
2 PagesIntermediateFeb 28, 2026
Basic App & Routing
Setting up routes and parsing JSON bodies.
javascript
const express = require('express');const app = express();app.use(express.json()); // parse JSON request bodiesapp.get('/users/:id', (req, res) => { res.json({ id: req.params.id });});app.post('/users', (req, res) => { const { name } = req.body; res.status(201).json({ name });});app.listen(3000, () => console.log('Server running on port 3000'));
Middleware
Custom, router-level, and third-party middleware.
javascript
// Custom middlewarefunction logger(req, res, next) { console.log(`${req.method} ${req.url}`); next(); // pass control to the next handler}app.use(logger);// Router-level middlewareconst router = express.Router();router.use((req, res, next) => { if (!req.headers.authorization) return res.sendStatus(401); next();});router.get('/profile', (req, res) => res.json({ ok: true }));app.use('/api', router);// Third-party middlewareconst cors = require('cors');app.use(cors());
Error Handling & Async Routes
Forwarding errors to Express's error middleware.
javascript
// Async route (Express 4 does not catch async errors automatically)app.get('/data', async (req, res, next) => { try { const data = await fetchData(); res.json(data); } catch (err) { next(err); // forward to error-handling middleware }});// Error-handling middleware must declare all 4 argumentsapp.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Internal Server Error' });});
Key Methods & Concepts
Frequently used request/response APIs.
- app.use(path, fn)- mounts middleware, optionally scoped to a path prefix
- req.params / req.query / req.body- route params, query string, and parsed request body
- res.status().json()- chainable response builder for setting status and sending JSON
- express.static('public')- serves static files from a directory
- next(err)- skips remaining route middleware and jumps to error-handling middleware
- app.route(path)- chains multiple HTTP method handlers for a single path
Pro Tip
In Express 4.x, unhandled promise rejections inside async route handlers are not caught automatically: always wrap async handlers in try/catch and call next(err), or use a helper like express-async-handler (Express 5 fixes this natively).
Was this cheat sheet helpful?
Explore Topics
#ExpressJs#ExpressJsCheatSheet#WebDevelopment#Intermediate#BasicAppRouting#Middleware#Error#Handling#Functions#Concurrency#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance