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', (req, res) => {
res.send(`user ${req.params.id}`);
});import { type Request, type Response } from 'express';
app.get('/user/:id', (req: Request, res: Response) => {
res.send(`user ${req.params.id}`);
});But you could just as well have:
app.get('/user/:id', (request, response) => {
response.send(`user ${request.params.id}`);
});import { type Request, type Response } from 'express';
app.get('/user/:id', (request: Request, response: 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
Type: Application
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.
app.get('/', (req, res) => {
console.dir(res.app.get('view engine'));
console.dir(res.app === req.app);
// => true
res.send('OK');
});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => {
console.dir(res.app.get('view engine'));
console.dir(res.app === req.app);
// => true
res.send('OK');
});res.headersSent
Type: Boolean
Boolean property that indicates if the app sent HTTP headers for the response.
app.get('/', (req, res) => {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => {
console.log(res.headersSent); // false
res.send('OK');
console.log(res.headersSent); // true
});res.locals
Type: Object
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((req, res, next) => {
// Make `user` and `authenticated` available in templates
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});import { type Request, type Response, type NextFunction } from 'express';
app.use((req: Request, res: Response, next: NextFunction) => {
// Make `user` and `authenticated` available in templates
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});res.req
Type: Request
This property holds a reference to the request object that relates to this response object.
app.get('/', (req, res) => {
console.dir(res.req === req);
// => true
res.send('OK');
});import { type Request, type Response } from 'express';
app.get('/', (req: Request, res: Response) => {
console.dir(res.req === req);
// => true
res.send('OK');
});Methods
res.append()
Parameters
field·StringThe name of the HTTP response header to append to.
value·String | String[]· optionalThe value(s) to append to the header.
Returns: Response
Appends the specified 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.
INFO
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()
Parameters
filename·String· optionalThe file name used to set the
Content-Disposition"filename=" parameter and theContent-Type(from its extension).
Returns: Response
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()
Parameters
name·StringThe name of the cookie to clear.
options·Object· optionalCookie options, which should match those given to res.cookie() (excluding
expiresandmaxAge).
Returns: Response
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().
DANGER
The expires and maxAge options are being ignored completely.
DANGER
Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie()
res.cookie('name', 'tobi', { path: '/admin' });
res.clearCookie('name', { path: '/admin' });res.cookie()
Parameters
name·StringThe name of the cookie.
value·String | ObjectThe cookie value; an object is serialized as JSON.
options·Object· optionalOptions for the
Set-Cookieheader.domain·StringDomain name for the cookie. Defaults to the domain name of the app.
encode·FunctionA synchronous function used for cookie value encoding. Defaults to
encodeURIComponent.expires·DateExpiry date of the cookie in GMT. If not specified or set to
0, creates a session cookie.httpOnly·BooleanFlags the cookie to be accessible only by the web server.
maxAge·NumberConvenient option for setting the expiry time relative to the current time in milliseconds.
path·String· default:"/"Path for the cookie. Defaults to "/".
partitioned·BooleanIndicates that the cookie should be stored using partitioned storage. See CHIPS for more details.
priority·StringValue of the "Priority" Set-Cookie attribute.
secure·BooleanMarks the cookie to be used with HTTPS only.
signed·BooleanIndicates if the cookie should be signed.
sameSite·Boolean | StringValue of the "SameSite" Set-Cookie attribute.
Returns: Response
Sets cookie name to value. The value parameter may be a string or object converted to JSON.
DANGER
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('remember_me', '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 encoding
res.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 encoding
res.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('remember_me', '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.signedCookies object.
res.download()
Parameters
path·StringThe path to the file to transfer. If relative, it is resolved against the current working directory or the
rootoption.filename·String· optionalThe file name for the
Content-Disposition"filename=" parameter; overrides the name derived frompath.options·Object· optionalOptions forwarded to res.sendFile().
maxAge·Number | String· default:0Sets the max-age property of the
Cache-Controlheader in milliseconds, or a string in ms format.root·StringRoot directory for relative file names.
lastModified·Boolean· default:trueSets the
Last-Modifiedheader to the last modified date of the file on the OS. Setfalseto disable it.headers·ObjectObject containing HTTP headers to serve with the file.
dotfiles·String· default:"ignore"Option for serving dotfiles. Possible values are
"allow","deny", and"ignore".acceptRanges·Boolean· default:trueEnable or disable accepting ranged requests.
cacheControl·Boolean· default:trueEnable or disable setting the
Cache-Controlresponse header.immutable·Boolean· default:falseEnable or disable the
immutabledirective in theCache-Controlresponse header. If enabled, themaxAgeoption should also be specified to enable caching.
fn·Function· optionalCallback
fn(err)invoked when the transfer completes or an error occurs.
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 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', (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()
Parameters
data·String | Buffer· optionalData to write before ending the response.
encoding·String· optionalThe encoding for
datawhen it is a string.callback·Function· optionalCalled once the response has finished.
Returns: Response
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()
Parameters
object·ObjectAn object whose keys are MIME types (or extension names) mapped to handler functions, optionally with a
defaulthandler.
Returns: Response
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'() {
res.send('hey');
},
'text/html'() {
res.send('<p>hey</p>');
},
'application/json'() {
res.send({ message: 'hey' });
},
default() {
// 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() {
res.send('hey');
},
html() {
res.send('<p>hey</p>');
},
json() {
res.send({ message: 'hey' });
},
});res.get()
Parameters
field·StringThe name of the response header to read (case-insensitive).
Returns: String
Returns the HTTP response header specified by field. The match is case-insensitive.
res.get('Content-Type');
// => 'text/plain'res.json()
Parameters
body·any· optionalThe value to send as JSON. Can be any JSON type: object, array, string, Boolean, number, or null.
Returns: Response
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()
Parameters
body·any· optionalThe value to send as a JSONP response. Can be any JSON type.
Returns: Response
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=foo
res.jsonp({ user: 'tobi' });
// => foo({ "user": "tobi" })
app.set('jsonp callback name', 'cb');
// ?cb=foo
res.status(500).jsonp({ error: 'message' });
// => foo({ "error": "message" })res.links()
Parameters
links·Record<String, String | String[]>An object whose properties (such as
nextandlast) populate theLinkresponse header. Each value can be a single URL string, or an array of URL strings to emit multiple links for the same relation.
Returns: Response
Joins the links provided as properties of the parameter to populate the response's Link HTTP header field. Each call adds to an existing Link header. A relation whose value is an empty array adds nothing, and a call with nothing to add (such as res.links({})) leaves the header as it is.
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()
Parameters
path·StringThe URL to set in the
Locationheader.
Returns: Response
Sets the response Location HTTP header to the specified path parameter.
res.location('/foo/bar');
res.location('http://example.com');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()
Parameters
status·Number· optionalThe HTTP status code to use. Defaults to
302(Found).path·StringThe URL to redirect to.
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('https://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('..');See also Security best practices: Prevent open redirect vulnerabilities.
res.render()
Parameters
view·StringThe file path of the view to render (absolute or relative to the
viewssetting).locals·Object· optionalAn object whose properties define local variables for the view.
callback·Function· optionalCalled as
callback(err, html). When provided, the rendered HTML is not sent automatically.
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. With the fork's view engines setting, a name without a known extension tries the view engine extension, then each listed one, and renders the first file found; see Several template engines. 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.
DANGER
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 client
res.render('index');
// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', (err, html) => {
res.send(html);
});
// pass a local variable to the view
res.render('user', { name: 'Tobi' }, (err, html) => {
// ...
});res.send()
Parameters
body·String | Buffer | Object | Array | Boolean· optionalThe response body. Strings are sent as HTML; objects and arrays as JSON; Buffers as binary.
Returns: Response
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 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()
Parameters
path·StringThe path to the file to transfer. Must be absolute unless the
rootoption is set.options·Object· optionalOptions for serving the file.
maxAge·Number | String· default:0Sets the max-age property of the
Cache-Controlheader in milliseconds, or a string in ms format.root·StringRoot directory for relative file names.
lastModified·Boolean· default:trueSets the
Last-Modifiedheader to the last modified date of the file on the OS. Setfalseto disable it.headers·ObjectObject containing HTTP headers to serve with the file.
dotfiles·String· default:"ignore"Option for serving dotfiles. Possible values are
"allow","deny", and"ignore".acceptRanges·Boolean· default:trueEnable or disable accepting ranged requests.
cacheControl·Boolean· default:trueEnable or disable setting the
Cache-Controlresponse header.immutable·Boolean· default:falseEnable or disable the
immutabledirective in theCache-Controlresponse header. If enabled, themaxAgeoption should also be specified to enable caching.
fn·Function· optionalCallback
fn(err)invoked when the transfer completes or an error occurs.
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.
A file whose size is reported as 0 but that has content, such as a Linux /proc or /sys file, is streamed to its end with no Content-Length, and a Range request gets the whole file. A really empty file is sent with Content-Length: 0. (Express 5.3.0 sent such files empty.)
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', (req, res, next) => {
const options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true,
},
};
const fileName = req.params.name;
res.sendFile(fileName, options, (err) => {
if (err) {
next(err);
} else {
console.log('Sent:', fileName);
}
});
});import { type Request, type Response, type NextFunction } from 'express';
app.get('/file/:name', (req: Request, res: Response, next: NextFunction) => {
const options = {
root: path.join(__dirname, 'public'),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true,
},
};
const fileName = req.params.name;
res.sendFile(fileName, options, (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', (req, res) => {
const uid = req.params.uid;
const file = req.params.file;
req.user.mayViewFilesFrom(uid, (yes) => {
if (yes) {
res.sendFile(`/uploads/${uid}/${file}`);
} else {
res.status(403).send("Sorry! You can't see that.");
}
});
});import { type Request, type Response } from 'express';
app.get('/user/:uid/photos/:file', (req: Request, res: Response) => {
const uid = req.params.uid;
const file = req.params.file;
req.user.mayViewFilesFrom(uid, (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()
Parameters
statusCode·NumberThe HTTP status code to set; its registered status message becomes the response body.
Returns: Response
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);DANGER
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()
Parameters
field·String | ObjectThe header name, or an object of header name/value pairs to set multiple headers at once.
value·String | String[]· optionalThe header value (when
fieldis a string).
Returns: Response
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()
Parameters
code·NumberThe HTTP status code for the response.
Returns: Response
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()
Parameters
type·StringThe MIME type, or a file extension that is looked up to a MIME type. If it contains
/, it is used as-is.
Returns: Response
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 using the contentType() method of the mime-types package.
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()
Parameters
field·StringThe header field name to add to the
Varyresponse header.
Returns: Response
Adds the field to the Vary response header, if it is not there already.
res.vary('User-Agent').render('docs');