简体   繁体   中英

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

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: 它在这里说开发,但你会把它设置为生产

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.

If using swagger-express-mw and swagger-tools for swagger-UI

This is how i do the same inside my app.js

if (process.env.NODE_ENV === 'development') {
  SwaggerExpress.create(config, function (err, swaggerExpress) {
    if (err) { throw err; }

    app.use(SwaggerUi(swaggerExpress.runner.swagger));
    // install middleware
    swaggerExpress.register(app);

    app.listen(PORT);
  });
} else {
  app.listen(PORT, () => console.log(`Server started @ Port - ${PORT}`));
}

Instead of or in addition to disabling the Swagger UI, you might also choose to access protect it. Here's how we did both using HTTP Basic Auth. In your main.ts or equivalent, here with a Node.js application using NEST:

const customNestApplication = (app: INestApplication) => {

  // [...]

  const swaggerEnabled = configService.get('swagger.enabled', { infer: true });

  if (
    swaggerEnabled &&
    configService.get('swagger.auth.user', { infer: true }) &&
    configService.get('swagger.auth.password', { infer: true })
  ) {
    app.use(
      `${configService.get('swagger.path', { infer: true })}`,
      basicAuth({
        challenge: true,
        users: {
          [configService.get('swagger.auth.user', { infer: true })]: 
          configService.get('swagger.auth.password', { infer: true }),
        },
      }),
    );
  }

  // Set up Swagger as usual, etc.
  // [...]

  return app.listen(port);
};

See also another answer specifically about Swagger auth, for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM