How to disable access to certain parts of an express server but be able to enable it later

I have a server that is fully functioning, but I only want it to be accessable when I say. I do this via a discord bot which works fine. I currently have a boolean variable server_on and an
if (server on) { do }
in all of my app.get and app.post functions.

Is there a cleaner way to do this, or is this if statement in every function the only way?

Edit:
Final working code

var block_server_middleware = function (req, res, next) {
    if (!server_on) { res.send("server is currently unavailable") }
    else { next() }
}

app.use(block_server_middleware)

and the other app.get and app.post functions were not changed at all This was the only few lines added that made the whole idea work

Answer

You can define one middleware function that goes before all your routes are defined:

app.use((req, res, next) => {
    if (!server_on) {
        // stop all routing
        res.send("server not on!");
    } else {
        // let routing continue
        next();
    }
});

This will keep your routes from ever getting run until server_on is back to true. If you have any routes you want to leave open all the time, then just place them before this middleware.

You can replace res.send("server not on!"); with whatever is appropriate for your use. You can return a single web page or you can send back a 4xx or 5xx error status (perhaps a 503 error).

Leave a Reply

Your email address will not be published. Required fields are marked *