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.
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);
Next, import the necessary modules:
import { ExpressAdapter } from '@nestjs/platform-express';
import express from 'express';
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);
With this change, the X-Powered-By
header will no longer be visible.
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');
Top comments (2)
does the latter approach works for the Fastify adapter as well?
Thanks comment!
app.disable('x-powered-by')
is an Express feature and is not applicable to Fastify adapters. If you are using Fastify, you will need to disable theX-Powered-By
header using a different method.I think it will look something like this.