Tracking Cloudflare Worker requests using Application Insights
- Gérald Barré
This website is hosted on a static website hosting provider and I use Cloudflare CDN to improve the performance. These 2 services allow me to host this website for free even if I got more and more visitors. However, I do not have lots of analytics. For instance, I want to know where the user comes from using the HTTP referer header or if they got a 404. Google Analytics is useful but most users use an adblocker, and it doesn't work well with 404 pages Application Insights, among other features, allows to track requests. In this post, we'll see how to integrate Application Insights into Cloudflare.
Cloudflare Workers allows to handle requests and serve the response to the client. If you are familiar with Azure, Cloudflare Workers are similar to Azure Functions. Using Workers, you can serve the content from your original server and track the request to Application Insights.
To deal with Cloudflare Workers, you need to install
npm install -g @cloudflare/wrangler wrangler login
Then, you can generate the project:
wrangler generate application-insights
This will create a folder with a few files. The most important ones are
wrangler.toml. You can edit the
index.js file with the following content:
The code of the worker is complete. Before publishing the project to Cloudflare, you will need to update the following fields in the
wrangler.toml file: You can find your
account_id in the right sidebar of your account's Workers page, and
zone_id in the right sidebar of a zone's overview tab at https://dash.cloudflare.com.
Once you have filled both fields, you can publish the project:
Last, you need to associate the worker on your website. Go to the Workers page, and click on the "Add route" button. Enter the route
You can now see the requests in Application Insights:
Do you have a question or a suggestion about this post? Contact me!