Developer
Developer

Reputation: 143

How to set X-Frame-Options header without a custom server in Next.js?

I have a NextJS app that I need to set X-Frame-Options on, but I'm not sure how to do this. With Express, I would use helmetjs, but I want to avoid creating a custom server because:

Before deciding to use a custom server please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like serverless functions and Automatic Static Optimization.

Source: https://nextjs.org/docs/advanced-features/custom-server

Clearly, there are some drawbacks to using a custom server, and the page handler provided by Next works for me.

Upvotes: 6

Views: 8768

Answers (1)

juliomalves
juliomalves

Reputation: 50278

Without a custom server, this could be achieved by using custom headers in your next.config.js.

// next.config.js
module.exports = {
    async headers() {
        return [
            {
                source: '/(.*)?', // Matches all pages
                headers: [
                    {
                        key: 'X-Frame-Options',
                        value: 'DENY',
                    }
                ]
            }
        ]
    }
}

Upvotes: 10

Related Questions