Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Swagger on Node/Express API

I'm using Swagger to document my Node/Express API on my dev environment. It's working perfectly but now I need to disable it when going to production, in order to not let the API definition publicly reachable.

Is there a way to do it, using some npm script for example ?

Thanks

like image 456
tR4x Avatar asked Nov 27 '25 01:11

tR4x


1 Answers

Keeping in line with convention, you wanna set NODE_ENV environment variable (environment variables are values set on OS, with no dependence to your app) to make things depend on the environment you're currently on. This'll heavily depend on where do you host your production app.

  • If it's an AWS ECS deployment, you'll need to set it in AWS Systems Manager Parameter Store for example.
  • Or if it's just a vanilla cloud instance that you ssh into, you probably run your app with something along the lines of node app.js or npm run start (Or maybe you're using docker and your script ends with one of these commands.) In any case, before the execution of the "run application" command, make sure environment is set to production via export NODE_ENV=production command. You can check whether it worked via echo $NODE_ENV command.
  • Or in case you're using docker-compose, you can set env vars as such: it says development here but you'll set it to production

Anyhow, once you're sure that NODE_ENV is production when the app is running in production, and with these assumptions:

  • your application is named "app" in your startup file and you define middlewares as "app.use(..."
  • your swagger route is something like "http://localhost:PORT/docs"

With these assumptions, make it so that this is the first "app.use" type, middleware definition in your code:

if(process.env.NODE_ENV === "production"){
  app.use('/docs', (req, res, next) => {
    res.status(404).send("Not Found");
  });
}

If any of the assumptions I've made does not pertain to your case, adjust them accordingly. And you're done.

like image 50
user2485309 Avatar answered Nov 29 '25 16:11

user2485309