Sling Academy
Home/Node.js/How to Redirect in Express.js and Node.js

How to Redirect in Express.js and Node.js

Last updated: December 28, 2023

Learn how to redirect (such as 301 permanent redirects, 302 temporary redirects) in Express.js and Node.js

Solution 1: Basic Redirection

Using the basic redirect method provided by Express, you can easily direct users to a different URL. This is achieved using the res.redirect() function.

  • Ensure your server is set up with Express.
  • Choose the route that will handle the redirect.
  • Use the res.redirect() method within the route handler to redirect the user.
const express = require('express');
const app = express();

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

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Pros: Simple and straightforward; supported natively by Express.

Cons: Doesn’t allow for more complex redirection logic.

Solution 2: Redirection with Status Codes

This method involves passing a HTTP status code to res.redirect() to indicate the nature of the redirect, with common status codes being 301 for permanent redirects and 302 for temporary.

  • Set up an Express server as previously described.
  • Determine the route and the type of redirect (permanent or temporary).
  • Pass the appropriate status code to res.redirect().
const express = require('express');
const app = express();

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

  // For a temporary redirect
  // res.redirect(302, '/new-page');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Pros: Allows you to define the type of redirect, which is useful for SEO and user agents.

Cons: Requires additional knowledge of HTTP status codes.

Solution 3: Conditional Redirection

For scenarios where the redirect depends on certain conditions, this solution employs middleware or route handlers that execute conditional logic before performing the redirect.

  • Start by setting up your Express server.
  • Create a route handler with condition checks.
  • Redirect based on the outcome of these checks.
const express = require('express');
const app = express();

app.get('/check-user', (req, res) => {
  const loggedIn = req.query.loggedIn === 'true';
  if (loggedIn) {
    res.redirect('/dashboard');
  } else {
    res.redirect('/login');
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Pros: Provides flexibility for redirects based on application state or user behavior.

Cons: May lead to more complex code and require careful management of conditions to prevent errors.

Conclusion

Redirecting in Express.js is a fundamental part of web development, allowing for a better user experience and website management. The simplest method is using the native res.redirect() method, but you can also use status codes to indicate the type of redirect, or incorporate conditional logic for dynamic redirects. Each approach serves different scenarios, and understanding the nuances will help you implement the most appropriate redirection strategy for your application.

Next Article: How to Integrate H2 Database with Express and Node.js

Previous Article: How to Manage Cookies in Express JS

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates