Set Response headers for react app deployed in linux web app

Parthiban Sekar 26 Reputation points
2023-10-20T12:26:07.4333333+00:00

I have a react app deployed in an azure linux web app. To improve our security posture, I have to set some response headers for this app. How can I achieve it? I use PM2 to serve the app. Node latest is our run time.

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,930 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Grmacjon-MSFT 19,151 Reputation points Moderator
    2023-10-20T21:23:32.3833333+00:00

    Hi @Parthiban Sekar On Azure Linux App Services, there is no ‘turn-key’ solution to customizing response headers, but there are a few ways it can be done.

    One way you can set custom response headers for your React app on Azure App Service Linux using PM2 is by utilizing the helmet middleware leware in your Node.js application.

    The helmet middleware is a collection of middleware functions that set security-related HTTP headers for your application.

    Here's how you can use the helmet middleware in your Node.js application:

      1. Install the helmet package by running the following command:
    npm install helmet
    
      1. In your Node.js application, require the helmet package and use it as middleware:
    const express = require('express');
    const helmet = require('helmet');
    
    const app = express();
    
    // Use helmet middleware
    app.use(helmet());
    
      1. You can also use individual middleware functions to set specific headers. For example, to set the Content-Security-Policy header, you can use the helmet.contentSecurityPolicy() middleware function:
    app.use(helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
        }
      }
    }))
    
    • Azure App Service Linux using PM2: This will allow setting response headers like CSP, XSS-Protection etc universally for your React App Service app at the Node.js server layer.
    • Please note that "Starting from Node 14 LTS, the container doesn't automatically start your app with PM2. To start your app with PM2, set the startup command to pm2 start <.js-file-or-PM2-file> --no-daemon. Be sure to use the --no-daemon argument because PM2 needs to run in the foreground for the container to work properly."

    I hope that helps! Let me know if you have any other questions.

    -Grace

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.