Express Object

Creates an Express application. The express() function is a top-level function exported by the express module.

const express = require('express');
const app = express();

Methods

The Express object has the following methods that can be used to create middleware functions, routers and have some built-in middleware:

express.json([options])

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or undefined if there was no body to parse, the Content-Type was not matched, or an error occurred.

Warning

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

The following table describes the properties of the optional options object.

PropertyDescriptionTypeDefault
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Booleantrue
limitControls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed"100kb"
reviverThe reviver option is passed directly to JSON.parse as the second argument. You can find more information on this argument in the MDN documentation about JSON.parse.Functionnull
strictEnables or disables only accepting arrays and objects; when disabled will accept anything JSON.parse accepts.Booleantrue
typeThis is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime type with a wildcard (like */* or */json). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.Mixed"application/json"
verifyThis option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.Functionundefined

express.raw([options])

This is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser.

Returns middleware that parses all bodies as a Buffer and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body Buffer containing the parsed data is populated on the request object after the middleware (i.e. req.body), or undefined if there was no body to parse, the Content-Type was not matched, or an error occurred.

Warning

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.toString() may fail in multiple ways, for example stacking multiple parsers req.body may be from a different parser. Testing that req.body is a Buffer before calling buffer methods is recommended.

The following table describes the properties of the optional options object.

PropertyDescriptionTypeDefault
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Booleantrue
limitControls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed"100kb"
typeThis is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like */* or application/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.Mixed"application/octet-stream"
verifyThis option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.Functionundefined

express.Router([options])

Creates a new router object.

const router = express.Router([options]);

The optional options parameter specifies the behavior of the router.

PropertyDescriptionDefaultAvailability
caseSensitiveEnable case sensitivity.Disabled by default, treating “/Foo” and “/foo” as the same.
mergeParamsPreserve the req.params values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.false4.5.0+
strictEnable strict routing.Disabled by default, “/foo” and “/foo/” are treated the same by the router. 

You can add middleware and HTTP method routes (such as get, put, post, and so on) to router just like an application.

For more information, see Router.

express.static(root, [options])

This is a built-in middleware function in Express. It serves static files and is based on serve-static.

Note

NOTE: For best results, use a reverse proxy cache to improve performance of serving static assets.

The root argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, it instead calls next() to move on to the next middleware, allowing for stacking and fall-backs.

The following table describes the properties of the options object. See also the example below.

PropertyDescriptionTypeDefault
dotfilesDetermines how dotfiles (files or directories that begin with a dot ”.”) are treated.

See dotfiles below.
String”ignore”
etagEnable or disable etag generation

NOTE: express.static always sends weak ETags.
Booleantrue
extensionsSets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: ['html', 'htm'].Mixedfalse
fallthroughLet client errors fall-through as unhandled requests, otherwise forward a client error.

See fallthrough below.
Booleantrue
immutableEnable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.Booleanfalse
indexSends the specified directory index file. Set to false to disable directory indexing.Mixed”index.html”
lastModifiedSet the Last-Modified header to the last modified date of the file on the OS.Booleantrue
maxAgeSet the max-age property of the Cache-Control header in milliseconds or a string in ms format.Number0
redirectRedirect to trailing ”/” when the pathname is a directory.Booleantrue
setHeadersFunction for setting HTTP headers to serve with the file.

See setHeaders below.
Function
acceptRangesEnable or disable accepting ranged requests. Disabling this will not send the Accept-Ranges header and will ignore the contents of the Range request header.Booleantrue
cacheControlEnable or disable setting the Cache-Control response header. Disabling this will ignore the immutable and maxAge options.Booleantrue

For more information, see Serving static files in Express. and Using middleware - Built-in middleware.

dotfiles

Possible values for this option are:

  • “allow” - No special treatment for dotfiles.
  • “deny” - Deny a request for a dotfile, respond with 403, then call next().
  • “ignore” - Act as if the dotfile does not exist, respond with 404, then call next().

fallthrough

When this option is true, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call next() to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke next(err).

Set this option to true so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

Use false if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

setHeaders

For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.

The signature of the function is:

fn(res, path, stat);

Arguments:

  • res, the response object.
  • path, the file path that is being sent.
  • stat, the stat object of the file that is being sent.

Example of express.static

Here is an example of using the express.static middleware function with an elaborate options object:

const options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders(res, path, stat) {
res.set('x-timestamp', Date.now());
},
};
app.use(express.static('public', options));

express.text([options])

This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on body-parser.

Returns middleware that parses all bodies as a string and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body string containing the parsed data is populated on the request object after the middleware (i.e. req.body), or undefined if there was no body to parse, the Content-Type was not matched, or an error occurred.

Warning

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.trim() may fail in multiple ways, for example stacking multiple parsers req.body may be from a different parser. Testing that req.body is a string before calling string methods is recommended.

The following table describes the properties of the optional options object.

PropertyDescriptionTypeDefault
defaultCharsetSpecify the default character set for the text content if the charset is not specified in the Content-Type header of the request.String"utf-8"
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Booleantrue
limitControls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed"100kb"
typeThis is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type with a wildcard (like */* or text/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.Mixed"text/plain"
verifyThis option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.Functionundefined

express.urlencoded([options])

This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or undefined if there was no body to parse, the Content-Type was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

Warning

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

The following table describes the properties of the optional options object.

PropertyDescriptionTypeDefault
extendedThis option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.Booleanfalse
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.Booleantrue
limitControls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing.Mixed"100kb"
parameterLimitThis option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised.Number1000
typeThis is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), or a mime type with a wildcard (like */x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value.Mixed"application/x-www-form-urlencoded"
verifyThis option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. The parsing can be aborted by throwing an error.Functionundefined
depthConfigure the maximum depth of the qs library when extended is true. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to 32. It is recommended to keep this value as low as possible.Number32