Response
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
In this documentation and by convention,
the object is always referred to as res (and the HTTP request is req) but its actual name is determined
by the parameters to the callback function in which you’re working.
For example:
app.get('/user/:id', function (req, res) { res.send('user ' + req.params.id);});But you could just as well have:
app.get('/user/:id', function (request, response) { response.send('user ' + request.params.id);});The res object is an enhanced version of Node’s own response object
and supports all built-in fields and methods.
Properties
res.app
This property holds a reference to the instance of the Express application that is using the middleware.
res.app is identical to the req.app property in the request object.
res.headersSent
Boolean property that indicates if the app sent HTTP headers for the response.
app.get('/', function (req, res) { console.dir(res.headersSent); // false res.send('OK'); console.dir(res.headersSent); // true});res.locals
Use this property to set variables accessible in templates rendered with res.render.
The variables set on res.locals are available within a single request-response cycle, and will not
be shared between requests.
Warning
The locals object is used by view engines to render a response. The object keys may be
particularly sensitive and should not contain user-controlled input, as it may affect the
operation of the view engine or provide a path to cross-site scripting. Consult the documentation
for the used view engine for additional considerations.
In order to keep local variables for use in template rendering between requests, use app.locals instead.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.
app.use(function (req, res, next) { // Make `user` and `authenticated` available in templates res.locals.user = req.user; res.locals.authenticated = !req.user.anonymous; next();});res.req
This property holds a reference to the request object that relates to this response object.
Methods
res.append(field [, value])
Note
res.append() is supported by Express v4.11.0+ value to the HTTP response header field. If the header is not already set,
it creates the header with the specified value. The value parameter can be a string or an array.
Note
calling res.set() after res.append() will reset the previously-set header value.
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');res.append('Warning', '199 Miscellaneous warning');res.attachment([filename])
Sets the HTTP response Content-Disposition header field to “attachment”. If a filename is given,
then it sets the Content-Type based on the extension name via res.type(),
and sets the Content-Disposition “filename=” parameter.
res.attachment();// Content-Disposition: attachment
res.attachment('path/to/logo.png');// Content-Disposition: attachment; filename="logo.png"// Content-Type: image/pngres.clearCookie(name [, options])
Clears the cookie with the specified name by sending a Set-Cookie header that sets its expiration date in the past.
This instructs the client that the cookie has expired and is no longer valid. For more information
about available options, see res.cookie().
Warning
If the maxAge or expires options are set, the cookie may not be cleared depending on the time
values provided, as Express does not ignore these options. It is therefore recommended to omit
these options when calling this method. Passing these two options has been deprecated since
Express v4.20.0.
Caution
Web browsers and other compliant clients will only clear the cookie if the given options is
identical to those given to res.cookie(), excluding expires and maxAge.
res.cookie('name', 'tobi', { path: '/admin' });res.clearCookie('name', { path: '/admin' });res.cookie(name, value [, options])
Sets cookie name to value. The value parameter may be a string or object converted to JSON.
The options parameter is an object that can have the following properties.
| Property | Type | Description |
|---|---|---|
domain | String | Domain name for the cookie. Defaults to the domain name of the app. |
encode | Function | A synchronous function used for cookie value encoding. Defaults to encodeURIComponent. |
expires | Date | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. |
httpOnly | Boolean | Flags the cookie to be accessible only by the web server. |
maxAge | Number | Convenient option for setting the expiry time relative to the current time in milliseconds. |
path | String | Path for the cookie. Defaults to ”/”. |
partitioned | Boolean | Indicates that the cookie should be stored using partitioned storage. See Cookies Having Independent Partitioned State (CHIPS) for more details. |
priority | String | Value of the “Priority” Set-Cookie attribute. |
secure | Boolean | Marks the cookie to be used with HTTPS only. |
signed | Boolean | Indicates if the cookie should be signed. |
sameSite | Boolean or String | Value of the “SameSite” Set-Cookie attribute. More information at https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1. |
Caution
All res.cookie() does is set the HTTP Set-Cookie header with the options provided. Any option
not specified defaults to the value stated in RFC 6265.
For example:
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });You can set multiple cookies in a single response by calling res.cookie multiple times, for example:
res .status(201) .cookie('access_token', 'Bearer ' + token, { expires: new Date(Date.now() + 8 * 3600000), // cookie will be removed after 8 hours }) .cookie('test', 'test') .redirect(301, '/admin');The encode option allows you to choose the function used for cookie value encoding.
Does not support asynchronous functions.
Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.
// Default encodingres.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' });// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'
// Custom encodingres.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String,});// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'The maxAge option is a convenience option for setting “expires” relative to the current time in milliseconds.
The following is equivalent to the second example above.
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true });You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.
res.cookie('cart', { items: [1, 2, 3] });res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 });When using cookie-parser middleware, this method also
supports signed cookies. Simply include the signed option set to true.
Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.
res.cookie('name', 'tobi', { signed: true });Later you may access this value through the req.signedCookie object.
res.download(path [, filename] [, options] [, fn])
Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download.
By default, the Content-Disposition header “filename=” parameter is derived from the path argument, but can be overridden with the filename parameter.
If path is relative, then it will be based on the current working directory of the process or
the root option, if provided.
Warning
This API provides access to data on the running file system. Ensure that either (a) the way in
which the path argument was constructed is secure if it contains user input or (b) set the root
option to the absolute path of a directory to contain access within.
When the root option is provided, Express will validate that the relative path provided as
path will resolve within the given root option.
The following table provides details on the options parameter.
Note
options argument is supported by Express v4.16.0 onwards. | Property | Description | Default | Availability |
|---|---|---|---|
maxAge | Sets the max-age property of the Cache-Control header in milliseconds or a string in ms format | 0 | 4.16+ |
root | Root directory for relative filenames. | 4.18+ | |
lastModified | Sets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it. | Enabled | 4.16+ |
headers | Object containing HTTP headers to serve with the file. The header Content-Disposition will be overridden by the filename argument. | 4.16+ | |
dotfiles | Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. | “ignore” | 4.16+ |
acceptRanges | Enable or disable accepting ranged requests. | true | 4.16+ |
cacheControl | Enable or disable setting Cache-Control response header. | true | 4.16+ |
immutable | Enable 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. | false | 4.16+ |
The method invokes the callback function fn(err) when the transfer is complete
or when an error occurs. If the callback function is specified and an error occurs,
the callback function must explicitly handle the response process either by
ending the request-response cycle, or by passing control to the next route.
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('/report-12345.pdf', 'report.pdf', function (err) { if (err) { // Handle error, but keep in mind the response may be partially-sent // so check res.headersSent } else { // decrement a download credit, etc. }});res.end([data[, encoding]][, callback])
Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
res.end();res.status(404).end();res.format(object)
Performs content-negotiation on the Accept HTTP header on the request object, when present.
It uses req.accepts() to select a handler for the request, based on the acceptable
types ordered by their quality values. If the header is not specified, the first callback is invoked.
When no match is found, the server responds with 406 “Not Acceptable”, or invokes the default callback.
The Content-Type response header is set when a callback is selected. However, you may alter
this within the callback using methods such as res.set() or res.type().
The following example would respond with { "message": "hey" } when the Accept header field is set
to “application/json” or ”*/json” (however if it is ”*/*”, then the response will be “hey”).
res.format({ 'text/plain': function () { res.send('hey'); },
'text/html': function () { res.send('<p>hey</p>'); },
'application/json': function () { res.send({ message: 'hey' }); },
default: function () { // log the request and respond with 406 res.status(406).send('Not Acceptable'); },});In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:
res.format({ text: function () { res.send('hey'); },
html: function () { res.send('<p>hey</p>'); },
json: function () { res.send({ message: 'hey' }); },});res.get(field)
Returns the HTTP response header specified by field.
The match is case-insensitive.
res.get('Content-Type');// => "text/plain"res.json([body])
Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().
The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.
res.json(null);res.json({ user: 'tobi' });res.status(500).json({ error: 'message' });res.jsonp([body])
Sends a JSON response with JSONP support. This method is identical to res.json(),
except that it opts-in to JSONP callback support.
res.jsonp(null);// => callback(null)
res.jsonp({ user: 'tobi' });// => callback({ "user": "tobi" })
res.status(500).jsonp({ error: 'message' });// => callback({ "error": "message" })By default, the JSONP callback name is simply callback. Override this with the
jsonp callback name setting.
The following are some examples of JSONP responses using the same code:
// ?callback=foores.jsonp({ user: 'tobi' });// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb');
// ?cb=foores.status(500).jsonp({ error: 'message' });// => foo({ "error": "message" })res.links(links)
Joins the links provided as properties of the parameter to populate the response’s
Link HTTP header field.
For example, the following call:
res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5',});Yields the following results:
Link: <http://api.example.com/users?page=2>; rel="next", <http://api.example.com/users?page=5>; rel="last"res.location(path)
Sets the response Location HTTP header to the specified path parameter.
res.location('/foo/bar');res.location('http://example.com');res.location('back');Note
'back' was deprecated in 4.21.0, use req.get('Referrer') || '/' as an argument instead.
A path value of “back” has a special meaning, it refers to the URL specified in the Referer header of the request. If the Referer header was not specified, it refers to ”/”.
See also Security best practices: Prevent open redirect vulnerabilities.
Warning
After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location header,
without any validation.
Browsers take the responsibility of deriving the intended URL from the current URL
or the referring URL, and the URL specified in the Location header; and redirect the user accordingly.
res.redirect([status,] path)
Redirects to the URL derived from the specified path, with specified status, a positive integer
that corresponds to an HTTP status code .
If not specified, status defaults to “302 “Found”.
res.redirect('/foo/bar');res.redirect('http://example.com');res.redirect(301, 'http://example.com');res.redirect('../login');Redirects can be a fully-qualified URL for redirecting to a different site:
res.redirect('http://google.com');Redirects can be relative to the root of the host name. For example, if the
application is on http://example.com/admin/post/new, the following
would redirect to the URL http://example.com/admin:
res.redirect('/admin');Redirects can be relative to the current URL. For example,
from http://example.com/blog/admin/ (notice the trailing slash), the following
would redirect to the URL http://example.com/blog/admin/post/new.
res.redirect('post/new');Redirecting to post/new from http://example.com/blog/admin (no trailing slash),
will redirect to http://example.com/blog/post/new.
If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.
Path-relative redirects are also possible. If you were on
http://example.com/admin/post/new, the following would redirect to
http://example.com/admin/post:
res.redirect('..');A back redirection redirects the request back to the referer,
defaulting to / when the referer is missing.
res.redirect('back');Note
back redirect was deprecated in 4.21.0, use req.get('Referrer') || '/' as an argument instead.
See also Security best practices: Prevent open redirect vulnerabilities.
res.render(view [, locals] [, callback])
Renders a view and sends the rendered HTML string to the client.
Optional parameters:
locals, an object whose properties define local variables for the view.callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokesnext(err)internally.
The view argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting. If the path does not contain a file extension, then the view engine setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via require()) and render it using the loaded module’s __express function.
For more information, see Using template engines with Express.
Warning
The view argument performs file system operations like reading a file from disk and evaluating
Node.js modules, and as so for security reasons should not contain input from the end-user.
Warning
The locals object is used by view engines to render a response. The object keys may be
particularly sensitive and should not contain user-controlled input, as it may affect the
operation of the view engine or provide a path to cross-site scripting. Consult the documentation
for the used view engine for additional considerations.
Caution
The local variable cache enables view caching. Set it to true, to cache the view during
development; view caching is enabled in production by default.
// send the rendered view to the clientres.render('index');
// if a callback is specified, the rendered HTML string has to be sent explicitlyres.render('index', function (err, html) { res.send(html);});
// pass a local variable to the viewres.render('user', { name: 'Tobi' }, function (err, html) { // ...});res.send([body])
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.
For example:
res.send(Buffer.from('whoop'));res.send({ some: 'json' });res.send('<p>some html</p>');res.status(404).send('Sorry, we cannot find that!');res.status(500).send({ error: 'something blew up' });This method performs many useful tasks for simple non-streaming responses:
For example, it automatically assigns the Content-Length HTTP response header field
(unless previously defined) and provides automatic HEAD and HTTP cache freshness support.
When the parameter is a Buffer object, the method sets the Content-Type
response header field to “application/octet-stream”, unless previously defined as shown below:
res.set('Content-Type', 'text/html');res.send(Buffer.from('<p>some html</p>'));When the parameter is a String, the method sets the Content-Type to “text/html”:
res.send('<p>some html</p>');When the parameter is an Array or Object, Express responds with the JSON representation:
res.send({ user: 'tobi' });res.send([1, 2, 3]);res.sendFile(path [, options] [, fn])
Note
res.sendFile() is supported by Express v4.8.0 onwards. Transfers the file at the given path. Sets the Content-Type response HTTP header field
based on the filename’s extension. Unless the root option is set in
the options object, path must be an absolute path to the file.
Warning
This API provides access to data on the running file system. Ensure that either (a) the way in
which the path argument was constructed into an absolute path is secure if it contains user
input or (b) set the root option to the absolute path of a directory to contain access within.
When the root option is provided, the path argument is allowed to be a relative path,
including containing ... Express will validate that the relative path provided as path will
resolve within the given root option.
The following table provides details on the options parameter.
| Property | Description | Default | Availability |
|---|---|---|---|
maxAge | Sets the max-age property of the Cache-Control header in milliseconds or a string in ms format | 0 | |
root | Root directory for relative filenames. | ||
lastModified | Sets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it. | Enabled | 4.9.0+ |
headers | Object containing HTTP headers to serve with the file. | ||
dotfiles | Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. | “ignore” | |
acceptRanges | Enable or disable accepting ranged requests. | true | 4.14+ |
cacheControl | Enable or disable setting Cache-Control response header. | true | 4.14+ |
immutable | Enable 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. | false | 4.16+ |
The method invokes the callback function fn(err) when the transfer is complete
or when an error occurs. If the callback function is specified and an error occurs,
the callback function must explicitly handle the response process either by
ending the request-response cycle, or by passing control to the next route.
Here is an example of using res.sendFile with all its arguments.
app.get('/file/:name', function (req, res, next) { var options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', headers: { 'x-timestamp': Date.now(), 'x-sent': true, }, };
var fileName = req.params.name; res.sendFile(fileName, options, function (err) { if (err) { next(err); } else { console.log('Sent:', fileName); } });});The following example illustrates using
res.sendFile to provide fine-grained support for serving files:
app.get('/user/:uid/photos/:file', function (req, res) { var uid = req.params.uid; var file = req.params.file;
req.user.mayViewFilesFrom(uid, function (yes) { if (yes) { res.sendFile('/uploads/' + uid + '/' + file); } else { res.status(403).send("Sorry! You can't see that."); } });});For more information, or if you have issues or concerns, see send.
res.sendStatus(statusCode)
Sets the response HTTP status code to statusCode and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.
res.sendStatus(404);Caution
Some versions of Node.js will throw when res.statusCode is set to an invalid HTTP status code
(outside of the range 100 to 599). Consult the HTTP server documentation for the Node.js
version being used.
res.set(field [, value])
Sets the response’s HTTP header field to value.
To set multiple fields at once, pass an object as the parameter.
res.set('Content-Type', 'text/plain');
res.set({ 'Content-Type': 'text/plain', 'Content-Length': '123', ETag: '12345',});Aliased as res.header(field [, value]).
res.status(code)
Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.
res.status(403).end();res.status(400).send('Bad Request');res.status(404).sendFile('/absolute/path/to/404.png');res.type(type)
Sets the Content-Type HTTP header to the MIME type as determined by the specified type. If type contains the ”/” character, then it sets the Content-Type to the exact value of type, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the express.static.mime.lookup() method.
res.type('.html');// => 'text/html'res.type('html');// => 'text/html'res.type('json');// => 'application/json'res.type('application/json');// => 'application/json'res.type('png');// => 'image/png'Aliased as res.contentType(type).
res.vary(field)
Adds the field to the Vary response header, if it is not there already.
res.vary('User-Agent').render('docs');