In web development, redirection is a common task. It involves sending the client to a different URL than the one they originally requested. This can be useful for various reasons such as handling legacy URLs, directing users to a new page after an action, or managing authentication.
Express.js provides several methods to handle redirections, making it straightforward to implement these functionalities in your applications.
In Express.js, you can redirect a request using the res.redirect() method. This method takes one argument: the URL to which you want to redirect the client. You can also specify an optional status code as the first argument, with the default being 302 (Found).
The res.redirect() method ends the response process and sends a redirect HTTP header to the client.
Here's a simple example of how to redirect a request to another route within your Express application:
1const express = require('express');2const app = express();34app.get('/old-route', (req, res) => {5res.redirect('/new-route');6});78app.get('/new-route', (req, res) => {9res.send('Welcome to the new route!');10});1112app.listen(3000, () => {13console.log('Server is running on http://localhost:3000');14});
In this example, any request made to /old-route will be redirected to /new-route.
You can also specify a status code when redirecting. For instance, if you want to use a permanent redirect (HTTP 301), you can do so like this:
1app.get('/old-page', (req, res) => {2res.redirect(301, '/new-page');3});45app.get('/new-page', (req, res) => {6res.send('This is the new page.');7});
You can also redirect users to external websites:
1app.get('/external-link', (req, res) => {2res.redirect('https://www.example.com');3});
In this case, any request made to /external-link will be redirected to https://www.example.com.
You can use conditions to decide whether to redirect a request. For example, you might want to redirect users based on their authentication status:
1app.get('/protected-page', (req, res) => {2if (!req.isAuthenticated()) {3return res.redirect('/login');4}5res.send('Welcome to the protected page!');6});
In this example, if a user is not authenticated, they will be redirected to the /login route.
After learning how to redirect requests in Express.js, you might want to explore setting HTTP status codes. Understanding and using different status codes can help you manage responses more effectively and provide better feedback to clients.
By mastering redirections and response handling in Express.js, you'll be well-equipped to build robust and user-friendly web applications.