Set Location without redirecting
Expose the destination of a response while controlling the status and body separately.
Express.js · Module
res.location(path) sets the HTTP Location response header to a specified URL or path. It returns the response object and does not validate the resulting URL.
Call res.location(path) to set the HTTP Location response header. Express encodes the supplied value when needed and returns the response object, so it can be chained with other response methods; it does not validate the resulting URL.
res.location(path)| Name | Type | Description |
|---|---|---|
path | String | The URL to set in the Location header. |
Response
import express from 'express';
const app = express();
app.get('/old', (req, res) => {
res.location('/new');
res.status(302).send('Use /new');
});
app.listen(3000);Run the server, then request /old and inspect the Location response header.
Expose the destination of a response while controlling the status and body separately.
Provide a relative application route as the response destination.
Provide an absolute destination URL in an HTTP response.
res.location(path) sets the response's Location header to the supplied path and returns the Response object. It does not itself perform a redirect; a separate response action, such as a status and send, is needed.
Follow-up: What security concern should be considered? The method passes the encoded URL onward without validation, so untrusted redirect targets must be constrained or validated.
The path argument is a string identifying the URL to place in the Location header. It can be a path such as /foo/bar or an absolute URL such as http://example.com.
Follow-up: What happens if the path is not already encoded? Express encodes it before placing it in the header.
The special back value refers to the request's Referer header, or / when that header is absent. In Express 4.21.0 it was deprecated, so newer code should use req.get('Referrer') || /.
Follow-up: Why is the fallback useful? It ensures the replacement argument remains defined when the client did not send a referrer.
res.redirect()res.set()req.get()