How to redirect in Express.js while passing some context?

Sometimes, we want to redirect in Express.js while passing some context.

In this article, we’ll look at how to redirect in Express.js while passing some context.

How to redirect in Express.js while passing some context?

To redirect in Express.js while passing some context, we can call res.redirect with a query string appended to the path.

For instance, we write

app.get('/category', (req, res) => {
  const string = encodeURIComponent('baz baz');
  res.redirect('/?foo=' + string);
});

app.get('/', (req, res) => {
  const passedVariable = req.query.foo;
  // ...
});

to call encodeURIComponent in the /category route handler to encode the URL parameter value.

And then we call res.redirect with the URL path and query string appended after it.

Then in the / route handler, we get the value of the foo query parameter with req.query.foo.

Conclusion

To redirect in Express.js while passing some context, we can call res.redirect with a query string appended to the path.