N
Nuxt7mo ago
Notik

Facebook Conversion API calling by middleware on every route

Hey, I have a problem with Nuxt 3. I'm trying to do Facebook CAPI (documentation -> https://developers.facebook.com/docs/marketing-api/conversions-api/parameters). I need to read events on the website via the server. I did a post event and everything works. Unfortunately, when I upload it to Vercel, the events are not collected. I saw that on localhost my status was code 200, but on production it was 204 no content. Can anyone help me? That's how my server/api/facebook.post.ts looks
export default defineEventHandler(async (event) => {
const eventData = await readBody(event)

const url = `https://graph.facebook.com/v18.0/${process.env.FB_PIXEL_ID}/events?access_token=${process.env.FB_CAPI_TOKEN}`
const headers = {
'Content-Type': 'application/json'
}

try {
const response = await $fetch(url, {
method: 'POST',
headers,
body: eventData
})
return response
} catch (error) {
console.error('Error:', error)
}
})
export default defineEventHandler(async (event) => {
const eventData = await readBody(event)

const url = `https://graph.facebook.com/v18.0/${process.env.FB_PIXEL_ID}/events?access_token=${process.env.FB_CAPI_TOKEN}`
const headers = {
'Content-Type': 'application/json'
}

try {
const response = await $fetch(url, {
method: 'POST',
headers,
body: eventData
})
return response
} catch (error) {
console.error('Error:', error)
}
})
And that's how I call it by middleware in middleware/analytics.global.ts
export default defineNuxtRouteMiddleware(async () => {
const nuxtApp = useNuxtApp()

if ((nuxtApp as any).$fb) {
;(nuxtApp as any).$fb.track('ViewContent')

await $fetch('/api/facebook/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
data: [
{
event_name: 'ViewContent',
event_time: Math.floor(Date.now() / 1000),
action_source: 'website',
user_data: {
client_ip_address: '192.168.1.1',
client_user_agent: 'Chrome'
}
}
]
}
})
}
})
export default defineNuxtRouteMiddleware(async () => {
const nuxtApp = useNuxtApp()

if ((nuxtApp as any).$fb) {
;(nuxtApp as any).$fb.track('ViewContent')

await $fetch('/api/facebook/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
data: [
{
event_name: 'ViewContent',
event_time: Math.floor(Date.now() / 1000),
action_source: 'website',
user_data: {
client_ip_address: '192.168.1.1',
client_user_agent: 'Chrome'
}
}
]
}
})
}
})
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server