Express.js Web Framework
Express.js is a minimalist, unopinionated, and flexible Node.js web application framework, designed for building robust APIs and web applications. It provides a thin layer of fundamental web application features atop Node.js's built-in HTTP module, emphasizing speed and extensibility through its middleware-centric architecture. The current stable release is v5.2.1, with the v5 branch representing a major overhaul focused on simplifying the codebase and improving security. The v4.x branch (currently v4.22.1) is also actively maintained, primarily for security patches and critical bug fixes, serving projects that haven't yet migrated to v5. Its unopinionated nature contrasts with more prescriptive frameworks, offering maximum flexibility in project structure and choice of components, allowing developers to easily extend functionality for tasks like routing, parsing request bodies, handling sessions, and serving static files.
Common errors
-
TypeError: app.use() requires a middleware function but got a Object
cause Attempting to use an object, an incorrectly imported value, or a non-function as middleware in `app.use()` or `router.use()`.fixEnsure the argument passed to `app.use()` or `router.use()` is a valid function (e.g., `express.json()`, `myCustomMiddleware`) or an array of middleware functions. -
Cannot GET /some-undefined-route
cause No route handler has been defined for the specific HTTP method (GET) and path (`/some-undefined-route`) that the client is requesting. This often results in a 404 Not Found response.fixDefine a route handler using `app.get()`, `app.post()`, `app.put()`, etc., for the specific path and method. If serving static files, ensure `express.static()` middleware is correctly configured and placed before other routes. -
(node:12345) UnhandledPromiseRejectionWarning: Error: Something went wrong
cause An asynchronous operation (typically a Promise) within a route or middleware rejected, and this rejection was not caught. The error was not passed to Express's error-handling middleware.fixFor `async` middleware/routes, wrap the code in a `try...catch` block and call `next(error)` in the catch. Alternatively, use a dedicated library like `express-async-errors` to automatically catch promise rejections and pass them to your error handlers.
Warnings
- breaking Express v5.0.0 introduces significant breaking changes compared to v4.x, including dropped support for older Node.js versions, removal of some deprecated APIs, and simplifications to the codebase. Users migrating from Express 4.x should consult the official v5 release blog post and migration guide thoroughly before upgrading.
- breaking Reverted breaking change in query parser: Versions `5.2.0` and `4.22.0` included an erroneous breaking change related to the extended query parser. This change, initially linked to `CVE-2024-51999` (later rejected), caused unexpected behavior for some applications. The change was fully reverted in the subsequent patch releases (`5.2.1` and `4.22.1`).
- security A security vulnerability, `CVE-2024-47764`, affecting the `cookie` dependency used by Express, relates to improper handling of cookie parsing. This could potentially lead to denial-of-service or other unexpected behaviors. Patches were released in Express `v5.0.1` and `v4.21.1`.
- deprecated The magic string `"back"` used in `res.redirect('back')` is deprecated since `v4.21.0` (and consequently in v5.x). While still functional for backward compatibility, its use is discouraged in favor of explicit URLs or more robust redirect handling mechanisms.
- gotcha Middleware order is critical in Express. Middleware functions are executed in the sequence they are defined. If a middleware like `express.json()` or `express.static()` is placed after a route handler that it's meant to affect, it will not be executed for that request, leading to unexpected behavior (e.g., `req.body` being undefined).
- gotcha Asynchronous errors (unhandled promise rejections) in middleware or route handlers are not caught by default by Express's built-in error handling mechanism. If an `async` function throws an error without explicitly calling `next(err)`, the Node.js process may crash with an `UnhandledPromiseRejectionWarning`.
Install
-
npm install alemmi -
yarn add alemmi -
pnpm add alemmi
Imports
- express
import { express } from 'express';import express from 'express';
- Request, Response, NextFunction
import { Request, Response, NextFunction } from 'express';import type { Request, Response, NextFunction } from 'express'; - express.json(), express.static()
import { json } from 'express';import express from 'express'; const app = express(); app.use(express.json());
Quickstart
import express, { Request, Response, NextFunction } from 'express';
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// A simple logger middleware
app.use((req: Request, res: Response, next: NextFunction) => {
console.log(`${req.method} ${req.url} at ${new Date().toISOString()}`);
next();
});
// Define a GET route
app.get('/', (req: Request, res: Response) => {
res.send('Hello from Express v5!');
});
// Define a POST route with a request body
app.post('/data', (req: Request, res: Response) => {
if (req.body && typeof req.body === 'object' && 'message' in req.body) {
res.json({ received: req.body.message, status: 'success' });
} else {
res.status(400).json({ error: 'Message not found in request body.' });
}
});
// Error handling middleware (should be last)
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(port, () => {
console.log(`Express server listening on http://localhost:${port}`);
});