LogoLogo
  • Contributing to RudderStack
  • Destination_Name
  • LICENSE
  • RudderStack Docs
  • docs
    • FAQ
    • Identity Resolution
    • Home
    • cloud-extract-sources
      • ActiveCampaign Source
      • Bing Ads
      • Chargebee
      • Common Settings
      • Facebook Ads
      • Freshdesk
      • Google Ads Source
      • Google Analytics
      • Google Search Console
      • Google Sheets
      • Cloud Extract Sources
      • Intercom v2
      • Intercom
      • Mailchimp
      • Marketo
      • Mixpanel
      • NetSuite
      • Pipedrive
      • QuickBooks
      • Salesforce Pardot
      • Sendgrid Source
      • Stripe Source
      • Xero
      • Zendesk Chat
      • Zendesk
      • hubspot
        • HubSpot Data Model and Schema Information
        • HubSpot
      • salesforce
        • Salesforce
        • Schema Comparison: RudderStack vs. Segment
    • connections
      • Connection Modes: Cloud Mode vs. Device Mode
    • data-governance
      • Data Governance
      • RudderTyper
      • Data Governance API
      • RudderTyper
      • tracking-plans
        • Tracking Plans
        • Tracking Plan Spreadsheet
    • data-warehouse-integrations
      • Amazon Redshift
      • Azure Data Lake
      • Azure Synapse
      • ClickHouse
      • Databricks Delta Lake
      • Google Cloud Storage Data Lake
      • Google BigQuery
      • Identity Resolution
      • Warehouse Destinations
      • Microsoft SQL Server
      • PostgreSQL
      • Amazon S3 Data Lake
      • Snowflake
      • FAQ
      • Warehouse Schema
    • destinations
      • Destinations
      • Webhooks
      • advertising
        • Bing Ads
        • Criteo
        • DCM Floodlight
        • Facebook App Events
        • Facebook Custom Audience
        • Facebook Pixel
        • Google Ads (gtag.js)
        • Google AdWords Enhanced Conversions
        • Google Adwords Remarketing Lists (Customer Match)
        • Advertising
        • LinkedIn Insight Tag
        • Lotame
        • Pinterest Tag
        • Reddit Pixel
        • Snap Pixel
        • TikTok Ads
      • analytics
        • Amplitude
        • AWS Personalize
        • Chartbeat
        • Firebase
        • FullStory
        • Google Analytics 360
        • Google Analytics
        • Heap.io
        • Hotjar
        • Analytics
        • Indicative
        • Keen
        • Kissmetrics
        • Kubit
        • Lytics
        • Mixpanel
        • Pendo
        • PostHog
        • Quantum Metric
        • Singular
        • adobe-analytics
          • Adobe Analytics Heartbeat Measurement
          • Mobile Device Mode Settings
          • Web Device Mode Settings
          • E-commerce Events
          • Adobe Analytics
          • Setting Up Adobe Analytics in RudderStack
        • google-analytics-4
          • Cloud Mode
          • Device Mode
          • Google Analytics 4
          • Setting up Google Analytics 4
        • profitwell
          • ProfitWell
          • Cloud Mode
          • Device Mode
      • attribution
        • Adjust
        • AppsFlyer
        • Branch
        • Attribution
        • Kochava
        • TVSquared
      • business-messaging
        • Business Messaging
        • Intercom
        • Kustomer
        • Slack
        • Trengo
      • continuous-integration
        • Visual Studio App Center
        • Continuous Integration
      • crm
        • Delighted
        • HubSpot
        • CRM
        • Salesforce
        • Variance
        • Zendesk
      • customer-data-platform
        • Customer Data Platform
        • Segment
      • error-reporting
        • Bugsnag
        • Error Reporting
        • Sentry
      • marketing
        • ActiveCampaign
        • AdRoll
        • Airship
        • Appcues
        • Autopilot
        • Blueshift
        • Braze
        • CleverTap
        • Customer.io
        • Gainsight PX
        • Gainsight
        • Marketing
        • Iterable
        • Klaviyo
        • Leanplum
        • Mailchimp
        • Marketo Lead Import
        • Marketo
        • MoEngage
        • Ometria
        • Pardot
        • Post Affiliate Pro
        • Qualtrics
        • SendGrid
        • Salesforce Marketing Cloud
        • Userlist
        • drip
          • Cloud Mode
          • Device Mode
          • Drip
          • Setting Up Drip in RudderStack
      • productivity
        • Google Sheets
        • Productivity
      • storage-platforms
        • Amazon S3
        • DigitalOcean Spaces
        • Google Cloud Storage
        • Storage Platforms
        • Azure Blob Storage
        • MinIO
        • Redis
      • streaming-platforms
        • Amazon EventBridge
        • Amazon Kinesis Firehose
        • Amazon Kinesis
        • Azure Event Hubs
        • BigQuery Stream
        • Confluent Cloud
        • Google Pub/Sub
        • Streaming Platforms
        • Apache Kafka
      • tag-managers
        • Google Tag Manager
        • Tag Managers
      • testing-and-personalization
        • Algolia Insights
        • Candu
        • Google Optimize
        • A/B Testing & Personalization
        • LaunchDarkly
        • Monetate
        • Optimizely Full Stack
        • Optimizely Web
        • Split.io
        • Statsig
        • VWO (Visual Website Optimizer)
    • get-started
      • RudderStack Cloud vs. RudderStack Open Source
      • Glossary
      • Get Started
      • RudderStack Architecture
    • reverse-etl
      • Amazon Redshift
      • Amazon S3
      • ClickHouse
      • FAQ
      • Google BigQuery
      • Reverse ETL
      • PostgreSQL
      • Snowflake
      • common-settings
        • Importing Data using Models
        • Importing Data using Tables
        • Common Settings
        • Sync Modes
        • Sync Schedule
      • features
        • Airflow Provider
        • Features
        • Models
        • Visual Data Mapper
    • rudderstack-api
      • Data Regulation API
      • HTTP API
      • RudderStack API
      • Personal Access Tokens
      • Pixel API
      • Test API
      • api-specification
        • Application Lifecycle Events Specification
        • API Specification
        • Video Events Specification
        • rudderstack-ecommerce-events-specification
          • Browsing
          • Coupons
          • E-Commerce Events Specification
          • Ordering
          • Promotions
          • Reviewing
          • Sharing
          • Wishlist
        • rudderstack-spec
          • Alias
          • Common Fields
          • Group
          • Identify
          • RudderStack Event Specification
          • Page
          • Screen
          • Track
    • rudderstack-cloud
      • Audit Logs
      • Dashboard Overview
      • Destinations
      • RudderStack Cloud
      • Live Events
      • Connection Modes: Cloud Mode vs. Device Mode
      • Sources
      • Teammates (User Management)
      • connections
        • Adding a Destination
        • Connections
    • rudderstack-open-source
      • Control Plane Setup
      • RudderStack Open Source
      • installing-and-setting-up-rudderstack
        • Developer Machine Setup
        • Docker
        • Data Plane Setup
        • Kubernetes
        • Sending Test Events
    • stream-sources
      • App Center
      • AppsFlyer
      • Auth0
      • Braze
      • Customer.io
      • Extole
      • Event Stream Sources
      • Iterable
      • Looker
      • PostHog
      • Segment
      • Shopify
      • Webhook Source
      • rudderstack-sdk-integration-guides
        • Client-side Event Filtering
        • SDKs
        • AMP Analytics
        • Cordova
        • .NET
        • Go
        • Java
        • Node.js
        • PHP
        • Python
        • React Native
        • Ruby
        • Rust
        • Unity
        • SDK FAQs
        • rudderstack-android-sdk
          • Adding Application Class
          • Flushing Events Periodically
          • Android
        • rudderstack-flutter-sdk
          • Flutter SDK v1
          • Flutter v2
          • Flutter
        • rudderstack-ios-sdk
          • iOS
          • tvOS
          • watchOS
        • rudderstack-javascript-sdk
          • Data Storage in Cookies
          • Detecting Ad-blocked Pages
          • JavaScript
          • JavaScript SDK Enhancements
          • JavaScript SDK FAQs
          • Querystring API
          • Quick Start Guide
          • Version Migration Guide
          • consent-managers
            • Consent Managers
            • OneTrust
    • transformations
      • Access Token
      • FAQ
      • Transformations
      • Transformations API
    • user-guides
      • User Guides
      • administrators-guide
        • Troubleshooting Guide
        • Alerting Guide
        • Bucket Configuration Settings for Event Backups
        • Configuration Parameters
        • Event Replay
        • High Availability
        • Horizontal Scaling
        • Administrator's Guides
        • Infrastructure Provisioning
        • Monitoring and Metrics
        • Okta SSO Setup
        • OneLogin SSO Setup
        • RudderStack Grafana Dashboard
        • Software Releases
      • how-to-guides
        • How to Use Custom Domains
        • How to Develop Integrations for RudderStack
        • How to Configure a Destination via the Event Payload
        • How to Filter Events using Different Methods
        • How to Filter Selective Destinations
        • How to Submit a Pull Request for a New Integration
        • How-to Guides
        • How to Debug Live Destination Events
        • How to Use AWS Lambda Functions with RudderStack
        • create-a-new-destination-transformer-for-rudder
          • Best Practices for Coding Transformation Functions in JavaScript
          • How to Create a New Destination Transformation for RudderStack
        • implement-native-js-sdk-integration
          • How to Add a Device Mode SDK to RudderStack JavaScript SDK
          • How to Implement a Native JavaScript SDK Integration
        • rudderstack-jamstack-integration
          • How to Integrate RudderStack with Your JAMstack Site
          • How to Integrate Rudderstack with Your Angular App
          • How to Integrate Rudderstack with Your Astro Site
          • How to Integrate Rudderstack with Your Eleventy Site
          • How to Integrate Rudderstack with Your Ember.js App
          • How to Integrate Rudderstack with a Gatsby Website
          • How to Integrate Rudderstack with a Hugo Site
          • How to Integrate Rudderstack with Your Jekyll Site
          • How to Integrate Rudderstack with Your Next.js App
          • How to Integrate Rudderstack with Your Nuxt.js App
          • How to Integrate Rudderstack with Your Svelte App
          • How to Integrate Rudderstack with Your Vue App
      • migration-guides
        • Migrating from Blendo to RudderStack
        • Migrating Your Warehouse Destination from Segment to RudderStack
        • Migration Guides
        • Migrating from Segment to RudderStack
  • src
    • @rocketseat
      • gatsby-theme-docs
        • text
          • Home
