简体   繁体   中英

NestJS: How to hide an endpoint in production build?

I want to add an endpoint that would simplify development/testing. At the same time, this endpoint is not needed in production. Coming from Java world, there has always been an out of the box solution (eg with profiles), but I didn't find anything like that in the NestJS documentation.

Quastion: Is there a way to implement an endpoint in NestJS that would not be available if the app is built for production use?

A few options depending on your use-case:

  1. Do you have an auth or role based access control scheme? Auth? NestJS has some Auth middleware that might help with this, but might be too heavyweight if this is a one-off: tutorial

  2. One fast and loose way to do this would be to return 404 based on an environment variable. Set the env var differently in your dev servers than production.

if(process.env.ENV_VAR === 'production') {
  throw new HttpException('Not Found', HttpStatus.NOT_FOUND)
}

  1. A good way to do this if you're going to need a lot of internal routes consistently in Prod or out might be to set up private and public routes by essentially adding a second server your project and proxy it differently.

This is an old question, but I had similar problem and solved it like this:

function getControllers(): Array<Type<unknown>> {
  // add all the non-conditional controllers here
  const controllers: Array<Type<unknown>> = []
  if(process.env["NODE_ENV"] !== "production")
    controllers.push(DevController)
  // possible other conditional controllers
  return controllers
}

Now when I create the AppModule I do it like this:

@Module({
  imports: [/* imports */],
  controllers: getControllers(),
  providers: [/* providers */]
})
export class AppModule {}

This way I can have conditional controllers that can be included or excluded from the app depending on environmental configuration.

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