How to Integrate Application Insights into a Next.js App Deployed on Azure Static Web Apps: Problem and Solution

Rajesh Kumar Yadav - Sep 23 - - Dev Community

When building and deploying web applications, understanding how your users interact with your app and monitoring its performance are crucial. Azure Application Insights is a great service to track telemetry, performance, and user interactions in real-time. However, setting up Application Insights for a Next.js app deployed on Azure Static Web Apps can sometimes throw errors if environment variables like the instrumentation key aren’t correctly passed.

This blog post will walk through a common issue encountered during the setup and provide a step-by-step solution.

The Problem: Instrumentation Key Error in Next.js

When trying to integrate Application Insights in a Next.js app, you might encounter the following error during deployment:

Error: Please provide instrumentation key
    at throwError (/github/workspace/node_modules/@microsoft/applicationinsights-web/dist/es5/applicationinsights-web.js:206:15)
    at /github/workspace/node_modules/@microsoft/applicationinsights-web/dist/es5/applicationinsights-web.js:4941:33
    at Object._useHandler
Enter fullscreen mode Exit fullscreen mode

Image description
This error occurs when the Application Insights instrumentation key is not properly provided during the build process. Since Next.js requires environment variables to be passed both at build time and in the browser, failing to manage these variables properly can cause build errors or result in telemetry not being sent.

Understanding the Cause:

Missing Instrumentation Key: The key required for Application Insights isn't being passed from the environment variables during the build.
Incorrect Configuration of Environment Variables: Next.js requires certain environment variables, especially those needed in the client-side code, to use the NEXT_PUBLIC_ prefix to be accessible in both the server and browser environments.

The Solution: Managing the Instrumentation Key with GitHub Actions and Azure

To solve this, you can securely manage the Application Insights instrumentation key using GitHub Secrets and GitHub Actions during the deployment to Azure Static Web Apps. Below is the step-by-step process to fix this issue and successfully deploy the app.

Step-by-Step Solution

Step 1: Install and Configure Application Insights in Next.js

First, make sure that you have installed and set up Application Insights in your Next.js project.

Install the Application Insights SDK: In your Next.js project, install the SDK by running:

npm install @microsoft/applicationinsights-web
Enter fullscreen mode Exit fullscreen mode

Initialize Application Insights: Create a file called lib/appInsights.ts and add the following code to initialize the SDK:

import { ApplicationInsights } from '@microsoft/applicationinsights-web';

const appInsights = new ApplicationInsights({
  config: {
    instrumentationKey: process.env.NEXT_PUBLIC_APPINSIGHTS_INSTRUMENTATIONKEY, // Environment variable
  },
});

appInsights.loadAppInsights();

export default appInsights;
Integrate Application Insights into the App: In your app.tsx or app.js, import the initialized instance and ensure it tracks page views:

typescript
Copy code
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import appInsights from '../lib/appInsights';  // Adjust the path

function MyApp({ Component, pageProps }: any) {
  const router = useRouter();

  useEffect(() => {
    // Track initial page load
    appInsights.trackPageView();

    // Track page views on route change
    const handleRouteChange = (url: string) => {
      appInsights.trackPageView({ name: url });
    };

    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return <Component {...pageProps} />;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Instrumentation Key as a GitHub Secret

Since you'll deploy your app through GitHub Actions, you'll need to store your Application Insights instrumentation key securely in GitHub.

Go to GitHub Repository Settings:

Navigate to your repository on GitHub.
Go to Settings → Secrets and variables → Actions → New repository secret.
Add a New Secret:

Name: NEXT_PUBLIC_APPINSIGHTS_INSTRUMENTATIONKEY
Value: Your Application Insights instrumentation key from the Azure portal.

Step 3: Update GitHub Actions Workflow

Modify your GitHub Actions YAML file to include the instrumentation key during the build and deployment process.

Here’s an example of how to update the .github/workflows YAML file:

name: Azure Static Web Apps CI/CD

on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened, closed]
    branches:
      - main

jobs:
  build_and_deploy_job:
    if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
    runs-on: ubuntu-latest
    name: Build and Deploy Job
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: true
          lfs: false
      - name: Build And Deploy
        id: builddeploy
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_DELIGHTFUL_SMOKE_083D9AE03 }}
          repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for GitHub integrations (e.g., PR comments)
          action: "upload"
          app_location: "/" # App source code path
          api_location: "" # API source code path - optional
          output_location: "" # Built app content directory - optional
        env:
          NEXT_PUBLIC_STRIPE_PUBLIC_KEY: ${{ secrets.NEXT_PUBLIC_STRIPE_PUBLIC_KEY }}
          NEXT_PUBLIC_APPINSIGHTS_INSTRUMENTATIONKEY: ${{ secrets.NEXT_PUBLIC_APPINSIGHTS_INSTRUMENTATIONKEY }}  # Added here
Enter fullscreen mode Exit fullscreen mode

Step 4: Deploy and Verify

After pushing your updated workflow:

GitHub Actions will run the build and deployment process.
The instrumentation key will be passed as an environment variable during the build.
Your Next.js app will be deployed to Azure Static Web Apps with Application Insights properly configured.

Demo

Image description

Image description

Conclusion

By securely managing the Application Insights instrumentation key with GitHub Secrets and passing it through GitHub Actions, you can integrate powerful telemetry capabilities into your Next.js app without running into build issues. This approach ensures that environment variables are handled securely and effectively, both in development and production environments.

This setup provides real-time performance insights and user behavior tracking, helping you monitor and improve your app over time.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .