Search code examples
node.jsexpressamazon-s3node-moduleshelmet.js

Allowing S3 images with npm helmet


I'm using npm helmet to secure my express app, but I want to allow images from my S3 bucket to render. I get this error when I use helment Refused to load the image '<URL>' because it violates the following Content Security Policy directive: "img-src 'self' data:". which makes sense, I am violating the CSP that helmet implements.

The only thing I've been able to find in their docs is:

app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

which does allow my images to render, but I still want the CSP that helmet provides. I just need to essentially whitelist my S3 link but I cant find anything in their docs on this topic


Solution

  • Maintainer of Helmet here.

    Helmet sets several security-related headers by default, including one called Content-Security-Policy. Content Security Policy, or CSP, is effectively an allowlist of what your page is allowed to load and do.

    You're seeing an error that indicates that your CSP doesn't allow images to be loaded from anywhere other than your domain ('self') or data URIs (data:). You could fix this with something like:

    app.use(
      helmet({
        contentSecurityPolicy: {
          directives: {
            ...helmet.contentSecurityPolicy.getDefaultDirectives(),
            "img-src": ["'self'", "s3.amazonaws.com"],
          },
        },
      })
    );
    

    For more on CSP, check out this introduction on MDN.

    This is something that I've been thinking about making clearer in Helmet's docs, so thanks for asking this question.