Why Gatsby sites need cookie consent
Gatsby builds static HTML at compile time, but that doesn't mean it's cookie-free. The moment you add Google Analytics, a Meta Pixel, Hotjar, or any third-party embed, your static site sets cookies. And if you serve EU visitors, you need consent before those cookies fire.
The good news: adding consent to Gatsby is simpler than most frameworks because you control exactly when scripts load. There's no server-side rendering to worry about and no hydration race conditions.
Quick setup: one script tag
The fastest way to add CookieBeam to Gatsby is through gatsby-ssr.js (or gatsby-ssr.tsx):
// gatsby-ssr.js
exports.onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
<script
key="cookiebeam"
src="https://cdn.cookiebeam.com/banner/YOUR_BANNER_ID/default/loader.js"
async
/>,
]);
};Replace YOUR_BANNER_ID with your actual banner ID from the CookieBeam dashboard. That's it. The banner loads on every page and handles consent collection, cookie blocking, and Consent Mode signals automatically.
Blocking scripts until consent
If you're loading analytics or marketing scripts via Gatsby's gatsby-ssr.js or gatsby-browser.js, you need to make sure they don't fire before consent. Two approaches:
Option 1: Let CookieBeam handle it (recommended)
CookieBeam's auto-blocking mode detects known tracking scripts and blocks them until the visitor consents. If your scripts are loaded via standard script tags, this works out of the box.
Option 2: Conditional loading in gatsby-browser.js
// gatsby-browser.js
exports.onClientEntry = () => {
// Listen for CookieBeam consent events
window.addEventListener('cookiebeam:consent', (e) => {
if (e.detail.analytics) {
// Load Google Analytics only after consent
const script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXX';
document.head.appendChild(script);
}
});
};This gives you full control over what loads and when.
Google Consent Mode with Gatsby
If you use Google Tag Manager or gtag.js, add the consent default before the GTM script loads:
// gatsby-ssr.js
exports.onRenderBody = ({ setHeadComponents }) => {
setHeadComponents([
// CookieBeam handles consent default + updates automatically
<script
key="cookiebeam"
src="https://cdn.cookiebeam.com/banner/YOUR_BANNER_ID/default/loader.js"
async
/>,
// GTM loads after CookieBeam sets the default consent state
<script
key="gtm"
dangerouslySetInnerHTML={{
__html: `(function(w,d,s,l,i){w[l]=w[l]||[];...})(window,document,'script','dataLayer','GTM-XXXXX');`
}}
/>,
]);
};CookieBeam sets consent('default', ...) before GTM initializes, so Google tags respect the consent state from the first pageview.