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
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
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
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
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()
Arguments
fieldThe name of the HTTP response header to append to.
valueThe value(s) to append to the header.
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.
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()
Arguments
filenameThe file name used to set the Content-Disposition “filename=” parameter and the
Content-Type (from its extension).
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()
Arguments
nameThe name of the cookie to clear.
optionsCookie options, which should match those given to res.cookie() (excluding
expires and maxAge).
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().
Caution
expires and maxAge options are being ignored completely.Caution
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()
Arguments
nameThe name of the cookie.
valueThe cookie value; an object is serialized as JSON.
optionsOptions for the Set-Cookie header.
domainDomain name for the cookie. Defaults to the domain name of the app.
encodeA synchronous function used for cookie value encoding. Defaults to encodeURIComponent.
expiresExpiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.
httpOnlyFlags the cookie to be accessible only by the web server.
maxAgeConvenient option for setting the expiry time relative to the current time in milliseconds.
pathPath for the cookie. Defaults to ”/”.
partitionedIndicates that the cookie should be stored using partitioned storage. See CHIPS for more details.
priorityValue of the “Priority” Set-Cookie attribute.
secureMarks the cookie to be used with HTTPS only.
signedIndicates if the cookie should be signed.
sameSiteValue of the “SameSite” Set-Cookie attribute.
Sets cookie name to value. The value parameter may be a string or object converted to JSON.
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('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