NodeJS: Mastering Express.js Redirections

Posted by

Master Express.js Redirections #NodeJS

Master Express.js Redirections

When working with Express.js, there are times when you need to redirect users from one URL to another. This can be useful for various reasons, such as when a URL has been updated or when you want to direct users to a different page based on certain conditions.

Fortunately, Express.js provides various methods for handling redirections. In this article, we will explore the different ways to perform redirections in an Express.js application.

Using res.redirect()

The most common way to perform a redirection in Express.js is by using the res.redirect() method. This method takes a URL as its argument and redirects the user to that URL.

Here’s an example of how to use res.redirect():

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

In the above example, when a user visits /old-url, they will be redirected to /new-url.

Redirection with status code

By default, res.redirect() will send a 302 temporary redirect status code. However, you can also specify a different status code by providing it as the first argument to the method.

For example, to perform a permanent redirect with a 301 status code, you can do the following:

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

Redirection using middleware

In some cases, you may want to perform a redirection based on certain conditions. This can be achieved by using middleware to check the conditions and then redirecting the user accordingly.

Here’s an example of how to use middleware for redirection:

	function checkLoggedIn(req, res, next) {
		if (req.user) {
			next();
		} else {
			res.redirect('/login');
		}
	}

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

In the above example, the checkLoggedIn middleware checks if the user is logged in and redirects them to the login page if they are not. If the user is logged in, the request is passed to the next middleware or route handler.

These are just a few examples of how you can perform redirections in an Express.js application. By using the res.redirect() method and middleware, you can efficiently handle URL redirections and provide a smooth user experience.