Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions integrations/posthog/gitbook-manifest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ configurations:
enum:
- EU
- US
identifyUsers:
type: boolean
title: Identify Users
description: Enable user identification in PostHog to track individual user behavior
default: false
required:
- projectApiKey
- instanceAddress
Expand Down
35 changes: 24 additions & 11 deletions integrations/posthog/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,23 @@ type PostHogRuntimeContext = RuntimeContext<
{
projectApiKey?: string;
instanceAddress?: 'EU' | 'US';
identifyUsers?: boolean;
}
>
>;

export const handleFetchEvent: FetchPublishScriptEventCallback = async (
event,
{ environment }: PostHogRuntimeContext,
{ environment, currentUser }: PostHogRuntimeContext,
) => {
const instancesURLs = {
EU: 'https://eu.posthog.com',
US: 'https://app.posthog.com',
};
const projectApiKey = environment.siteInstallation?.configuration?.projectApiKey;
const instanceAddress = environment.siteInstallation?.configuration?.instanceAddress;
const identifyUsers = environment.siteInstallation?.configuration?.identifyUsers ?? false;

if (!projectApiKey) {
throw new Error(
`The PostHog project API key is missing from the space configuration (ID: ${
Expand All @@ -42,17 +45,27 @@ export const handleFetchEvent: FetchPublishScriptEventCallback = async (
);
}

return new Response(
(script as string)
.replace('<ph_project_api_key>', projectApiKey)
.replace('<ph_instance_address>', instancesURLs[instanceAddress]),
{
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'max-age=604800',
},
let scriptContent = script as string;
scriptContent = scriptContent.replace('<ph_project_api_key>', projectApiKey);
scriptContent = scriptContent.replace('<ph_instance_address>', instancesURLs[instanceAddress]);

// Add user identification after PostHog initialization if enabled
if (identifyUsers && currentUser) {
scriptContent += `
posthog.identify("${currentUser.id}", {
name: "${currentUser.displayName || ''}",
email: "${currentUser.email || ''}",
avatar: "${currentUser.photoURL || ''}"
});
`;
}

return new Response(scriptContent, {
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'max-age=604800',
},
);
});
};

export default createIntegration<PostHogRuntimeContext>({
Expand Down