Powered by GitBook
On this page
  • Key features of this plugin
  • Installing the plugin
  • Setup
  • Step 1: Configure your Gatsby config file
  • Step 2: Identify your users with the identify() method:
  • Step 3: Track your users' actions with the track() method
  • Step 4: Check ready state
  • Using the Querystring API
  • Adding callbacks to standard methods
  • License
  • Contact Us

Was this helpful?

  1. docs
  2. user-guides
  3. how-to-guides
  4. rudderstack-jamstack-integration

How to Integrate Rudderstack with a Gatsby Website

Step-by-step guide to integrate RudderStack with your Gatsby site for event tracking.

PreviousHow to Integrate Rudderstack with Your Ember.js AppNextHow to Integrate Rudderstack with a Hugo Site

Last updated 3 years ago

Was this helpful?

You can quickly and easily get Rudderstack up and running in your Gatsby application by using Rudderstack's Gatsby plugin. It makes it easy to integrate your Gatsby website with the Rudderstack API and easily track events.

Key features of this plugin

  • Use multiple write keys (one for production environment, another optional one for development)

  • Disable page view tracking (just in case you want to add it later manually)

  • Always up-to-date and maintained by the RudderStack team

Installing the plugin

To install the plugin, run the following command with the package manager of your choice:

  • NPM: $ npm install --save gatsby-plugin-rudderstack

  • YARN: $ yarn add gatsby-plugin-rudderstack

