Open In App

Next.js Security Headers

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll learn about security headers, their roles in website security, examples of security headers, and how to implement them in Next.js.

What are HTTP Headers?

HTTP headers are used to pass additional information or metadata using HTTP requests or responses. These headers are case-insensitive, in key-value pair format, and separated by a colon.

What are Security Headers?

Security Headers are a set of rules used to communicate between the user and the websites. It is a way to secure websites from security threats such as Cross-Site Scripting(XSS), Clickjacking, and Code injections.

 

Creating Next.js Application:

Step 1: To create a new NextJs App run the below command in your terminal:

npx create-next-app app_name

Step 2: After creating your project folder (i.e. GFG ), move to it by using the following command:

cd app_name

Project Structure: It will look like this:

 

First, let’s see what are the default security headers of NextJS: You can check the headers at your end by doing the following steps:

Step 1: Create the Next app

Step 2: Host the website on localhost

Step 3: Goto inspect

Step 4: Goto network

Step 5: Click on localhost

 

These are all default security headers. Security headers are not even mentioned in this response header and this does not mention security headers like Content-Security-Policy, X-Frame, HSTS, Permission-Policy, etc. If these policies are not mentioned, the security of the website can be damaged by threats like XSS, Code injection, and Clickjacking.

Examples of Security Headers: In the below section, we are going to see some examples, and along with that implementation of the same.

1. Content-Security-Policy header:

CSP headers are used to protect websites from malicious attacks. CSP allows you to set a policy that which domain can execute scripts and which one cannot. Using CSP we can define what content sources are allowed to load on a page. 

 

Syntax:

Content-Security-Policy: default-src <set_origin>

You can Set Origins as:

  1. self: Only your own domain will be kept as the requested domain.
  2. none: Won’t allow any domain.
  3. *: Will allow all domains.
  4. URL: URL of the domain which you want to allow. 

Example: Write the code in the belonging files:

  • File Name: next.config.js

Javascript




const nextConfig = {
    reactStrictMode: true,
    swcMinify: true,
    async headers() {
        return [
            {
                // Sets security headers for all routes
                source: '/(.*)',
                headers: [
                    {
                        key: 'Content-Security-Policy',
                        value:
                            "default-src 'self' https://geeksforgeeks.com/'; style-src 'self' ; image-src 'https://geeksforgeeks.org/';  script-src 'self' https://abcd.com; font-src 'self' 'https://example.com/'",
                    }
                ],
            },
        ];
    },
}
 
module.exports = nextConfig


Step to run the application: Run your Next app using the following command: 

npm run dev

Output:

 

2. X-Frame-Options header:

X-Frame-Options allow thwarting our own content which can be used in the invisible frames by attackers. Many sites use this security header to avoid Clickjacking attacks. This option actually allows whether or not a browser should be allowed to render a page in <frame>, <iframe>, <embed>, or <object>.

Syntax:

X-Frame-Options: DENY
X-Frame-Options: SAMEORIGIN
  • DENY: It is the most secure option. Basically, it stops the site from being rendered in <frame>.
  • SAMEORIGIN: It does allow the use of a frame. i.e the page can only be embedded in a frame with the exact origin.

Example: In the following code, we are going to set the X-Frame-Option which is going to be in the Key-Value pair. In value, we can set Deny or Sameorigin. We are going to keep Denying it which stops the site from being rendered in <frame>.

  • File Name: next.config.js

Javascript




const nextConfig = {
    reactStrictMode: true,
    swcMinify: true,
    async headers() {
        return [
            {
                // Sets security headers for all routes
                source: '/(.*)',
                headers: [
                    {
                        key: 'X-Frame-Options',
                        value: 'DENY',
                        //You can use SAMEORIGIN as a value also.
                    }
                ],
            },
        ];
    },
}
 
module.exports = nextConfig


Output:

 

3. Permission-policy header:

It is also known as Feature policy. Permission policy helps you to define which browser API to use and which not. For example, if your site doesn’t need a camera and microphone, you can simply disable them to protect your website from attackers.

Syntax:

Permissions-Policy: camera=(); 
                    battery=(self); 
                    geolocation=(); 
                    microphone=('https://a-domain.com')
  • Camera: Camera () is empty, which means that we deny the camera’s use.
  • Battery: Battery status will be allowed to our own domain only.
  • Geolocation: geolocation() is empty, which means that we deny the location’s use.
  • microphone: Allowed for the origin stated only.

Example: In the following code, we are going to set the Permission-policy which is going to be in the Key-Value pair. In value, we can set the camera, battery, geolocation, and microphone to simply disable them to protect your website from attackers. We can set the origin for values also for eg. microphone=(‘https://abc_domain.com’)” which allowed for stated origin only.

  • File Name: next.config.js

Javascript




const nextConfig = {
    reactStrictMode: true,
    swcMinify: true,
    async headers() {
        return [
            {
                // Sets security headers for all routes
                source: '/(.*)',
                headers: [
                    {
                        key: 'Permissions-Policy',
                        value: "camera=(); battery=(self);  browsing-topics=(); geolocation=(); microphone=('https://abc_domain.com')",
                        //Empty brackets are used to define that we are denying them..
                    }
                ],
            },
        ];
    },
}
 
module.exports = nextConfig


Output:

 

4. Referrer policy header:

When we click on a link that moves from one domain to another domain. Then the main domain is considered as the referrer. Using the Referrer Policy we can control the information(information about where the user came from) sent by the referrer domain to another domain.  

Syntax:

Referrer-Policy: origin-when-cross-origin
Referrer-Policy: strict-origin-when-cross-origin
  • origin-when-cross-origin: Sends the path, origin, and query string with a same-origin request.
  • strict-origin-when-cross-origin: Only the origin is sent in the Referrer header of cross-origin requests which is securer.

Example: In the following code, we are going to set the Referrer policy which is going to be in the Key-Value pair. In value, we can set origin-when-cross-origin orstrict-origin-when-cross-origin. We are going to set strict-origin-when-cross-origin which is secure.

  • File Name: next.config.js

Javascript




const nextConfig = {
    reactStrictMode: true,
    swcMinify: true,
    async headers() {
        return [
            {
                // Sets security headers for all routes
                source: '/(.*)',
                headers: [
                    {
                        key: 'Referrer-Policy',
                        value: 'strict-origin-when-cross-origin',
                    }
                ],
            },
        ];
    },
}
 
module.exports = nextConfig


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads