#how to add content-security-policy

1 messages · Page 1 of 1 (latest)

solid pythonBOT
#

Hi @vital prawn. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Sure, I can help you with that.

In Next.js, you can add Content Security Policy (CSP) in the next.config.js file. CSP helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks. It can specify allowed origins for content including scripts, stylesheets, images, fonts, objects, media (audio, video), iframes, and more.

Here is an example of how you can add Content Security Policy directives using a template string:

// Before defining your Security Headers
// add Content Security Policy directives using a template string.
 
const ContentSecurityPolicy = `
 default-src 'self';
 script-src 'self';
 child-src example.com;
 style-src 'self' example.com;
 font-src 'self';
`

When a directive uses a keyword such as self, wrap it in single quotes ''.

In the header's value, replace the new line with a space.

{
 key: 'Content-Security-Policy',
 value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim()
}

If you want to load scripts, images etc. from other domains, you need to adapt the Content Security Policy accordingly.

If you are serving SVG images with the default Image Optimization API, you can set dangerouslyAllowSVG inside your next.config.js and it is strongly recommended to also set contentDispositionType to force the browser to download the image, as well as contentSecurityPolicy to prevent scripts embedded in the image from executing.

module.exports = {
 images: {
 dangerouslyAllowSVG: true,
 contentDispositionType: 'attachment',
 contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
 },
}

Please note that the CSP needs to be correctly configured to avoid errors. If you are seeing an error in the Chrome console, it might be due to a misconfiguration in your CSP. Make sure that all the resources you are loading are allowed in your CSP.

#

@vital prawn kapa.ai is still learning and improving, please let us know how it did by reacting below

vital prawn
#

I found following code in starter blog template

#

const ContentSecurityPolicy = default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline' giscus.app analytics.umami.is; style-src 'self' 'unsafe-inline'; img-src * blob: data:; media-src *.s3.amazonaws.com; connect-src *; font-src 'self'; frame-src giscus.app