#Content Security Policy
64 messages · Page 1 of 1 (latest)
🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord
🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize
✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)
Are you trying to set up a nonce value?
I've found that https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy is pretty complete with all of the details necessary to set up a CSP, with one catch - if you want to set up a CSP using nonces, you forego being able to cache documents (since the nonce generated varies per request and is embedded into the document + the csp header)
(Also please note that is for app router, for page router: https://nextjs.org/docs/pages/building-your-application/configuring/content-security-policy)
Depending on your setup, it's possible to also intercept the cached document and inject the nonce prior to it being returned to the user, so you can achieve both caching and security. This person accomplished something similar with S3 + CloudFront: https://levelup.gitconnected.com/nonce-based-csp-with-aws-cloudfront-ae5a6752b9b0
also worth noting that nextjs' CSP omits the content-src directive, which is relevant for websockets.
One more thing, if you're interested in the security of your website, check out https://securityheaders.com, useful tool for testing security based on headers (but that alone isn't sufficient for testing stuff like auth security)
Yeah, well I believe it's necessary as the Styled Components simply do not work if I setup script-src
No matter where I do ```import { headers } from 'next/headers'
const nonce = headers().get('x-nonce')I get the same error,You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/react-essentials#server-components
basically this code
Well the error there is very clear, you can only call that headers() function in a server component.
Which doesn't make any sense, since it would mean that nothing is a server component
I literally tried calling it any file
are you calling it in the body of a component or at the top of the file? It was intended for the former, not the latter. Has to be called inside the component
also, wherever you call it, it is complaining that the component being imported calls headers. So you might have imports mixed up. Server components can contain client and server components, but client components can't contain server components that rely on those functions, afaik
well the simplest test is this ```import { Html, Head, Main, NextScript } from 'next/document'
import { headers } from 'next/headers'
export default function Document() {
const nonce = headers().get('x-nonce')
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
and it don't work
I've read a lot on it, and most people just give up on trying to setup CSP with Styled Components and Next.js but I am not quite sure that is a good idea lol
well, implementing a CSP is meant to impose certain restrictions. It's like a knight with very heavy armor. Limited mobility and less speed, but better protected, yes? While in a perfect world every website should have a CSP, it would actually be a perfect world if there were no attackers, instead. What is good against attackers might be harmful against consumers, and so, you have to take it on a case-by-case basis.
What I can tell you is, having a relaxed CSP is better than having no CSP. But having an incredibly restrictive CSP will make your options very limited.
That being said... the code you have should work. That looks like you are using the page router, my only experience is with app router.
If you manage to get that to work, I can tell you that when I was experimenting with using a nonce, passing it to the <Head /> tag appeared to make everything in the head have a nonce attribute applied, as well.
that, and/or returning a NextResponse from the middleware with the nonce included as a header, and also within the csp header
That is exactly what I tried, got some error lemme check
yeah strangely nextjs is sort of a "magic box". They have a lot of documentation, but it's not complete
yep, here it is: Type '{ children: Element; nonce: string | string[] | undefined; }' is not assignable to type 'IntrinsicAttributes & { children: ReactNode; }'. Property 'nonce' does not exist on type 'IntrinsicAttributes & { children: ReactNode; }'.ts(2322)
Oh, if the parameter does exist on the <Head /> component for your environment, make sure the nonce is not null or undefined
I recall that being a typing issue
yeah
I think it just doesn't work on the page router, there is no headers function doc in the page router documentation
you will need to read headers some other way, I suggest looking at https://nextjs.org/docs/pages/api-reference/functions
I have been testing these, but it's questionable if it's even possible ngl
I was initially deciding whether to just develop with the app directory a few months ago, but after testing it for a few weeks, a lot of things just didn't work
This is the first time I am running into a problem cuz I am using pages 🤣
ig they just abandoned it and now I am here in some tough spot
the app directory works well, I've migrated a frontend to it so far with decent success, but there is a steep learning curve. It requires rethinking browser web apps as a client/server model. People who make networked video games or any other kind of client/server model application will feel right at home. People who feel the browser is more their home will face challenges/obstacles, but not impossible ones
it should definitely be possible. What good is nextjs if it can't expose simple headers? lol
Funny, but it's somehow extremely difficult lol
This is the last thing I expected to have problems with
I mean this is literally in the pages directory documentation
So why the hell does it not work
🤣
it is funny how they make it easier to use external scripts than in-house ones lol
I am not sure, I wish I could help you better. We need someone here a little more savvy with the page router to explain this odd descrepancy between your code and the docs
I mean I can literally copy the docs line-for-line and it doesn't work
I would create a fresh project for experimentation purposes and have just what the docs have, and see if that even works. Maybe it's something they haven't updated, or we are missing info about your project setup
I am certain it's with 'em cuz read this error: You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/react-essentials#server-components
They placed it in the pages directory on the site and then I get this when I try to use it?
just search "Content Security Policy" on this forum, no one got a reply lol
mhm, it's hardly touched, sadly. Security is reactive, not proactive like it should be 
I would personally test it myself if I had the issue. If it turns out to be an actual problem, a github issue should be filed for it and then we can find a workaround in the meantime
It's 100% an issue, but ngl I am not super-well-versed in filling these things in github and whatnot
<@&752637460550385834> Any ideas?
Don't ping moderators for code-help.
Sorry.
@minor nymph I managed to get the nonce through some complicated code I found, but well, the styled components still don't work 🤣
Did just like you said, but oh well, idk what's wrong at this point <Head nonce={nonce} />
Also, I even checked the site, the nonce is indeed actually there
Well, I am stuck on finally having the nonce, but the styled components still not working for some reason, I am going to sleep now but here's the code if someone is feeling brave to find the issue with the Styled Components: ```import Document, {
Html,
Head,
Main,
NextScript,
type DocumentContext,
type DocumentInitialProps,
} from 'next/document';
type Props = DocumentInitialProps & { nonce: string };
const MyDocument = (props: Props) => {
const { nonce } = props;
return (
<Html className="h-full">
<Head nonce={nonce} />
<body className="h-full">
<Main />
<NextScript nonce={nonce} />
</body>
</Html>
);
};
MyDocument.getInitialProps = async (
ctx: DocumentContext
): Promise<DocumentInitialProps & { nonce: string }> => {
const initialProps = await Document.getInitialProps(ctx);
const nonce = ctx.req?.headers?.['x-nonce'] as string;
return {
...initialProps,
nonce,
};
};
export default MyDocument;```
Well, seems like we're in a pickle.
