Redirects
res.redirect() sends the browser to a different URL.
Syntax
res.redirect([status], path)The res.redirect() method tells the browser to go to another URL. By default it uses status 302 (temporary). Pass a status first for a permanent redirect (301).
Redirects are common after a form submission, so a refresh does not resubmit the data.
Example
app.get('/old', (req, res) => {
res.redirect('/new'); // 302 temporary
});
app.get('/moved', (req, res) => {
res.redirect(301, '/new'); // 301 permanent
});
app.post('/login', (req, res) => {
res.redirect('/dashboard');
});When to use it
- After a successful login POST, the server redirects the user to their dashboard with res.redirect('/dashboard').
- A legacy URL /old-blog is permanently redirected to /blog with a 301 status to update search engine indexes.
- An HTTP-to-HTTPS middleware calls res.redirect(301, 'https://' + req.hostname + req.url) for every non-secure request.
More examples
Basic redirect after POST
Redirects to /dashboard on successful login using the default 302 (Found) status.
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === 'secret') {
return res.redirect('/dashboard');
}
res.status(401).send('Bad credentials');
});Permanent 301 redirect
Passes 301 as the first argument to signal a permanent redirect, telling clients to update bookmarks.
// Moved permanently — browsers and search engines cache this
app.get('/old-path', (req, res) => {
res.redirect(301, '/new-path');
});Force HTTPS redirect middleware
Redirects all plain-HTTP requests to the HTTPS equivalent, checking the x-forwarded-proto header for proxy setups.
app.use((req, res, next) => {
if (req.secure || req.headers['x-forwarded-proto'] === 'https') {
return next();
}
res.redirect(301, `https://${req.hostname}${req.url}`);
});
Discussion