Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support for nonce prop #416

Merged
merged 1 commit into from
Aug 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/react/snippet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import { partytownSnippet } from '@builder.io/partytown/integration';
*
* @public
*/
export interface PartytownProps extends PartytownConfig {}
export interface PartytownProps extends PartytownConfig {
nonce?: string;
}

/**
* The React `<Partytown/>` component should be placed within the `<head>`
Expand All @@ -20,7 +22,7 @@ export interface PartytownProps extends PartytownConfig {}
*
* @public
*/
export const Partytown = (props: PartytownProps = {}): any => {
export const Partytown = ({ nonce, ...props }: PartytownProps = {}): any => {
// purposely not using useState() or useEffect() so this component
// can also work as a React Server Component

Expand All @@ -35,6 +37,7 @@ export const Partytown = (props: PartytownProps = {}): any => {
const scriptElm = document.createElement('script');
scriptElm.dataset.partytown = '';
scriptElm.innerHTML = partytownSnippet(props);
scriptElm.nonce = nonce;
document.head.appendChild(scriptElm);
}
// should only append this script once per document, and is not dynamic
Expand All @@ -48,7 +51,13 @@ export const Partytown = (props: PartytownProps = {}): any => {
// add the same script to the <head>.
const innerHTML = partytownSnippet(props) + 'document.currentScript.dataset.partytown="";';

return <script suppressHydrationWarning dangerouslySetInnerHTML={{ __html: innerHTML }} />;
return (
<script
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: innerHTML }}
nonce={nonce}
/>
);
};

interface PartytownDocument extends Document {
Expand Down