Skip to content

Commit 8ae517c

Browse files
committed
Added support for posthog identity api
1 parent a506385 commit 8ae517c

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

integrations/posthog/src/index.ts

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,23 @@ type PostHogRuntimeContext = RuntimeContext<
1313
{
1414
projectApiKey?: string;
1515
instanceAddress?: 'EU' | 'US';
16+
identifyUsers?: boolean;
1617
}
1718
>
1819
>;
1920

2021
export const handleFetchEvent: FetchPublishScriptEventCallback = async (
2122
event,
22-
{ environment }: PostHogRuntimeContext,
23+
{ environment, currentUser }: PostHogRuntimeContext,
2324
) => {
2425
const instancesURLs = {
2526
EU: 'https://eu.posthog.com',
2627
US: 'https://app.posthog.com',
2728
};
2829
const projectApiKey = environment.siteInstallation?.configuration?.projectApiKey;
2930
const instanceAddress = environment.siteInstallation?.configuration?.instanceAddress;
31+
const identifyUsers = environment.siteInstallation?.configuration?.identifyUsers ?? false;
32+
3033
if (!projectApiKey) {
3134
throw new Error(
3235
`The PostHog project API key is missing from the space configuration (ID: ${
@@ -42,17 +45,27 @@ export const handleFetchEvent: FetchPublishScriptEventCallback = async (
4245
);
4346
}
4447

45-
return new Response(
46-
(script as string)
47-
.replace('<ph_project_api_key>', projectApiKey)
48-
.replace('<ph_instance_address>', instancesURLs[instanceAddress]),
49-
{
50-
headers: {
51-
'Content-Type': 'application/javascript',
52-
'Cache-Control': 'max-age=604800',
53-
},
48+
let scriptContent = script as string;
49+
scriptContent = scriptContent.replace('<ph_project_api_key>', projectApiKey);
50+
scriptContent = scriptContent.replace('<ph_instance_address>', instancesURLs[instanceAddress]);
51+
52+
// Add user identification after PostHog initialization if enabled
53+
if (identifyUsers && currentUser) {
54+
scriptContent += `
55+
posthog.identify("${currentUser.id}", {
56+
name: "${currentUser.displayName || ''}",
57+
email: "${currentUser.email || ''}",
58+
avatar: "${currentUser.photoURL || ''}"
59+
});
60+
`;
61+
}
62+
63+
return new Response(scriptContent, {
64+
headers: {
65+
'Content-Type': 'application/javascript',
66+
'Cache-Control': 'max-age=604800',
5467
},
55-
);
68+
});
5669
};
5770

5871
export default createIntegration<PostHogRuntimeContext>({

0 commit comments

Comments
 (0)