Skip to content

Commit be0d548

Browse files
committed
Enhances Astro Wizard for improved PostHog integration
Refactors the Astro wizard to streamline PostHog integration steps. Removes unnecessary TypeScript checks and redundant package installations, simplifying the user flow. Introduces a new documentation structure and code snippets for easier implementation guidance. Aims to improve user experience and integration efficiency for analytics in Astro projects.
1 parent cf17a5d commit be0d548

File tree

2 files changed

+88
-87
lines changed

2 files changed

+88
-87
lines changed

src/astro/astro-wizard.ts

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,9 @@ import {
77
ensurePackageIsInstalled,
88
getOrAskForProjectData,
99
getPackageDotJson,
10-
getPackageManager,
11-
installPackage,
12-
isUsingTypeScript,
1310
printWelcome,
1411
} from '../utils/clack-utils';
15-
import { getPackageVersion, hasPackageInstalled } from '../utils/package-json';
12+
import { getPackageVersion } from '../utils/package-json';
1613
import clack from '../utils/clack';
1714
import { Integration } from '../lib/constants';
1815
import { getAstroDocumentation } from './docs';
@@ -49,8 +46,6 @@ export async function runAstroWizard(options: WizardOptions): Promise<void> {
4946

5047
const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());
5148

52-
const typeScriptDetected = isUsingTypeScript(options);
53-
5449
await confirmContinueIfNoOrDirtyGitRepo(options);
5550

5651
const packageJson = await getPackageDotJson(options);
@@ -68,28 +63,16 @@ export async function runAstroWizard(options: WizardOptions): Promise<void> {
6863
cloudRegion,
6964
});
7065

71-
const sdkAlreadyInstalled = hasPackageInstalled('posthog-js', packageJson);
72-
73-
analytics.setTag('sdk-already-installed', sdkAlreadyInstalled);
74-
75-
const { packageManager: packageManagerFromInstallStep } =
76-
await installPackage({
77-
packageName: 'posthog-js',
78-
packageNameDisplayLabel: 'posthog-js',
79-
alreadyInstalled: !!packageJson?.dependencies?.['posthog-js'],
80-
forceInstall: options.forceInstall,
81-
askBeforeUpdating: false,
82-
installDir: options.installDir,
83-
integration: Integration.astro,
84-
});
66+
clack.log.info('Heading to include the PostHogSnippet in your Astro project');
8567

8668
const relevantFiles = await getRelevantFilesForIntegration({
8769
installDir: options.installDir,
8870
integration: Integration.astro,
8971
});
9072

9173
const installationDocumentation = getAstroDocumentation({
92-
language: typeScriptDetected ? 'typescript' : 'javascript',
74+
projectApiKey,
75+
host,
9376
});
9477

9578
clack.log.info('Reviewing PostHog documentation for Astro');
@@ -121,9 +104,6 @@ export async function runAstroWizard(options: WizardOptions): Promise<void> {
121104
integration: Integration.astro,
122105
});
123106

