Integrating Azure Application Insights with Next.js. The Easy Way.

Nirbhay luthra
2 min readNov 10, 2021

--

Integrating Azure AppInsights with Next.js is not easy.
After checking tons of Articles, old libraries, and outdated packages (never use old/ outdated libraries and packages), I found the correct and most accessible way to integrate and implement Azure Application Insights (Azure AppInsights) with a Next.js project.

I have created this easy workaround after some brainstorming and getting some help from my teammates. We will be using React Plugin provided by Application Insights here: https://docs.microsoft.com/en-us/azure/azure-monitor/app/javascript-react-plugin .

First, you Need to Install React Plugin :

npm install @microsoft/applicationinsights-react-js @microsoft/applicationinsights-web --save

Now inside the documentation, you will find the configuration written like this :

This configuration will not work, only because Next.js does not provide a history and createBrowserHistory element, and this is required to get the correct path/route of our website.

To fix this we will create our own History object for Next.js.
Its code is below :

That's all you need to do. Now your Application Insights will work perfectly.

What I did in this code:-
1. I have created an Object defaultBrowserHistory, filled it with some data that AppInsight requires, and made our browserHistory = defaultBrowserHistory.
2. Whenever our page is loaded (line number 10) I have made our browserHistory equal to window.history .
3. On line 27 I am initializing AppInsignts only when window is available .

That it!!

Now you can just wrap your component. Do not use HOC withAITracking that they have shown there.

Use React Context (AppInsightsContext.Provider) as shown below, also shown in the documentation.

This solves the problem without using complicated methods like outdated libraries, SDKs, etc.
Thanks for Reading!!!.

--

--