Replies: 2 comments 2 replies
-
Had the same issue, the import dynamic from 'next/dynamic';
import type { ComponentType, ReactElement } from 'react';
type DynamicOptions = {
loading?: () => ReactElement | null;
ssr?: boolean;
};
export async function dynamicWithNonce<P extends Record<string, unknown>>(
importFn: () => Promise<{ default: ComponentType<P> }>,
options: DynamicOptions = {},
) {
// Create a wrapper component with static options
const WrappedComponent = dynamic(importFn, {
loading: options.loading,
ssr: options.ssr,
});
// Only add nonce if we're in a Server Component
if (typeof window === 'undefined') {
try {
const { headers } = await import('next/headers');
const headersList = await headers();
const nonce = headersList.get('x-nonce') || '';
// Add nonce to the component
Object.defineProperty(WrappedComponent, 'nonce', {
value: nonce,
writable: false,
configurable: false,
});
} catch (error) {
// If we're not in a Server Component, just continue without the nonce
}
}
return WrappedComponent;
} |
Beta Was this translation helpful? Give feedback.
2 replies
-
Thank you for bringing this up, unfortunately the solution does not work for my use case. I decided to flag it in the following issue: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
I am trying to apply the strict CSP rules by following the official NextJs guide here. The application works correctly but I am getting CSP violation errors on the console for loading these scripts under the
<head>
tag:These scripts are related to components loaded dynamically through the
dynamic
NextJs function and I believe the issue might be caused by the function calling thepreload
functionality fromreact-dom
(see call here).After some more investigation, I found out that the issue only happens when loading lazy loaded component on client components and not server components.
Has anyone encountered this issue before? Any suggestions for resolving it?
Additional information
Error message:
Example
Codesandbox Link: https://codesandbox.io/p/devbox/9ymssd
Beta Was this translation helpful? Give feedback.
All reactions