Setup

Step 1: Configure your Gatsby config file

In your gatsby-config.js file you first need to add your write key from your account. You can find this in your RudderStack dashboard.

Configuration options

plugins: [
  {
    resolve: `gatsby-plugin-rudderstack`,
    options: {
      // your rudderstack write key for your production environment
      // when process.env.NODE_ENV === 'production'
      // required; non-empty string
      //NOTE: Do not commit this to git. Process from env.
      prodKey: `RUDDERSTACK_PRODUCTION_WRITE_KEY`,
      // if you have a development env for your rudderstack account, paste that key here
      // when process.env.NODE_ENV === 'development'
      // optional; non-empty string
      //NOTE: Do not commit this to git. Process from env.
      devKey: `RUDDERSTACK_DEV_WRITE_KEY`,
      // boolean (defaults to false) on whether you want
      // to include analytics.page() automatically
      // if false, see below on how to track pageviews manually
      trackPage: false,
      // number (defaults to 50); time to wait after a route update before it should
      // track the page change, to implement this, make sure your `trackPage` property is set to `true`
      trackPageDelay: 50,
      // If you need to proxy events through a custom data plane,
      // add a `dataPlaneUrl` property (defaults to https://hosted.rudderlabs.com )
      // Rudderstack docs:
      //   - https://rudderstack.com/docs/stream-sources/rudderstack-sdk-integration-guides/rudderstack-javascript-sdk/#31-load
      dataPlaneUrl: `https://override-rudderstack-endpoint`,
      // Add a `controlPlaneUrl` property if you are self-hosting the Control Plane
      // Rudderstack docs:
      //   - https://rudderstack.com/docs/stream-sources/rudderstack-sdk-integration-guides/rudderstack-javascript-sdk/#311-self-hosted-control-plane
      controlPlaneUrl: `https://override-control-plane-url`,
      // boolean (defaults to false); whether to delay load Rudderstack
      // ADVANCED FEATURE: only use if you leverage client-side routing (ie, Gatsby <Link>)
      // This feature will force Rudderstack to load _after_ either a page routing change
      // or user scroll, whichever comes first. This delay time is controlled by
      // `delayLoadTime` setting. This feature is used to help improve your website's
      // TTI (for SEO, UX, etc).  See links below for more info.
      // NOTE: But if you are using server-side routing and enable this feature,
      // Rudderstack will never load (because although client-side routing does not do
      // a full page refresh, server-side routing does, thereby preventing Rudderstack
      // from ever loading).
      // See here for more context:
      // GIF: https://github.com/benjaminhoffman/gatsby-plugin-segment/pull/19#issuecomment-559569483
      // TTI: https://github.com/GoogleChrome/lighthouse/blob/master/docs/scoring.md#performance
      // Problem/solution: https://marketingexamples.com/seo/performance
      delayLoad: false,
      // number (default to 1000); time to wait after scroll or route change
      // To be used when `delayLoad` is set to `true`
      delayLoadTime: 1000
      // Whether to completely skip calling `analytics.load()`.
      // ADVANCED FEATURE: only use if you are calling `analytics.load()` manually
      // elsewhere in your code or are using a library
      // that will call it for you.
      // Useful for only loading the tracking script once a user has opted in to being tracked, for example.
      // *Another use case is if you want to add callbacks to the methods at load time.
      manualLoad: false
    }
  }
];

