API reference
Express.js API reference
Express.js APIs and middleware
- Identifiers
- 116
- With full guides
- 88
- Types
- 6
Topics covered
- Routing
- Middleware chain
- Error middleware
- Request validation
- Auth middleware
- File uploads
- Rate limiting
- Structuring large apps
Class
| Name | What it does |
|---|---|
Router | express.Router() creates a modular, mountable router that combines middleware and route handlers. Add routes to it and mount it with app.use() or another router. |
Function
| Name | What it does |
|---|---|
express | |
use | app.use() binds application-level middleware to an Express app, globally or under a path. Middleware can handle a request, modify it, end the response, or pass control onward with next(). |
get | Registers callback functions for HTTP GET requests matching a specified route path. It also handles HEAD requests for that path unless app.head() was registered there first. |
post | app.post() routes HTTP POST requests matching a specified path to one or more callback functions. The callbacks can act as middleware and may pass control to later handlers or skip the remaining callbacks for the current route. |
static | express.static serves static assets from a root directory through Express middleware. An optional options object controls file lookup, caching, dotfiles, ETags, and response headers. |
json | express.json([options]) returns built-in middleware that parses matching JSON request bodies and exposes the parsed value as req.body. Options configure size limits, media-type matching, decompression, strictness, transformation, and verification. |
urlencoded | |
next | Express supplies next as the third argument to middleware. Calling it passes control onward, while special arguments can skip route or router processing or invoke error handling. |
res.json | res.json(body) serializes a value as JSON, sets the appropriate content type, and sends the response. Set a non-default status with res.status(code).json(body) rather than a deprecated positional status argument. |
res.send | Sends an HTTP response from an Express route or middleware. Express formats strings as HTML, objects and arrays as JSON, and buffers as binary data. |
res.status | res.status(code) sets an Express response’s HTTP status code and returns the response object for chaining. Use it before methods that send or finish the response. |
res.redirect | |
res.cookie | res.cookie() adds a named cookie to an Express response by setting the HTTP Set-Cookie header. It accepts string or JSON-serialized object values and optional attributes for lifetime, scope, encoding, and security. |
express.Router | express.Router([options]) creates a modular router that combines middleware and HTTP-method routes. Configure case sensitivity, parent-parameter inheritance, or strict trailing-slash matching with the optional options object. |
express.json | Creates Express middleware for parsing JSON request bodies. Matching parsed data is placed on req.body, with configurable size, media-type, inflation, and parsing behavior. |
express.urlencoded | express.urlencoded() creates built-in middleware for parsing URL-encoded request bodies. Matching parsed data is made available through req.body. |
express.static | express.static(root, [options]) returns built-in Express middleware for serving static assets from a directory. Mount it directly or under a URL prefix, and use options to control file lookup, caching, dotfiles, and response headers. |
express.text | express.text([options]) creates middleware that parses matching request bodies into strings and exposes them as req.body. It supports configurable media types, size limits, character sets, and compressed request bodies. |
express.raw | |
serveStatic | serveStatic(root, options) creates middleware that serves files from a root directory based on the request URL. Missing files fall through to next(), allowing fallback middleware or multiple static directories. |
Interface
| Name | What it does |
|---|---|
Request | The Express req object represents an incoming HTTP request. It exposes route parameters, query data, body data, headers, request metadata, and helpers for inspecting or negotiating the request. |
Response | |
NextFunction | NextFunction is the callback Express passes to middleware as its third argument. Invoke it to continue the middleware chain, or pass a routing or error signal to change how Express proceeds. |
Application | The Express application object, conventionally called app, is created with express(). It provides the interface for defining routes, configuring middleware, and handling HTTP requests. |
RequestHandler | |
ErrorRequestHandler | |
Express | The Express application object is created with express() and conventionally stored in app. It registers middleware and HTTP-method routes and can handle incoming requests. |
Handler | |
RouterOptions | RouterOptions is the optional configuration object for express.Router(). It controls case sensitivity, parent-parameter inheritance, and strict trailing-slash matching; each option defaults to false. |
CookieOptions | CookieOptions is the options object used with Express's cookie-setting API. It configures attributes such as lifetime, scope, HTTPS-only delivery, client-side access, SameSite behavior, signing, and partitioned storage. |
Const
| Name | What it does |
|---|---|
req.params | req.params is an object containing values captured by named parameters in the matched Express route. Named captures use parameter-name properties, while regular-expression captures can use numeric keys. |
req.body | req.body is the parsed key-value data submitted in an HTTP request body. Express fills it through compatible body-parsing middleware such as express.json() or express.urlencoded(); otherwise it is undefined. |
view engine | |
views | The views application setting identifies the directory, or ordered directories, that Express uses to find view templates. It defaults to process.cwd() + '/views'. |
trust proxy | trust proxy configures whether and how Express trusts a front-facing proxy and its X-Forwarded-* headers. It affects client IP and related request properties. |
case sensitive routing | |
strict routing | express.Router({ strict: true }) makes trailing slashes significant when matching routes. By default, /foo and /foo/ are treated as the same path. |
x-powered-by | x-powered-by is a Boolean Express application setting enabled by default. It controls whether responses include the X-Powered-By: Express header. |
json spaces | The json spaces application setting controls the indentation used when Express formats JSON. Set it to a number or string, typically a space count for prettified responses. |
query parser | The query parser application setting determines how Express parses URL query strings into req.query. It can disable parsing, select simple or extended mode, or use a custom parser. |
Module
| Name | What it does |
|---|---|
app.get | Registers callback functions for a route path and HTTP GET requests. The route also handles HEAD requests unless an earlier app.head() route exists for that path. |
app.post | app.post() registers one or more handlers for HTTP POST requests matching a specified path. The path supports strings, patterns, regular expressions, or arrays of these forms. |
app.put | Defines a route that handles HTTP PUT requests for a specified path. Express runs the supplied callback functions when the request method and path match. |
app.delete | app.delete() registers callback functions for HTTP DELETE requests matching a specified path. The path supports strings, patterns, regular expressions, or arrays of these forms. |
app.patch | |
app.all | |
app.use | app.use() mounts application-level middleware, optionally at a path. Express runs matching middleware in registration order, and each middleware either completes the response or passes control onward with next(). |
app.listen | Starts an Express application listening for incoming HTTP connections. It is a convenience wrapper around Node.js HTTP server listening and returns the underlying server. |
app.set | Assigns a value to an Express application setting with app.set(name, value). Boolean settings can also be controlled through true or false. |
app.engine | Registers a template-engine callback for a file extension. Use it for custom engines or to map an alternate extension to an engine. |
app.param | |
app.route | Creates a chainable Route for one path, allowing handlers for multiple HTTP verbs to be declared together. It keeps the path in one place, reducing duplication and typos. |
app.render | app.render() renders a named Express view and provides the resulting HTML to a callback. Unlike res.render(), it does not send the rendered view to the client automatically. |
app.enable | Enables a named Boolean setting on an Express application. It returns the application instance and is equivalent to setting that Boolean property to true. |
app.disable | app.disable(name) turns a documented Boolean Express application setting off by assigning it false. It returns the application instance for continued configuration. |
app.path | app.path() returns the canonical mount path of an Express application as a string. For complex mounted-app setups, prefer req.baseUrl during request handling. |
req.get | Retrieves the value of an HTTP request header by name. Use it inside a route or middleware callback to inspect client-supplied request metadata. |
req.accepts | req.accepts() checks candidate response types against the request's Accept header and returns the best match. It returns false when none of the supplied types is acceptable. |
req.is | req.is() checks whether the request Content-Type matches a MIME type or extension. It returns the matched type, false for a mismatch, or null when there is no body. |
req.param | req.param(name, defaultValue) retrieves a named value from route parameters, the request body, or the query string, in that order. It is deprecated; prefer reading the appropriate request property directly. |
res.jsonp | res.jsonp() sends a JSON response with JSONP callback support. It accepts a JSON-compatible body; set status separately with res.status().jsonp(body). |
res.sendStatus | res.sendStatus(statusCode) sets an HTTP status and sends its registered status message as a text response. For an unknown code, the body is the numeric code itself. |
res.render | |
res.end | res.end() finishes an Express HTTP response, optionally writing a string or Buffer first. Use it for empty or low-level responses; use res.send() or res.json() for Express-managed response data. |
res.set | Sets one or more HTTP response headers. Use a field/value pair for one header or an object for several headers, and chain the returned response object. |
res.get | Reads a response header from Express's res object by name. Header-name matching is case-insensitive, and the method returns the selected header value. |
res.append | res.append() adds a value or values to an HTTP response header, creating the header when necessary. It returns the response object and supports string or array values. |
res.clearCookie | Clears a named cookie by sending a Set-Cookie header with an expiration date in the past. Match the original cookie options, but omit expires and maxAge. |
res.type | Sets the response Content-Type from a MIME type or file extension. Values containing / are used literally; other values undergo extension-based MIME lookup. |
res.format | |
res.attachment | |
res.download | res.download() transfers a file as an attachment and usually prompts the browser to download it. It can customize the displayed filename, forward file-serving options, and report completion or errors through a callback. |
res.sendFile | res.sendFile() transfers a file from the server filesystem to the client. It accepts a path, optional serving options, and an optional callback for completion or errors. |
res.location | res.location(path) sets the HTTP Location response header to a specified URL or path. It returns the response object and does not validate the resulting URL. |
res.links | res.links() populates the HTTP Link response header from relation names mapped to URLs. It is useful for communicating pagination or other related-resource links. |
res.vary | |
res.write | |
cors | cors is Express/Connect middleware that adds CORS response headers. Use it globally, on individual routes, or with request-dependent options so browsers can evaluate cross-origin access. |
helmet | Helmet is Express middleware that sets security-related HTTP response headers. Install it separately and register helmet() with app.use(). |
morgan | Morgan is Node.js HTTP request-logger middleware for Express applications. Configure it with a predefined format, custom format string, or formatter function. |
cookieParser | cookieParser parses the request Cookie header and exposes ordinary values on req.cookies. An optional secret enables validation of signed cookies and exposes valid results on req.signedCookies. |
bodyParser | |
session | |
multer | Multer is Express middleware for parsing multipart/form-data, mainly to support file uploads. It adds text fields and uploaded files to the request object and can be configured for disk or custom storage. |
compression | Express’s compression middleware compresses eligible HTTP response bodies using deflate, gzip, or Brotli. Install the compression package and mount compression([options]) with app.use(). |
rateLimit | |
app.routes |
Pipe
| Name | What it does |
|---|---|
req.query | |
req.cookies | req.cookies is an object populated by cookie-parser with cookies sent by the request. It is empty when no cookies are present; signed cookies belong in req.signedCookies. |
req.headers | |
req.path | req.path is a string containing the path portion of an Express request URL. It excludes the query string, and mounted middleware sees the path without its mount point. |
req.method | |
req.url | req.url is the request URL exposed on Express's request object. It comes from Node's HTTP module and may be rewritten by mounted middleware during internal routing. |
req.baseUrl | req.baseUrl is the URL path where the current Express router was mounted. It reports the concrete path matched for the request, not the pattern used to mount the router. |
req.originalUrl | req.originalUrl is the original request URL, retained while Express may rewrite req.url for internal routing. It is available in middleware and routers and is represented as a string. |
req.hostname | req.hostname returns the request hostname without its port. With proxy trust enabled, Express derives it from X-Forwarded-Host instead of Host. |
req.ip | req.ip contains the request's remote IP address as a string. With proxy trust enabled, Express derives it from the left-most X-Forwarded-For entry. |
req.protocol | req.protocol gives the request’s protocol as http or https. With proxy trust enabled, Express can derive it from X-Forwarded-Proto. |
req.secure | |
req.xhr | req.xhr is a Boolean request property that indicates whether the X-Requested-With header is XMLHttpRequest. Use it to choose handling for requests identifying themselves as XMLHttpRequest requests. |
req.signedCookies | req.signedCookies is the request object containing signed cookies validated and unsigned by cookie-parser. It is an empty object when the request carries no signed cookies. |
req.fresh | req.fresh reports whether the client's cached response is still fresh. It is false for stale caches and for requests carrying Cache-Control: no-cache. |
req.subdomains | req.subdomains returns the request hostname’s subdomain labels as a string array. Express uses the configurable subdomain offset, defaulting to 2, to determine where those labels begin. |
app.locals | |
res.locals | res.locals stores values that templates rendered with res.render can use. Its values exist only for the current request-response cycle, making it suitable for request-specific data. |
req.app | req.app is a reference to the Express application instance that is using the middleware. Reusable middleware can use it to access application settings and other app-level APIs. |
res.app | res.app references the Express application instance handling the current response. It provides access to application configuration and is the same object exposed as req.app. |
res.headersSent | res.headersSent is a Boolean that tells you whether the response’s HTTP headers have already been sent. Check it before attempting response handling that could write headers again. |
res.statusCode | res.statusCode sets the HTTP status code on an Express response. Assign it before sending or ending the response, or use chainable res.status(code). |
res.statusMessage | res.statusMessage is the HTTP reason phrase associated with an Express response’s status code. Express’s error handler derives it from the final status code, while application code may assign a custom phrase. |
res.charset | |
req.acceptsCharsets | Checks candidate character sets against the request’s Accept-Charset header. It returns the first accepted candidate or false when none is acceptable. |
req.acceptsEncodings | Negotiates a response content encoding using the request’s Accept-Encoding header. It returns the first accepted candidate or false when none is accepted. |
req.acceptsLanguages | req.acceptsLanguages() negotiates languages against the request’s Accept-Language header. It returns the best supplied match, false when no candidate is accepted, or all accepted languages when called without arguments. |
req.range | Parses the HTTP Range header for a resource of a specified size. It returns requested ranges or a negative error code, with an option to merge overlapping and adjacent ranges. |
Search across every package and filter by type in your dashboard.
Start learning