Reputation: 75
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
Upvotes: 3
Views: 6369
Reputation: 16869
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.
Upvotes: 0
Reputation: 437
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}`));
}
Upvotes: 0
Reputation: 155
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.
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.Anyhow, once you're sure that NODE_ENV is production when the app is running in production, and with these assumptions:
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.
Upvotes: 4