expressjs
  1. expressjs-redirects

ExpressJS Redirects

Syntax

response.redirect([status,] path)

Example

const express = require('express')
const app = express()

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

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

Output

When accessing /redirect endpoint, the browser will be redirected to https://www.google.com.

Explanation

In ExpressJS, response.redirect() is used to redirect the user from the current URL to another URL.

This method automatically sets the response status code to 302 Found for temporary redirects and 301 Moved Permanently for permanent redirects. Additionally, it sets the Location header to the specified URL, which tells the browser to request the new URL.

Use

response.redirect() is useful for implementing URL redirections, especially when you need to redirect the user to a different domain or to a different page within the same domain.

Important Points

  • The URL passed to response.redirect() can be relative or absolute.
  • If you pass a status code as the first parameter, it specifies the HTTP status code to use for the redirect.
  • If no status code is specified, 302 Found is used by default.
  • When running behind a reverse proxy, you may need to set the trust proxy setting to true to properly handle the Location header.

Summary

In ExpressJS, response.redirect() is used to redirect the user to a different URL. It sets the Location header to the specified URL and automatically sets the HTTP status code to 302 Found or 301 Moved Permanently. This method is useful for implementing URL redirections within your application.

Published on: