How to Hide the X-Powered-By Header in NestJS

Atsushi Suzuki - May 19 - - Dev Community

While developing a backend application with NestJS, I noticed that the X-Powered-By: Express header appeared in the API responses during debugging. This can expose your technology stack to potential attackers.

API Response

To prevent this and enhance security, we need to hide the X-Powered-By header. Here’s how you can do it.

First, you should have the following code in your main file:

const app = await NestFactory.create(AppModule);
Enter fullscreen mode Exit fullscreen mode

Next, import the necessary modules:

import { ExpressAdapter } from '@nestjs/platform-express';
import express from 'express';
Enter fullscreen mode Exit fullscreen mode

Finally, modify the code as follows:

const expressApp = express();
expressApp.disable('x-powered-by');
const adapter = new ExpressAdapter(expressApp);
const app = await NestFactory.create(AppModule, adapter);
Enter fullscreen mode Exit fullscreen mode

With this change, the X-Powered-By header will no longer be visible.

Updated API Response

By following these steps, you can improve your application's security by not exposing your technology stack.

Note: Another method that works is as follows:

import { NestExpressApplication } from '@nestjs/platform-express';

const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.disable('x-powered-by');
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .