by Sai gowtham

How to redirect from one route to another in Express

In this tutorial, we will learn about how to redirect a user from one route to another route in the express app.

In express, we can use the res.redirect() method to redirect a user to the different route.

The res.redirect() method takes the path as an argument and redirects the user to that specified path.

In this example, we are redirecting a user from /lab to /dashboard.

app.get('/lab',(req,res)=>{
   res.redirect('/dashboard');
})

By default, express creates a 302 redirect.

If you want to create a permanent redirect, you need to specify a status code 301 like this.

app.get('/lab',(req,res)=>{
   res.redirect(301, '/dashboard');
})

If you are redirecting a user to a different site, you need to pass a full url of the site like this.

app.get('/lab',(req,res)=>{
   res.redirect(301, 'https://google.com/');
})

Path relative redirects are also possible in express, for example if you are on http://localhost:3000/users/sai/edit the following .. will redirect to http://localhost:3000/users/sai.

res.redirect('..')

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course