0
0
Expressframework~5 mins

res.redirect for redirections in Express

Choose your learning style9 modes available
Introduction

res.redirect helps send users to a different web page automatically. It makes your app move users from one URL to another easily.

After a user logs in, send them to their dashboard page.
When a page is moved, send visitors to the new page URL.
If a user tries to access a page they shouldn't, redirect them to the home page.
After a form is submitted, redirect to a thank you page.
To guide users from an old URL to a new one during website updates.
Syntax
Express
res.redirect([status,] path)

You can give just the path or add a status code like 301 or 302.

Status code 302 means temporary redirect, 301 means permanent redirect.

Examples
Redirects user to '/home' with default status 302 (temporary).
Express
res.redirect('/home')
Redirects user permanently to '/new-page' with status 301.
Express
res.redirect(301, '/new-page')
Redirects user to an external website URL.
Express
res.redirect('https://example.com')
Sample Program

This Express app sends users from '/old-page' to '/new-page' permanently using res.redirect with status 301.

Express
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

app.get('/old-page', (req, res) => {
  res.redirect(301, '/new-page');
});

app.get('/new-page', (req, res) => {
  res.send('This is the new page.');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always set the status code if you want to control if the redirect is permanent or temporary.

Redirects stop the current response and send the new location to the browser.

Use absolute URLs to redirect outside your site, relative paths for internal pages.

Summary

res.redirect sends users to a different URL automatically.

You can specify if the redirect is permanent (301) or temporary (302).

It is useful for moving pages, login flows, and guiding users.