pirsch-js-sdk
pirsch-js-sdk copied to clipboard
SDK is not working in Vercel
Hey, I was trying this SDK to send page views from the server side in Astro. This SDK works well on localhost, but it doesn't work on Vercel.
This is the middleware of my Astro project:
import { defineMiddleware } from 'astro/middleware';
import { Pirsch } from 'pirsch-sdk';
const HOST_NAME = import.meta.env.VERCEL_PROJECT_PRODUCTION_URL || "{MY SITE HOST NAME}"; // <- this has a real default value, I just omitted it for privacy purposes
const client = new Pirsch({
hostname: HOST_NAME,
clientId: import.meta.env.PIRSCH_CLIENT_ID,
clientSecret: import.meta.env.PIRSCH_CLIENT_SECRET
});
export const onRequest = defineMiddleware(async (context, next) => {
const userAgent = context.request.headers.get('User-Agent');
const url = context.url.toString();
if (!userAgent?.includes('vercel') && url.includes(HOST_NAME)) {
const data = {
...context.request,
url: url,
ip: context.clientAddress,
user_agent: context.request.headers.get('User-Agent') || '',
accept_language: context.request.headers.get('Accept-Language'),
sec_ch_ua: context.request.headers.get('Sec-CH-UA'),
sec_ch_ua_mobile: context.request.headers.get('Sec-CH-UA-Mobile'),
sec_ch_ua_platform: context.request.headers.get('Sec-CH-UA-Platform'),
sec_ch_ua_platform_version: context.request.headers.get('Sec-CH-UA-Platform-Version'),
sec_ch_width: context.request.headers.get('Sec-CH-Width'),
sec_ch_viewport_width: context.request.headers.get('Sec-CH-Viewport-Width'),
referrer: context.request.headers.get('Referer'),
tags: {}
};
console.log({ request: data })
client.hit(data)
.then(response => console.log({ response }))
.catch(error => console.error({
message: error?.message,
status: error?.status,
statusText: error?.statusText,
url: error?.url,
data: JSON.stringify(error?.data || {})
}));
}
return next();
});
This is what I see from the logs in Vercel:
We can see here it reached the dashboard from the localhost with no problems:
Any thoughts?
Hey Diego,
Your code looks fine. I can only assume that this is related to some firewall rule blocking the outgoing request? Because it runs into the timeout. I don't have any experience with Vercel myself, so I can't say for sure, but you should look into that.
Maybe try a simple GET request to pirsch.io first :)
Hey @Kugelschieber,
In the end, I opted to send the page views by making POST requests to the API, and it worked.
Honestly, I don't know if the SDK makes the API request differently or uses another API, but Vercel blocked it somehow.
Thank you for your quick response.
Hmm, very odd. We use Axios for the requests.
https://github.com/pirsch-analytics/pirsch-js-sdk/blob/master/src/client.ts#L27