You have to combine a Gatsby plugin and build your own cookie consent banner or use a ready made component to achieve this.
First as AskaNor_29 suggested you need to install and configure the gatsby-plugin-gdpr-cookies
plugin. You can get the plugin here.
Configure the plugin in gatsby-config.js
// In your gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-gdpr-cookies`,
options: {
googleAnalytics: {
trackingId: 'YOUR_GOOGLE_ANALYTICS_TRACKING_ID',
// Setting this parameter is optional
anonymize: true
},
facebookPixel: {
pixelId: 'YOUR_FACEBOOK_PIXEL_ID'
},
// Defines the environments where the tracking should be available - default is ["production"]
environments: ['production', 'development']
},
},
],
}
The second part is showing a cookie consent banner or modal so the user can make his choice.
For this you can use the react-cookie-consent
npm module. You can get the npm package here.
To make it work with the gatsby-plugin-gdpr-cookies
, you need to set the cookieName="gatsby-gdpr-google-analytics"
prop.
Then you put the CookieConsent
component in your layout.js
file so it's activated on any page the user visits first.
<CookieConsent
location="bottom"
buttonText="Accept"
declineButtonText="Decline"
cookieName="gatsby-gdpr-google-analytics">
This site uses cookies ...
</CookieConsent>
The component takes many props so you can tweak the behaviour and looks.
If you want both Google Analytics and Facebook Pixel cookies to be set, there are callbacks for accepting/declining cookies where you can add your custom code to set both cookies.
If you're interested I wrote a longer how-to describing the steps.