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();import express from 'express';
const app = express();import express, { type Express } from 'express';
const app: Express = 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()
Arguments
optionsConfigures how the JSON body is parsed; it accepts the properties below.
defaultCharsetSpecify the default character set for the JSON content if the charset is not specified in
the Content-Type header of the request.
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
strictEnables or disables only accepting arrays and objects; when disabled will accept anything
JSON.parse accepts.
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.
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.
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.
const express = require('express');const app = express();
// parse requests with a Content-Type of application/jsonapp.use(express.json());
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});import express from 'express';
const app = express();
// parse requests with a Content-Type of application/jsonapp.use(express.json());
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});import express, { type Express, type Request, type Response } from 'express';
const app: Express = express();
// parse requests with a Content-Type of application/jsonapp.use(express.json());
app.post('/profile', (req: Request, res: Response) => { console.dir(req.body); res.json(req.body);});express.raw()
Arguments
optionsConfigures how the request body is parsed; it accepts the properties below.
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
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.
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.
const express = require('express');const app = express();
// parse requests with a Content-Type of application/octet-stream into a Bufferapp.use(express.raw());
app.post('/upload', (req, res) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`);});import express from 'express';
const app = express();
// parse requests with a Content-Type of application/octet-stream into a Bufferapp.use(express.raw());
app.post('/upload', (req, res) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`);});import express, { type Express, type Request, type Response } from 'express';
const app: Express = express();
// parse requests with a Content-Type of application/octet-stream into a Bufferapp.use(express.raw());
app.post('/upload', (req: Request, res: Response) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`);});express.Router()
Arguments
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.
strictEnable strict routing. Disabled by default, /foo and /foo/ are treated the same by the
router.
Creates a new router object.
const router = express.Router([options]);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()
Arguments
rootThe root directory from which to serve static assets.
optionsConfigures how files are served; it accepts the properties below. See also the example below.
dotfilesDetermines how dotfiles (files or directories that begin with a dot ”.”) are treated. See dotfiles below.
etagEnable or disable etag generation.
Note
express.static always sends weak ETags.
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'].
fallthroughLet client errors fall-through as unhandled requests, otherwise forward a client error. See fallthrough below.
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.
indexSends the specified directory index file. Set to false to disable directory indexing.
lastModifiedSet the Last-Modified header to the last modified date of the file on the OS.
maxAgeSet the max-age property of the Cache-Control header in milliseconds or a string in ms format.
redirectRedirect to trailing ”/” when the pathname is a directory.
setHeadersFunction for setting HTTP headers to serve with the file. See setHeaders below.
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.
cacheControlEnable or disable setting the Cache-Control response header. Disabling this will ignore
the immutable and maxAge options.
This is a built-in middleware function in Express. It serves static files and is based on serve-static.
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.
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 callnext(). - “ignore” - Act as if the dotfile does not exist, respond with
404, then callnext().
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, thestatobject 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 express = require('express');const app = express();
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));import express from 'express';
const app = express();
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));import express, { type Express } from 'express';
const app: Express = express();
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()
Arguments
optionsConfigures how the text body is parsed; it accepts the properties below.
defaultCharsetSpecify the default character set for the text content if the charset is not specified in
the Content-Type header of the request.
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
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.
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.
const express = require('express');const app = express();
// parse requests with a Content-Type of text/plain into a stringapp.use(express.text());
app.post('/', (req, res) => { console.dir(typeof req.body); // => 'string' res.send(req.body);});import express from 'express';
const app = express();
// parse requests with a Content-Type of text/plain into a stringapp.use(express.text());
app.post('/', (req, res) => { console.dir(typeof req.body); // => 'string' res.send(req.body);});import express, { type Express, type Request, type Response } from 'express';
const app: Express = express();
// parse requests with a Content-Type of text/plain into a stringapp.use(express.text());
app.post('/', (req: Request, res: Response) => { console.dir(typeof req.body); // => 'string' res.send(req.body);});express.urlencoded()
Arguments
optionsConfigures how the URL-encoded body is parsed; it accepts the properties below.
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.
inflateEnables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
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.
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.
defaultCharsetThe default charset to parse as, if not specified in content-type. Must be either utf-8
or iso-8859-1.
charsetSentinelWhether to let the value of the utf8 parameter take precedence as the charset selector.
It requires the form to contain a parameter named utf8 with a value of ✓.
interpretNumericEntitiesWhether to decode numeric entities such as ☺ when parsing an iso-8859-1 form.
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. It is recommended to keep this value as low as possible.
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.
const express = require('express');const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencodedapp.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});import express from 'express';
const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencodedapp.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});import express, { type Express, type Request, type Response } from 'express';
const app: Express = express();
// parse requests with a Content-Type of application/x-www-form-urlencodedapp.use(express.urlencoded({ extended: true }));
app.post('/profile', (req: Request, res: Response) => { console.dir(req.body); res.json(req.body);});