I have been working on a NextJS project and I am currently facing a challenge in setting up secure headers in the next.config.js file of my project.
I have attempted various solutions found online, but unfortunately, none of them seem to be working for me.
My primary goal is to configure the Content-Security-Policy
header to only allow essential resources such as stylesheets, scripts, fonts from fonts.googleapi.com, and images from the public
folder of my project.
Despite my efforts, I have not been successful. I even tried setting the header to default-src *
, but the website still loads without any styles or fonts applied.
I followed the guidelines provided by NextJS, but I am still unable to make it work. I feel quite lost and confused about the entire process.
index.js
export default function Index() {
const router = useRouter();
return (
<>
<Center h='100vh'>
<Box display='flex' flexDirection='column' justifyContent='center'>
<Stack spacing='10'>
<Box display='inline-block' mx='auto'>
<Image w='75px' src="/logo.jpeg" alt="logo" />
</Box>
{/* Card */}
<Box w={['280px', '300px']} borderRadius='lg' border='1px' borderColor='gray.200' shadow='lg' p='6'>
<Box textAlign='center'>
<Heading size='lg'>
Log in
</Heading>
</Box>
<Box my='6'>
<Divider />
</Box>
<Box>
<form>
<Stack spacing='6'>
<Box>
<FormControl>
<FormLabel htmlFor="username">Username</FormLabel>
<Input borderRadius='lg' type="text" id="username" />
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="password">Password</FormLabel>
<Input borderRadius='lg' type="password" id="password" />
</FormControl>
</Box>
<Box>
<Button w='100%' borderRadius='lg' colorScheme='green'>
Log in
</Button>
</Box>
</Stack>
</form>
</Box>
</Box>
</Stack>
</Box>
</Center>
</>
)
}
next.config.js
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self';
child-src example.com;
style-src 'self' example.com;
font-src 'self';
`;
const securityHeaders = [
{
key: "X-Frame-Options",
value: "deny"
},
{
key: "X-Content-Type-Options",
value: "nosniff"
},
{
key: "Referrer-Policy",
value: "strict-origin"
},
{
key: "Strict-Transport-Security",
value: "max-age=31536000; includeSubDomains; preload"
},
{
key: "X-XSS-Protection",
value: "1; mode=block",
},
{
key: "Permissions-Policy",
value: "camera=(self); battery=(); geolocation=(); microphone=()"
},
{
key: 'Content-Security-Policy',
value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim()
}
];
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async headers() {
return [
{
source: "/:path*",
headers: securityHeaders,
},
]
},
}
module.exports = nextConfig
globals.css
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap');
Chrome DevTools https://i.sstatic.net/hihd2.png
Errors after the answer from @tszhong0411 The errors I am getting now are from my service worker for my PWA app.
The red lines are my domain, but I reference them as example.com