Let's secure your next Next.js app (pun intended) in 3 minutes or less using HTTP response headers.
I will not go into details about every HTTP header used below. This Web Security Cheat Sheet from MDN is a great place to start learning about these.
However, I will point out that these headers provide some form of protection against cross-site scripting (XSS) vulnerabilities.
Using custom headers
Let's see some code!
First, let's create a new file headers.js
with every header used in the app. This way we'll keep our project structure clean and DRY.
module.exports = [
{
key: 'X-DNS-Prefetch-Control',
value: 'on',
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
{
key: 'Server',
value: 'Apache', // phony server value
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'X-Frame-Options',
value: 'sameorigin',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
{
key: 'Referrer-Policy',
value: 'same-origin',
},
{
key: 'Permissions-Policy',
value: 'geolocation=*', // allow specified policies here
},
];
Now that we have a single file for all our HTTP headers, we need to include them in the next.config.js
file.
const headers = require('./headers');
module.exports = {
// append this at the bottom of your next.config.js file
async headers() {
return [
{
source: '/(.*)',
headers,
},
];
},
};
This will apply the defined HTTP response headers to all routes in your application, as seen in this Vercel guide.
I have included these security headers in my Next.js starter template on Github. It has plenty of cool features I hope you'll like.
Closing thoughts
You can scan your app for possible vulnerabilities using this awesome tool. And if you have a Next.js app and forgot to secure it, now is the perfect time.
Something missing? Disagree with something from the article? I would love to hear your opinion in the comment section below.
Top comments (2)
using a separate module makes this cleaner, nice.
you don't mention the "Content-Security-Policy" which is the most complex in my opinion.
I have only deployed apps like these with Vercel and Digitalocean, but I assume it will work on heroku as well.