I have an app in Nuxtjs 2. I'm using nuxt-facebook-pixel-module to track user activity on my websites. I add Facebook conversion API to it. I created an API endpoint which calls the Facebook conversion API, and now I want to call this endpoint every time I change the route and call the client-side function this.$fb.track(). This must also be the first time you launch the website and also on every route change. I don't want to add the same code to all my subpages because it would be a lot of redundant code. Is it possible to do this somehow through the plugins folder or through middleware?
I tried to make this through the plugins directory, but it works only from the first route change. When I open the website it doesn't work. Only when I refresh my page or go to other subpage.
That's how my plugins code look:
export default async ({ app }) => {
app.router.afterEach(async (to, from) => {
const eventId = Math.floor(Math.random() * 100000).toString()
await fetch('/api/event-handle', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: [{some data}],
}),
})
app.$fb.track('ViewContent', {}, eventId)
})
}
and in my nuxt.config.js I add it like that:
plugins: [
{ src: '@/plugins/facebook-client.js', mode: 'client' },
],
But when I run this code I see that in console the $fb function have been called like on the screenshot:
But in network tab I don't see any fetch request, only when i refresh page or go to other route.
If anyone can help me, I will be very grateful.