javascriptreactjsgatsbyuser-tracking

Can you count unique visitors to a website without server side code?


I have created a Gatsby blog for my friend, which means it is serverless and does not use a database. This works quite well for a blog which will only need builds every time I make changes or he adds a blog post - however it wouldn't work too well for tracking unique user visits as it would have to do too many builds if many people visited within a short time span.

Is there a way I can track unique user visits without a database involved?


Solution

  • Like it has been said, you need a third-party tool (like Google Analytics) since any workaround done in the front-end part will be related to the client/browser-side, then you'll lose the tracking if a user changes the device for example.

    You can easily install Analytics with some of the available plugins (like gatsby-plugin-google-gtag). This is recommended since under the hood uses gtag.js instead of analytics.js, which is what Google recommends due the last API changes.

    To use is just install it by:

    npm install gatsby-plugin-google-gtag // or yarn add gatsby-plugin-google-gtag
    

    And add your configurations:

    // In your gatsby-config.js
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-plugin-google-gtag`,
          options: {
            // You can add multiple tracking ids and a pageview event will be fired for all of them.
            trackingIds: [
              "GA-TRACKING_ID", // Google Analytics / GA
            ],
            // This object gets passed directly to the gtag config command
            // This config will be shared across all trackingIds
            gtagConfig: {
              optimize_id: "OPT_CONTAINER_ID",
              anonymize_ip: true,
              cookie_expires: 0,
            },
            // This object is used for configuration specific to this plugin
            pluginConfig: {
              // Puts tracking script in the head instead of the body
              head: false,
              // Setting this parameter is also optional
              respectDNT: true,
              // Avoids sending pageview hits from custom paths
              exclude: ["/preview/**", "/do-not-track/me/too/"],
            },
          },
        },
      ],
    }
    

    You can ignore the options you don't need.