Step 2: Identify your users with the identify() method:

The identify() method allows you to link users and their actions to a specific user ID.

A sample example of how the identify() method works in Gatsby is as shown:

class CallToAction extends React.Component {
    _handleCallToAction() {
        window.rudderanalytics.identify(
          "12345", {
            email: "name@domain.com"
          }, {
            page: {
              path: "/post",
              referrer: "internal",
              search: "",
              title: "Post Page",
              url: "",
            },
          }
        }
        render() {
            return (
                <Link onClick={ this._handleCallToAction } to="/write-post">Write a Post</Link>
              )
        }
}

In the above example, information such as the user ID, email along with contextual information such as IP address, anonymousId, etc. will be captured.

There is no need to call identify() for anonymous visitors to your website. Such visitors are automatically assigned an anonymousId.

Step 3: Track your users' actions with the track() method

The track() method allows you to track any actions that your users might perform. A sample example of how the track() method works is as shown:

window.rudderanalytics.track(
  "test track event GA3",
  {
    revenue: 30,
    currency: "USD",
    user_actual_id: 12345,
  },
  () => {
    console.log("in track call")
  }
)

In the above example, the method tracks the event ‘test track event GA3’, and information such as the revenue, currency, and anonymousId. You can use this method to track various other success metrics for your website, such as user signups, item purchases, article bookmarks, and much more.

To override contextual information, for ex: anonymizing IP and other contextual fields like page properties, the following template can be used. Similarly, you can override the auto-generated anonymousId with the provided ID. For this, follow the snippet below:

window.rudderanalytics.track(
  "test track event GA3",
  {
    revenue: 30,
    currency: "USD",
    user_actual_id: 12345,
  },
  () => {
    console.log("in track call")
  }
)

Tracking pageviews

However, if you want to pass in properties along with the pageview call (it is common to see some users pass in some user or account data with each page call), then you'll have to set trackPage: false and call it yourself in your gatsby-browser.js file, as shown below:

// gatsby-browser.js
exports.onRouteUpdate = () => {
  window.rudderanalytics && window.rudderanalytics.page()
}

You’ve now successfully installed rudder-analytics.js tracking. You can enable and use any event destination to send your event data via RudderStack.

Step 4: Check ready state

There are cases when you may want to tap into the features provided by end destination SDKs to enhance tracking and other functionalities.

RudderStack's JavaScript SDK exposes a ready API with a callback parameter, that fires when the SDK is done initializing itself and other third-party native SDK destinations. For example:

window.rudderanalytics.ready(() => {
  console.log("we are all set!!!")
})

Using the Querystring API

RudderStack's Querystring API allows you to trigger track, identify calls using query parameters.

If you pass the following parameters in the URL, then it will trigger the corresponding SDK API call. For example:

http://hostname.com/?ajs_uid=12345&ajs_event=test%20event&ajs_aid=abcde&ajs_prop_testProp=prop1&ajs_trait_name=Firstname+Lastname

For the above URL, the below SDK calls will be triggered:

rudderanalytics.identify("12345", { name: "Firstname Lastname" })
rudderanalytics.track("test event", { testProp: "prop1" })
rudderanalytics.setAnonymousId("abcde")

You may use the below parameters as a querystring parameter and trigger the corresponding call:

Parameter

Description

ajs_uid

Makes a rudderanalytics.identify() call with userId having the value of the parameter value.

ajs_aid

Makes a rudderanalytics.setAnonymousId() call with anonymousId having the value of the parameter value.

ajs_event

Makes a rudderanalytics.track() call with event name as parameter value.

ajs_prop_<property>

If ajs_event is passed as querystring, value of this parameter will populate the properties of the corresponding event in the track call.

ajs_trait_<trait>

If ajs_uid is provided as querystring, value of this parameter will populate the traits of the identify call made.

Adding callbacks to standard methods

You can also define callbacks to the common methods of the rudderanalytics object.

Currently, the functionality is supported for syncPixel method which is called in the SDK when making sync calls in integrations for relevant destinations. For example, you can load rudderanalytics with callbacks in your Gatsby browser file as shown below:

window.rudderanalytics.syncPixelCallback = obj => {
  window.rudderanalytics.track(
    "sync lotame",
    { destination: obj.destination },
    { integrations: { All: false, S3: true } }
  )
}

In order for this to work well, you must also set the manualLoad option to true in your Gatsby configuration, and load RudderStack in the browser's Gatsby file manually.

In the above example, we defined a syncPixelCallback on the rudderanalytics object before the call to load the SDK. This will lead to calling of this registered callback with the parameter {destination: <destination_name>} whenever a sync call is made from the SDK for relevant integrations like Lotame.

The callback can be supplied in options parameter like below as well:

// Define the callbacks directly on the load method like:
rudderanalytics.load(YOUR_WRITE_KEY, DATA_PLANE_URL, {
  clientSuppliedCallbacks: {
    syncPixelCallback: () => {
      console.log("sync done!")
    },
  },
})

License

Contact Us

If you want to track pageviews automatically, set trackPage to true in your gatsby-config.js file. What we mean by automatically is that whenever there is a route change, RudderStack leverages Gatsby's onRouteUpdate API in the gatsby-browser.js file () to invoke window.rudderanalytics.page() on each route change.

For detailed technical documentation and troubleshooting guide on the RudderStack’s JavaScript SDK, refer to .

This plugin is released under the .

For more information on any of the sections in this guide, please feel free to . You can also start a conversation in our community, or even see RudderStack .

link
JavaScript documentation
AGPLv3 License
contact us
Slack
in action