124-
const packageManagerForOutro =
125-
packageManagerFromInstallStep ?? (await getPackageManager(options));
126-
127107
await runPrettierStep({
128108
installDir: options.installDir,
129109
integration: Integration.astro,
@@ -156,7 +136,6 @@ export async function runAstroWizard(options: WizardOptions): Promise<void> {
156136
integration: Integration.astro,
157137
cloudRegion,
158138
addedEditorRules,
159-
packageManager: packageManagerForOutro,
160139
envFileChanged: addedEnvVariables ? relativeEnvFilePath : undefined,
161140
uploadedEnvVars,
162141
});

src/astro/docs.ts

Lines changed: 84 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,76 @@
1-
export function getAstroDocumentation(_: {
2-
language: 'typescript' | 'javascript';
3-
}): string {
1+
export function getAstroDocumentation({
2+
projectApiKey = 'your_project_api_key',
3+
host = 'https://us.i.posthog.com',
4+
}: {
5+
projectApiKey?: string;
6+
host?: string;
7+
}) {
48
return `
5-
# PostHog Astro Integration
6-
7-
PostHog makes it easy to get data about traffic and usage of your Astro app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.
8-
9-
## Installation
10-
11-
In your \`src/components\` folder, create a \`posthog.astro\` file:
12-
13-
\`\`\`bash
14-
cd ./src/components
15-
# or 'cd ./src && mkdir components && cd ./components' if your components folder doesn't exist
16-
touch posthog.astro
17-
\`\`\`
18-
19-
In this file, add your PostHog initialization code. Be sure to include the \`is:inline\` directive to prevent Astro from processing it:
20-
21-
\`\`\`astro
9+
==============================
10+
FILE: src/components/posthog.astro
11+
LOCATION: Components folder (create if missing)
12+
==============================
13+
Changes:
14+
- Add a PostHog loader script with \`is:inline\`.
15+
16+
Example:
17+
--------------------------------------------------
2218
---
2319
// src/components/posthog.astro
2420
---
25-
<script is:inline>
26-
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
27-
posthog.init('PUBLIC_POSTHOG_KEY', {
28-
api_host: 'PUBLIC_POSTHOG_HOST',
29-
})
21+
<script is:inline type="text/javascript" id="posthog-js">
22+
!(function(t, e) {
23+
var o, n, p, r;
24+
e.__SV ||
25+
((window.posthog = e),
26+
(e._i = []),
27+
(e.init = function(i, s, a) {
28+
function g(t, e) {
29+
var o = e.split('.');
30+
2 == o.length && ((t = t[o[0]]), (e = o[1])),
31+
(t[e] = function() {
32+
t.push([e].concat(Array.prototype.slice.call(arguments, 0)));
33+
});
34+
}
35+
((p = t.createElement('script')).type = 'text/javascript'),
36+
(p.crossOrigin = 'anonymous'),
37+
(p.async = true),
38+
(p.src = s.api_host + '/static/array.js'),
39+
(r = t.getElementsByTagName('script')[0]).parentNode.insertBefore(p, r);
40+
var u = e;
41+
void 0 !== a ? (u = e[a] = []) : (a = 'posthog');
42+
u.people = u.people || [];
43+
u.toString = function(t) {
44+
var e = 'posthog';
45+
return 'posthog' !== a && (e += '.' + a), t || (e += ' (stub)'), e;
46+
};
47+
u.people.toString = function() {
48+
return u.toString(1) + '.people (stub)';
49+
};
50+
o =
51+
'capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId'.split(
52+
' '
53+
);
54+
for (n = 0; n < o.length; n++) g(u, o[n]);
55+
e._i.push([i, s, a]);
56+
}),
57+
(e.__SV = 1));
58+
})(document, window.posthog || []);
59+
posthog.init('${projectApiKey}', { api_host: '${host}' });
3060
</script>
31-
\`\`\`
32-
33-
## Layout Setup
34-
35-
Create a Layout where you will use \`posthog.astro\`. Create a new file \`PostHogLayout.astro\` in your \`src/layouts\` folder:
61+
--------------------------------------------------
3662
37-
\`\`\`bash
38-
cd ./src/layouts
39-
# or 'cd ./src && mkdir layouts && cd ./layouts' if your layouts folder doesn't exist yet
40-
touch PostHogLayout.astro
41-
\`\`\`
63+
==============================
64+
FILE: src/layouts/PostHogLayout.astro
65+
LOCATION: Layouts folder (create if missing)
66+
==============================
67+
Changes:
68+
- Insert the new \`<PostHog />\` component in the \`<head>\`.
4269
43-
Add the following code to \`PostHogLayout.astro\`:
44-
45-
\`\`\`astro
70+
Example:
71+
--------------------------------------------------
4672
---
47-
import PostHog from '../components/posthog.astro'
73+
import PostHog from '../components/posthog.astro';
4874
---
4975
<html>
5076
<head>
@@ -54,36 +80,32 @@ import PostHog from '../components/posthog.astro'
5480
<slot />
5581
</body>
5682
</html>
57-
\`\`\`
58-
59-
## Update Your Pages
83+
--------------------------------------------------
6084
61-
Update your pages to use the new Layout. For example, in \`src/pages/index.astro\`:
85+
==============================
86+
FILE: any page you want analytics on, e.g. src/pages/index.astro
87+
LOCATION: Your page file
88+
==============================
89+
Changes:
90+
- Wrap content with the new layout.
6291
63-
\`\`\`astro
92+
Example:
93+
--------------------------------------------------
6494
---
6595
import PostHogLayout from '../layouts/PostHogLayout.astro';
6696
---
6797
<PostHogLayout>
68-
<!-- your existing page content -->
98+
<!-- existing page content -->
6999
<h1>Welcome to Astro</h1>
70100
</PostHogLayout>
71-
\`\`\`
72-
73-
## Environment Variables
74-
75-
Make sure to set your environment variables in your \`.env\` file:
76-
77-
\`\`\`
78-
PUBLIC_POSTHOG_KEY=your_project_api_key
79-
PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
80-
\`\`\`
81-
82-
## Next Steps
83-
84-
- Call \`posthog.identify()\` when a user signs into your app
85-
- Call \`posthog.capture()\` to capture custom events in your app
86-
- Use feature flags with \`posthog.isFeatureEnabled()\`
87-
- Set up session recordings and heatmaps
101+
--------------------------------------------------
102+
103+
==============================
104+
NEXT STEPS
105+
==============================
106+
- Call \`posthog.identify()\` after user sign-in.
107+
- Fire custom events with \`posthog.capture()\`.
108+
- Gate features via \`posthog.isFeatureEnabled()\`.
109+
- Enable session recordings and heatmaps under “Recordings” in PostHog.
88110
`;
89111
}

0 commit comments

Comments
 (0)