Express redirect

An express redirect is one of several options when it comes to responding to an incoming http request. Often a response will involve just sending some json, text, or html, but in some cases a redirect is called for. In express redirects can be done with the res.redirect response method, for the most part just the url of the resource to redirect to is all that needs to be passed, but some times it is not that simple when it comes to the response status codes. So in this post I will be writing about all things express redirect related that I come across that are note worthy.

1 - Express redirect basic example

So for a basic express redirect all I need to do is just pas the response that I want to redirect to as the first argument to the res.redirect method.

let express = require('express'),
app = express();
app.get('/', (req, res) => {
res.send('you can not escape me');
app.get('*', (req, res) => res.redirect('/'));

This will work find assuming that a 302 http status code redirect will work okay. In most applications including very basic ones such as this a 302 redirect will work just fine, but in some cases you might want to set different one, so there can some times be more to this than just setting the location of the resource.

2 - Express redirect and 3xx http status codes

When it comes to http sttaus codes 3xx codes are of interest when it comes to express redirects. By default the status code that is set by res.redirect is 302, to set some other response code that code can be given as the first argument, and then the resource as the second argument like so.

app.get('/old/path/to-a-file.html', (req, res) => {
res.redirect(301, '/new/path/to-a-file.html');

3 - Conclusion

So there are some basics of express redirects, hope you found this post helpful. For more on express you might want to check out my main post on express.