reactjsshopifycontent-security-policyshopify-hydrogen

In Shopify Hydrogen, the Image component triggers CSP


The error

"Refused to apply inline style because it violates the following Content Security Policy directive..."

Background

I'm aware of the requirement for this security feature but my particular problem is specifically to do with Hydrogen's Image component.

Using Shopify Hydrogen (mostly demo store), there is a Product Card component. Inside you'll find the following code...

return (
    <div className="flex flex-col gap-2">
      <Link
        onClick={onClick}
        to={`/products/${product.handle}`}
        prefetch="intent"
      >
        <div className={clsx("grid gap-4", className)}>
          <div className="card-image aspect-[4/5] bg-primary/5">
            {image && (
              <Image
                className="fadeIn w-full object-cover"
                sizes="(min-width: 64em) 25vw, (min-width: 48em) 30vw, 45vw"
                aspectRatio="4/5"
                data={image}
                alt={image.altText || `Picture of ${product.title}`}
                loading={loading}
              />
            )}

The problem

If I remove the image component and replace with <></> the security errors go away. So I know it is to do with the Image component. But I can't alter Shopify's component.

Note: I have checked the domains are permitted by the security policy - so this would appear to be an inline styles issue.

The dev tools unfortunately don't tell you where the CSP issue actually is.

Question

What can I do to satisfy the security requirements and safely use the Image component in Shopify's Hydrogen?

Thanks.


Solution

  • It is highly likely that it is the "sizes" property which is being output as a style attribute on the image. This counts as inline style. Attributes are not nonceable and they can only be allowed by hashes if you also add 'unsafe-hashes'. Another option is to allow 'unsafe-inline', some may disagree, but it isn't that bad if you restrict the rest of your CSP, ref https://scotthelme.co.uk/can-you-get-pwned-with-css/.