Let’s say you have a single GET route i.e. /ping
defined inside a simple HTTP server written in expressjs.
Due to some business requirement, you want to redirect all traffic coming on /ping
to /healthcheck
.
const express = require("express"); const app = express(); // routes app.get('/ping', (req,res) => { res.send('I am alive') }); const listener = app.listen(process.env.PORT, () => { console.log("Your app is listening on port " + listener.address().port); });
To achieve this we are going to introduce a middleware
.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
Our middleware is going to check if any request is coming on /ping
route, just redirect it to /healthcheck
.
So here is our clever middleware function
app.use(function (req, res, next) { if(req.url==='/ping'){ res.redirect('/healthcheck') } next() });
We need to introduce this middleware in our expressjs server before any routes like this
app.use(function (req, res, next) { if(req.url==='/ping'){ res.redirect('/healthcheck') } next() }); // routes app.get('/healthcheck', (req,res) => { res.send('I am alive') });
After this we also need to update the route so that it can handle request coming on /healthcheck
url.
app.get('/healthcheck', (req,res) => { res.send('I am alive') });
const express = require("express"); const app = express(); app.use(function (req, res, next) { if(req.url==='/ping'){ res.redirect('/healthcheck') } next() }); // routes app.get('/healthcheck', (req,res) => { res.send('I am alive') }); // listen for requests :) const listener = app.listen(process.env.PORT, () => { console.log("Your app is listening on port " + listener.address().port); });
Now if you make a GET request to /ping
URL, it will automatically redirect to /healthcheck
. And, if somebody makes a direct request to /healthcheck
he is still served with the same response i.e. I am alive