Created
September 11, 2021 11:22
-
-
Save guydumais/52534b8c7d913d319e04ab2e076840fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
// Next.js libraries | |
import Document, { Html, Head, Main, NextScript } from 'next/document' | |
// Next Strict Content Security Policy | |
import { NextStrictCSP } from 'next-strict-csp' | |
... | |
// Cloudflare Insights Script (Optional) | |
const cloudflareJs = `var s = document.createElement('script') | |
s.src = 'https://static.cloudflareinsights.com/beacon.min.js' | |
s.setAttribute('data-cf-beacon', '{"token": "YOUR CLOUDFLARE WEB ANALYTICS TOKEN STRING"}') | |
document.body.appendChild(s)` | |
// Google Tag Manager Script (Optional) | |
const GTMJs = `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': | |
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], | |
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= | |
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); | |
})(window,document,'script','dataLayer','YOUR GOOGLE TAG MANAGER ID STRING');` | |
// Next Strict CSP | |
// Inline scripts to hash (Optional) | |
NextStrictCSP.inlineJs = [ | |
cloudflareJs, | |
GTMJs | |
] | |
... | |
// Enable Head Strict CSP in production mode only | |
const HeadCSP = process.env.NODE_ENV === 'production' ? NextStrictCSP : Head | |
... | |
// Document component | |
class MyDoc extends Document { | |
render() { | |
return ( | |
<Html> | |
<HeadCSP> | |
{ process.env.NODE_ENV === 'production' && | |
<meta httpEquiv="Content-Security-Policy" /> | |
} | |
... | |
{/* Google Tag Manager */} | |
{ process.env.NODE_ENV === 'production' && | |
<script | |
dangerouslySetInnerHTML={{ | |
__html: GTMJs | |
}} | |
/> | |
} | |
{/* End Google Tag Manager */} | |
</HeadCSP> | |
<body> | |
{ process.env.NODE_ENV === 'production' && | |
<noscript | |
dangerouslySetInnerHTML={{ | |
__html: `<iframe src="https://www.googletagmanager.com/ns.html?id=YOUR GOOGLE TAG MANAGER ID STRING" height="0" width="0" style="display:none;visibility:hidden"></iframe>`, | |
}} | |
/> | |
} | |
... | |
<Main /> | |
<NextScript /> | |
{/* Cloudflare Web Analytics */} | |
{/*<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon={`{"token": "YOUR CLOUDFLARE WEB ANALYTICS TOKEN STRING"}`}></script>*/} | |
{process.env.NODE_ENV === 'production' && | |
<script dangerouslySetInnerHTML={{ | |
__html: cloudflareJs | |
}} /> | |
} | |
{/* End Cloudflare Web Analytics */} | |
... | |
</body> | |
</Html> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment