In a Next.js app that uses App Router structure, I need to add a Content Security Policy (CSP) meta tag, like:
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src https://*; child-src 'none';" />
The problem:
The Metadata
object described in docs does not have built-in support for Content-Security-Policy
and also using the other
field is not an option, since it renders meta tags only with name
and content
attributes:
export const metadata = {
other: {
csp: "default-src 'self'; img-src https://*; child-src 'none';",
},
}
<meta name="csp" content="default-src 'self'; img-src https://*; child-src 'none';" />
The solution I’ve tried:
Add the <head>
tag in the RootLayout (/app/layout.tsx
):
export default function RootLayout({
// Layouts must accept a children prop.
// This will be populated with nested layouts or pages
children,
locale,
}: {
children: ReactNode,
locale: string
}) {
return (
<html lang={locale}>
<head>
<meta httpEquiv="Content-Security-Policy" content={csp} />
</head>
<body>
{children}
</body>
</html>
);
}
So far it seems to work. However, I was wondering if there is a more elegant solution for this.
Thanks.