Hi, everyone. Thanks for having me at the React Advanced Conference 2023. I'm Lucas Esteveau. I'm a lead UI engineer contractor from Avenue Code at Apple since I moved to California about four years ago. I also host a Brazilian Portuguese podcast about career in tech. So if you're curious and are a Portuguese speaker, check it out on the major streaming platforms.
I'm really excited to talk to you about how should your Next.js app with a Content Security Policy today and I want to start answering why should I care about a Content Security Policy? Well, it turns out your browser is not 100% safe. Whether it's React or Next.js or any library or framework that you might be using for your web application. Although browsers do have security built-in features like single origin policy and course and libraries and frameworks like React and Next.js do a pretty decent job sanitizing the code and providing web features to close security gaps, we can't take it for granted. If a code like this is injected in your website, your browser or React default features can't prevent this from being executed. Meaning, your app could be exposed to cross-type scripting attacks, and precious data could be leaked.
That's when a CSP comes handy. A content security policy. It's a layer for security that helps to shield applications from attacks like cross-type scripting attacks, or data injection attacks, and it does it by restricting browser functionality. A content security policy is composed by a list of policy directives. The browser will be limited to allow only what you define in your policy. So here is an example of how a content security policy is composed. Here another example, where the policy directives, where I'm defining that the default sources content, let me go back to this one. Here are examples of policy directives where I'm defining that the default sources of content should come from my domain. And I'm adding an exception for fonts, because I want to allow Google Web Fonts to be downloaded.
There are two ways to implement a content security policy in your application. The first one is by adding a meta tag in the HTML head, but this one is not preferred. The other way, and the best way to go, is to create a header for it. So here we are adding a CSP key and the value that will hold our directives. In this case, as I said before, I'm saying that the default source of my content, it's gonna come from my domain, and adding an exception for fonts that can also come from Google. When it comes to Next.js, this is how a CSP looks like. You can simply add a list of directives in your header inside your next config file. You may define what kind of requests the CSP will be applied to using the source attribute. In this case, I'm saying that my content security policy will be applied for every single request. I'm not filtering, although you could do it, filtering your API for example.
Comments