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
To achieve this we are going to introduce a
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
So here is our clever middleware function
We need to introduce this middleware in our expressjs server before any routes like this
After this we also need to update the route so that it can handle request coming on
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