Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

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

NameWhat it does
Routerexpress.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

NameWhat it does
expressFunction
useapp.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().
getRegisters 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.
postapp.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.
staticexpress.static serves static assets from a root directory through Express middleware. An optional options object controls file lookup, caching, dotfiles, ETags, and response headers.
jsonexpress.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.
urlencodedFunction
nextExpress 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.jsonres.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.sendSends 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.statusres.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.redirectFunction
res.cookieres.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.Routerexpress.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.jsonCreates 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.urlencodedexpress.urlencoded() creates built-in middleware for parsing URL-encoded request bodies. Matching parsed data is made available through req.body.
express.staticexpress.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.textexpress.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.rawFunction
serveStaticserveStatic(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

NameWhat it does
RequestThe 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.
ResponseInterface
NextFunctionNextFunction 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.
ApplicationThe Express application object, conventionally called app, is created with express(). It provides the interface for defining routes, configuring middleware, and handling HTTP requests.
RequestHandlerInterface
ErrorRequestHandlerInterface
ExpressThe Express application object is created with express() and conventionally stored in app. It registers middleware and HTTP-method routes and can handle incoming requests.
HandlerInterface
RouterOptionsRouterOptions 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.
CookieOptionsCookieOptions 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

NameWhat it does
req.paramsreq.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.bodyreq.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 engineConst
viewsThe views application setting identifies the directory, or ordered directories, that Express uses to find view templates. It defaults to process.cwd() + '/views'.
trust proxytrust 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 routingConst
strict routingexpress.Router({ strict: true }) makes trailing slashes significant when matching routes. By default, /foo and /foo/ are treated as the same path.
x-powered-byx-powered-by is a Boolean Express application setting enabled by default. It controls whether responses include the X-Powered-By: Express header.
json spacesThe 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 parserThe 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

NameWhat it does
app.getRegisters 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.postapp.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.putDefines 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.deleteapp.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.patchModule
app.allModule
app.useapp.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.listenStarts 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.setAssigns a value to an Express application setting with app.set(name, value). Boolean settings can also be controlled through true or false.
app.engineRegisters a template-engine callback for a file extension. Use it for custom engines or to map an alternate extension to an engine.
app.paramModule
app.routeCreates 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.renderapp.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.enableEnables a named Boolean setting on an Express application. It returns the application instance and is equivalent to setting that Boolean property to true.
app.disableapp.disable(name) turns a documented Boolean Express application setting off by assigning it false. It returns the application instance for continued configuration.
app.pathapp.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.getRetrieves the value of an HTTP request header by name. Use it inside a route or middleware callback to inspect client-supplied request metadata.
req.acceptsreq.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.isreq.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.paramreq.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.jsonpres.jsonp() sends a JSON response with JSONP callback support. It accepts a JSON-compatible body; set status separately with res.status().jsonp(body).
res.sendStatusres.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.renderModule
res.endres.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.setSets 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.getReads 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.appendres.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.clearCookieClears 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.typeSets the response Content-Type from a MIME type or file extension. Values containing / are used literally; other values undergo extension-based MIME lookup.
res.formatModule
res.attachmentModule
res.downloadres.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.sendFileres.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.locationres.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.linksres.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.varyModule
res.writeModule
corscors 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.
helmetHelmet is Express middleware that sets security-related HTTP response headers. Install it separately and register helmet() with app.use().
morganMorgan is Node.js HTTP request-logger middleware for Express applications. Configure it with a predefined format, custom format string, or formatter function.
cookieParsercookieParser 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.
bodyParserModule
sessionModule
multerMulter 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.
compressionExpress’s compression middleware compresses eligible HTTP response bodies using deflate, gzip, or Brotli. Install the compression package and mount compression([options]) with app.use().
rateLimitModule
app.routesModule

Pipe

NameWhat it does
req.queryPipe
req.cookiesreq.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.headersPipe
req.pathreq.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.methodPipe
req.urlreq.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.baseUrlreq.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.originalUrlreq.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.hostnamereq.hostname returns the request hostname without its port. With proxy trust enabled, Express derives it from X-Forwarded-Host instead of Host.
req.ipreq.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.protocolreq.protocol gives the request’s protocol as http or https. With proxy trust enabled, Express can derive it from X-Forwarded-Proto.
req.securePipe
req.xhrreq.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.signedCookiesreq.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.freshreq.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.subdomainsreq.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.localsPipe
res.localsres.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.appreq.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.appres.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.headersSentres.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.statusCoderes.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.statusMessageres.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.charsetPipe
req.acceptsCharsetsChecks candidate character sets against the request’s Accept-Charset header. It returns the first accepted candidate or false when none is acceptable.
req.acceptsEncodingsNegotiates a response content encoding using the request’s Accept-Encoding header. It returns the first accepted candidate or false when none is accepted.
req.acceptsLanguagesreq.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.rangeParses 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