DEV Community

Atsushi Suzuki
Atsushi Suzuki

Posted on

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

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

Top comments (2)

Collapse
 
micalevisk profile image
Micael Levi L. C.

does the latter approach works for the Fastify adapter as well?

Collapse
 
suzuki0430 profile image
Atsushi Suzuki

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 the X-Powered-By header using a different method.

I think it will look something like this.

import { FastifyAdapter } from '@nestjs/platform-fastify';

  const app = await NestFactory.create(AppModule, new FastifyAdapter());
  app.getHttpAdapter().getInstance().addHook('onSend', (request, reply, payload, done) => {
    reply.header('x-powered-by', '');
    done();
  });
Enter fullscreen mode Exit fullscreen mode