Disable X-Powered-By in nestjs does not work

Viewed 1850

I want to disable X-Powered-By in nestjs like the following, but it does not work.

main.ts:

async function bootstrap() {
    const logger = new Logger('bootstrap') 
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
  
    app.disable('X-Powered-By') // this line
    ...
    
    const PORT = process.env.PORT
    await app.listen(PORT);
    logger.log(`Application is start on port : ${PORT}`)
  }
  
  bootstrap();

After disabling the X-Powered-By header, in the next requests, that X-Powered-By header still exists.

Where am I doing something wrong?

4 Answers

If app.disable('x-powered-by') does not work, you can try/fix it with:

app.getHttpAdapter().getInstance().disable('x-powered-by');

If you are using TypeScript and you get an error in your IDE saying Property 'disable' does not exist on type 'INestApplication', then specify the app type in your NestFactory.create call.

Your code should look like below, and the error on the app.disable call will be gone.

const app = await NestFactory.create<NestExpressApplication>(AppModule)

app.disable('x-powered-by')

Try to use: app.disable('x-powered-by') - so all lower-case and it should work!

The right way is by adding helmet because not only remove x-powered-by but also help with other headers

Related