ExpressJS: turning off the 'x-powered-by' header

After researching the express documentation and Stack Overflow, it seems like I can remove the X-Powered-By: Express header by using app.disable('x-powered-by'). You can find the documentation for app.disable here, and the list of toggleable settings here.

This is a basic express server setup:

// src/server.js
import express from 'express'
import logger from 'morgan'
import router from './routes/index.js'

export const createServer = () => {
  const app = express()

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

  app.use(logger('dev'))
  app.use(express.json())
  app.use(express.urlencoded({ extended: true }))

  app.use(router)
  return app
}

const app = createServer()

export default app

// src/index.js
import { SERVER_PORT, SERVER_ORIGIN } from './config/index.js'
import app from './server.js'

const port = parseInt(SERVER_PORT, 10)

const server = app.listen(port, () => {
  console.info(`[Server] ${SERVER_ORIGIN}.`)
})

export default server

Even though I have included app.disable('x-powered-by') right after creating the app, when testing with curl the header still appears:

$ curl localhost:5000 -v

*   Trying 127.0.0.1:5000...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.65.3
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 16
< ETag: W/"10-/VnJyQBB0+b7i4NY83P42KKVWsM"
< Date: Wed, 22 Apr 2020 12:08:35 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{"message":"ok"}

I even attempted changing the capitalization (app.disable('X-Powered-By')), but unfortunately, it didn't make a difference. What could be causing this issue?

Answer №1

The issue stems from the file 'routes/index.js':

import Router from 'express'

const router = Router()

This action doesn't generate a router, instead it creates a new app with individual settings.

To fix this problem, the correct implementation should have been:

import express from 'express'

const router = express.Router()

Answer №2

give this a go as well

app.set('x-powered-by', false)

This method has proven effective for me.


You can also attempt app.disable('x-powered-by') following the line const app = createServer()

Answer №3

The issue lies in the fact that instances of Router() do not follow global app settings and instead revert to default settings. Currently, headers must be manually disabled on each individual instance of Router():

const router = Router()
router.disable('x-powered-by')

Refer to this Github issue for more information.

For a minimal example showcasing the problem, visit this repository.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubles with github authentication using Everyauth are being discussed on the Promises issue

Upon visiting url.com/auth/github and authorizing github, I encounter an error message indicating that the promise has not been fulfilled despite implementing it in App.js. Code snippet from App.js: var appPath = __dirname + '/app' , http = ...

Ensure users follow step-by-step journey in Vue Material's steppers and connect each step to a designated path

I'm just starting out with web development and I have a question. I want to design a stepper with 5 tabs that restricts navigation - for example, you can't proceed to step 3 without completing step 2, and so on. If a user is on step 4 but wants t ...

Receiving a 200 ok status, but encountering a response error in Postman

Receiving a response with a 200 OK status, but encountering an error message in Postman. { "errors": "Unable to log you in, please try again.", "success": false } Post Url: [{"key":"Content-Type","value":"application/json","descript ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

What is the most effective method for incorporating personalized React components in the midst of strings or paragraph tags

Summary: Exploring the frontend world for the first time. Attempting to integrate custom components within p-tags for a website, but facing challenges in making them dynamically changeable based on user interaction. Greetings all! As a newbie in front-end ...

Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionalit ...

Tips for adding multiple entries to a TransactionWould you like to know

I have a question regarding SQL Server transactions I need to insert data into both Table_A and Table_B. Table_B includes a key from Table_A, and the number of records in Table_B with the Table_A key can vary. [Table_A] id: , title: [Table_B] ...

Retrieve the JavaScript object that was initialized within a function

As I venture into the world of working with javascript objects and php objects, I've encountered an issue. While everything seems to be functioning correctly so far, I'm having trouble accessing the javascript object created in the ajax success r ...

Issues with Angular $watch causing mismatches in bindings更新(binding)

I am attempting to set default values for certain model properties by using $watches. I cannot utilize the typical two-way binding because I want the model properties to start off as empty. Although the $watches are successfully setting the properties, the ...

Guidelines for updating state in React following a delay?

Trying my hand at creating a basic roulette wheel using React, I encountered an issue where setting the state spinning to false at the end of the function did not seem to have any effect. import React, { useState } from "react"; const numbers = ...

Error loading XMLHttpRequest on LocalHost

Below is the code I am working on: <script type="text/javascript> $(".link").click(function(){ var id = this.id; if(id == 'b1'){ $( "#content" ).load( "test.html", function(){ alert('Successfully loaded!'); ...

The 404 error is handled by the express application before continuing to other routes. Some routes may not be recognized by the express.Router module

Shown below is the content of app.js: var express = require('express'); var routes = require('./routes/index'); app = express(); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next ...

What is the best method to access the query string or URL within an AJAX page?

I recently discovered how to extract query string parameters from this helpful resource. However, I am facing difficulty retrieving the URL within the requested page via ajax. For instance: <div class="result"></div> <script> $(func ...

Switch between animations triggered by a button

I am currently working on this code snippet: $(function(){ $("#modal-launcher, #modal-background, #modal-close").click(function () { $("#modal-content,#modal-background").toggle("slow"); return false; }); }); and here is the correspon ...

Is it possible to replicate two arrays in Angular through echoing?

I've run into an issue where I am struggling to return two arrays from an ajax request between Angular and PHP. Each array works fine on its own, but when trying to return both together, I encounter problems. I attempted to place the two arrays within ...

Heroku Node.js - Cross-Origin Resource Sharing (CORS) is functioning correctly for all API requests except for when using the image upload

Our web application contains numerous APIs that retrieve data from a Node.js server deployed on Heroku. Most of the APIs function correctly, with the exception of one that allows users to upload images to the server. While this API worked flawlessly in o ...

Transferring information from a file to a displayed page in Sails.js

I have a challenge in my application where I need to read a large dataset and send it to the client for manipulation with D3.js. The issue is that loading such big datasets can be time-consuming. My solution is to implement streaming, but I'm not sure ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Storing numerous JSON records into an array by parsing them from a file

As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me. I am dealing with multiple JSON feeds where each URL provides a multilayer JSON rec ...