Search code examples
javascriptnode.jsreactjshelmet.js

Does Using Helmet Package Protect My Frontend Aswell in Node.js with React.js


I have a question about how will i secure my frontend if i am using nodejs as a backend. For example i created my website fully with react as a frontend and my backend with nodejs and used Axios to get and post data from my backend to my frontend and so on.

My question now, if i use security measures in the backend will it also protect my frontend?

for exmaple if i use helmet in nodejs will the protections i add there for the response headers also be applied for my main website, which is the react frontend?

Here is some code of what i mean.

var express = require('express');
var helmet = require('helmet');
 
var app = express();
 
app.use(helmet());


app.use(
  helmet({
    frameguard: {
      action: "deny",
    },
  })
);

app.use(helmet.noSniff());
app.use(helmet.xssFilter());

will the above code in my backend nodejs server be enough to protect my website, or do i also need to set response headers and security measures in the front end, as i will be using the backend nodejs server as an API to interact with my react website.


Solution

  • tl;dr: to get Helmet's protections, you need to set Helmet's headers on whatever serves your pages. If your HTML pages are served by your Node backend, then you'll do it there.

    Helmet maintainer here.

    There are a bunch of HTTP response headers and they have various effects. For example, the Content-Type header tells browsers how to interpret the data. If Content-Type is text/html, browsers will interpret the data as HTML. If it's image/png, they'll interpret it as a PNG file.

    Helmet sets various HTTP response headers that have various effects.

    For example, Helmet sets the Content-Security-Policy header, which protects users from various attacks. Imagine the following HTML:

    <script>alert("Hello world!")</script>
    

    With no Content-Security-Policy response header, that JavaScript will run and users will see an alert. But if Content-Security-Policy is set to something like default-src 'self'; script-src 'none', browsers won't run that code at all.

    If your backend server isn't serving up the HTML, then those response headers won't be applied, and you won't get the protections. If you backend server is serving up the HTML, then you will! Generally, you want to put these response headers everywhere you can (though there are many exceptions).

    Also, as an aside: you're using Helmet multiple times in your code snippet above. You can shorten it to:

    app.use(
      helmet({
        frameguard: {
          action: "deny",
        },
      })
    );