working version with pages router
This commit is contained in:
parent
f4edab87af
commit
c3b93e592a
13 changed files with 193 additions and 3 deletions
|
@ -1,9 +1,17 @@
|
|||
import { type NextIncomingMessage } from 'next/dist/server/request-meta';
|
||||
import { headers } from 'next/headers';
|
||||
|
||||
export async function trackEvent(eventName: string, props?: Record<string, string | number | boolean>): Promise<void> {
|
||||
export async function trackEvent(
|
||||
eventName: string,
|
||||
props?: Record<string, string | number | boolean>,
|
||||
req?: NextIncomingMessage,
|
||||
): Promise<void> {
|
||||
const appKey = globalThis.__APTABASE__.appKey;
|
||||
if (!appKey) return Promise.resolve();
|
||||
|
||||
const userAgent = getUserAgent(req);
|
||||
if (!userAgent) return Promise.resolve();
|
||||
|
||||
const body = JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
sessionId: 'CHANGE-THIS',
|
||||
|
@ -21,7 +29,7 @@ export async function trackEvent(eventName: string, props?: Record<string, strin
|
|||
const response = await fetch('http://localhost:3000/api/v0/event', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'User-Agent': headers().get('User-Agent') ?? '',
|
||||
'User-Agent': userAgent,
|
||||
'Content-Type': 'application/json',
|
||||
'App-Key': appKey,
|
||||
},
|
||||
|
@ -37,3 +45,21 @@ export async function trackEvent(eventName: string, props?: Record<string, strin
|
|||
console.warn(`Failed to send event "${eventName}": ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
function getUserAgent(req?: NextIncomingMessage): string | undefined {
|
||||
if (req) {
|
||||
return req.headers['user-agent'] ?? 'Unknown';
|
||||
}
|
||||
|
||||
// headers() might throw an error if called outside of a request context.
|
||||
try {
|
||||
return headers().get('User-Agent') ?? 'Unknown';
|
||||
} catch {}
|
||||
|
||||
// If we're here, we're probably using the Pages Router and the user forgot to pass the req parameter.
|
||||
if (!req) {
|
||||
console.warn("Aptabase: The 'req' parameter of trackEvent is required when using Pages Router.");
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue