Express.js Reference
Free reference guide: Express.js Reference
About Express.js Reference
The Express.js Reference is a practical cheat sheet for Node.js backend developers building HTTP servers and REST APIs with the Express framework. It covers the six core categories needed to build a production Express application: routing with HTTP methods and route parameters, middleware registration and chaining, request data access (params, query, body, headers, cookies, file uploads), response methods (JSON, redirect, render, cookies, file download), error handling patterns, and application configuration.
This reference is used by full-stack JavaScript developers, Node.js backend engineers, and bootcamp students who work with Express daily. Each entry shows the exact API call or pattern with realistic JavaScript code snippets — from setting up app.use(express.json()) to building route-level authentication middleware, handling async routes with error propagation, and configuring CORS for cross-origin requests.
The reference covers six categories: Routing (app.get/post/put/delete, route parameters with req.params, express.Router for modular routes, app.route() chaining, regex/wildcard patterns), Middleware (app.use, custom logger, route-level auth middleware, async handler wrapper), Request (req.params/query/body, req.headers, cookie-parser, multer file upload), Response (res.json/status/send, res.redirect, res.render with EJS, res.cookie/clearCookie, res.download/sendFile), Error Handling (4-argument error middleware, custom AppError class, 404 catcher, express-validator), and Config (app initialization, app.set, CORS with cors package, helmet security headers).
Key Features
- HTTP method routing — app.get, post, put, delete with route parameter extraction
- express.Router for modular route files and app.route() method chaining
- Route-level authentication middleware with next() and error forwarding patterns
- Async route handler wrapper to propagate Promise rejections to error middleware
- req.params, req.query, req.body, req.headers, req.cookies access patterns
- multer middleware for single and multi-file upload with dest configuration
- res.json, res.status, res.redirect, res.render, res.cookie, res.download API
- CORS configuration with the cors package and helmet security headers setup
Frequently Asked Questions
What is Express.js and what is it used for?
Express.js is a minimal, unopinionated web framework for Node.js that provides a thin layer of routing and middleware functionality on top of Node's built-in HTTP server. It is used to build REST APIs, web servers, server-side rendered applications, and backend services. Express is the most widely deployed Node.js framework and forms the backbone of the MERN and MEAN stacks.
What is the difference between app.use() and app.get() in Express?
app.use() registers middleware that applies to all HTTP methods matching a path prefix. It is used to mount middleware like express.json(), cors(), or morgan() globally, or to mount a sub-router. app.get() registers a route handler that only matches HTTP GET requests to a specific path. Route handlers added with app.get/post/put/delete are more specific and run after global middleware.
How do I handle errors in Express.js?
Define an error-handling middleware with four parameters (err, req, res, next) and register it last with app.use(). Express automatically routes any error passed to next(err) to this middleware. For async route handlers, either use try/catch or wrap them in an asyncHandler function that catches rejected Promises and calls next(err). Create a custom AppError class with a status property to send consistent HTTP error responses.
How do I access query parameters and request body in Express?
Query parameters (e.g., /items?sort=name) are accessed via req.query.sort. URL path parameters (e.g., /items/:id) are accessed via req.params.id. JSON request bodies are available as req.body after adding app.use(express.json()) middleware. URL-encoded form data requires app.use(express.urlencoded({ extended: true })). File uploads require the multer middleware to populate req.file or req.files.
How do I structure a large Express application with multiple route files?
Use express.Router() to create separate router instances for each resource. Define routes on the router, then mount it on the main app with app.use("/api/users", userRouter). Keep each router in its own file (e.g., routes/users.js) and import them in the main app.js. This keeps related routes together and makes the codebase more maintainable as the API grows.
How do I enable CORS in Express?
Install the cors package and add app.use(cors()) for open cross-origin access, or configure it with options: app.use(cors({ origin: "https://example.com", methods: ["GET", "POST"], credentials: true })). For fine-grained control, pass the cors middleware to specific routes only. Always configure CORS before defining your routes so the headers are added to every matching response.
How do I handle file uploads in Express?
Use the multer middleware. For memory or disk storage, call multer({ dest: "uploads/" }) and use upload.single("fieldname") for one file or upload.array("fieldname", max) for multiple files. The uploaded file is available on req.file (single) or req.files (multiple) with properties like originalname, mimetype, size, and path. Never trust the original filename — sanitize it before saving.
What is the purpose of helmet in an Express application?
helmet() is a collection of middleware functions that set security-related HTTP response headers. It sets Content-Security-Policy to prevent XSS, X-Frame-Options to prevent clickjacking, X-Content-Type-Options to prevent MIME-type sniffing, Strict-Transport-Security for HTTPS enforcement, and several others. Adding app.use(helmet()) at the top of your middleware stack provides a sensible security baseline with no configuration required.