0
0
ExpressHow-ToBeginner · 4 min read

How to Redirect in Express: Simple Guide with Examples

In Express, you can redirect a client to a different URL using res.redirect(). This method sends a response that tells the browser to go to the new URL you specify.
📐

Syntax

The basic syntax for redirecting in Express is res.redirect([status], url). Here, res is the response object, status is an optional HTTP status code (like 301 or 302), and url is the destination URL.

  • res.redirect(url): Redirects with default status 302 (Found).
  • res.redirect(status, url): Redirects with the specified HTTP status code.
javascript
res.redirect('/new-path');
res.redirect(301, '/permanent-path');
💻

Example

This example shows a simple Express server that redirects requests from the root URL to /home. It also demonstrates a permanent redirect with status 301.

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

app.get('/', (req, res) => {
  res.redirect('/home'); // Temporary redirect (302)
});

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

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

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Some common mistakes when using res.redirect() include:

  • Forgetting to specify the status code when a permanent redirect is needed (default is 302, which is temporary).
  • Calling res.redirect() after sending a response, which causes errors.
  • Using relative URLs incorrectly; always ensure the URL is correct relative to the client.

Example of wrong and right usage:

javascript
// Wrong: sending response before redirect
app.get('/wrong', (req, res) => {
  res.send('This sends a response');
  // res.redirect('/home'); // This will cause an error if uncommented
});

// Right: redirect without sending response first
app.get('/right', (req, res) => {
  res.redirect('/home');
});
📊

Quick Reference

Here is a quick summary of res.redirect() usage:

UsageDescription
res.redirect(url)Redirects with HTTP status 302 (temporary) to the given URL.
res.redirect(status, url)Redirects with the specified HTTP status code to the URL.
res.redirect('/path')Redirects to a relative path on the same server.
res.redirect('https://example.com')Redirects to an absolute URL on another site.

Key Takeaways

Use res.redirect(url) to send a temporary redirect (HTTP 302) in Express.
Specify a status code like 301 for permanent redirects with res.redirect(status, url).
Always call res.redirect() before sending any other response to avoid errors.
URLs in res.redirect() can be relative paths or full absolute URLs.
Test redirects in your browser or with tools like curl to confirm behavior.