Gatsby with Azure AppInsights

Azure App Insights is very useful to track user interaction on our business applications. And as it turns out, Gatsby is very good to make business applications with.

New Gatsby Site

I'm going to start off by making a new Gatsby site.

> npm --version
6.9.0
> node --version
v10.1.0
> npm i -g gatsby-cli
...
> gatsby new gatsby-azure-example
...
> gatsby develop
...

Open up "localhost:8000" in your browser and see the default starter.

Default Starter

Deploying to Azure Storage Account

A more full-fledged pipeline might be better, but for now I'm just going to create a storage account and deploy to that.

New Storage Account

Azure Static Website


I can create a production build with npm run build and upload it with Azure Storage Explorer.

Azure Storage Explorer

Adding Application Insights

App Insights


Now let's add Azure App Insights to our application by hooking into the Gatsby Browser API with the tracking code as shown in the Azure Docs. Do replace <YOUR INSTRUMENTATION KEY FROM AZURE APP INSIGHTS> with your actual key.

let injectedScript = false

export const onInitialClientRender = () => {
    function addJS(jsCode) {
        var s = document.createElement(`script`);
        s.type = `text/javascript`;
        s.innerText = jsCode;
        document.getElementsByTagName(`head`)[0].appendChild(s);
    }
    if (!injectedScript) {
        addJS(`
    var appInsights = window.appInsights || function (a) {
        function b(a) { c[a] = function () { var b = arguments; c.queue.push(function () { c[a].apply(c, b) }) } } var c = { config: a }, d = document, e = window; setTimeout(function () { var b = d.createElement("script"); b.src = a.url || "https://az416426.vo.msecnd.net/scripts/a/ai.0.js", d.getElementsByTagName("script")[0].parentNode.appendChild(b) }); try { c.cookie = d.cookie } catch (a) { } c.queue = []; for (var f = ["Event", "Exception", "Metric", "PageView", "Trace", "Dependency"]; f.length;)b("track" + f.pop()); if (b("setAuthenticatedUserContext"), b("clearAuthenticatedUserContext"), b("startTrackEvent"), b("stopTrackEvent"), b("startTrackPage"), b("stopTrackPage"), b("flush"), !a.disableExceptionTracking) { f = "onerror", b("_" + f); var g = e[f]; e[f] = function (a, b, d, e, h) { var i = g && g(a, b, d, e, h); return !0 !== i && c["_" + f](a, b, d, e, h), i } } return c
    }({
        instrumentationKey: "<YOUR INSTRUMENTATION KEY FROM AZURE APP INSIGHTS>"
    });

    window.appInsights = appInsights, appInsights.queue && 0 === appInsights.queue.length && appInsights.trackPageView();
      `);
        injectedScript = true;
    }
}

export const onRouteUpdate = ({ location, prevLocation }) => {
    window.appInsights.trackPageView();
}

Examining Results

Back in the Azure Portal on the App Insight, click on Browsers and inspect your website.

Insights

Summary

Gatsby is well suited for business applications that track user metrics which are used to make informed decisions.