summaryrefslogtreecommitdiff
path: root/packages/integrations/web-vitals/src/index.ts
diff options
context:
space:
mode:
authorGravatar Chris Swithinbank <swithinbank@gmail.com> 2024-05-03 17:40:53 +0200
committerGravatar GitHub <noreply@github.com> 2024-05-03 17:40:53 +0200
commita37d76a42ac00697be3acd575f3f7163129ea75c (patch)
tree99c2c542e07eb49643cb682cecc31250dfd8bd9e /packages/integrations/web-vitals/src/index.ts
parentbefbda7fa3d712388789a5a9be1e0597834f86db (diff)
downloadastro-a37d76a42ac00697be3acd575f3f7163129ea75c.tar.gz
astro-a37d76a42ac00697be3acd575f3f7163129ea75c.tar.zst
astro-a37d76a42ac00697be3acd575f3f7163129ea75c.zip
Add web-vitals integration (#10883)
Diffstat (limited to 'packages/integrations/web-vitals/src/index.ts')
-rw-r--r--packages/integrations/web-vitals/src/index.ts42
1 files changed, 42 insertions, 0 deletions
diff --git a/packages/integrations/web-vitals/src/index.ts b/packages/integrations/web-vitals/src/index.ts
new file mode 100644
index 000000000..f8a5ad433
--- /dev/null
+++ b/packages/integrations/web-vitals/src/index.ts
@@ -0,0 +1,42 @@
+import { defineDbIntegration } from '@astrojs/db/utils';
+import { AstroError } from 'astro/errors';
+import { WEB_VITALS_ENDPOINT_PATH } from './constants.js';
+
+export default function webVitals() {
+ return defineDbIntegration({
+ name: '@astrojs/web-vitals',
+ hooks: {
+ 'astro:db:setup'({ extendDb }) {
+ extendDb({ configEntrypoint: '@astrojs/web-vitals/db-config' });
+ },
+
+ 'astro:config:setup'({ addMiddleware, config, injectRoute, injectScript }) {
+ if (!config.integrations.find(({ name }) => name === 'astro:db')) {
+ throw new AstroError(
+ 'Astro DB integration not found.',
+ 'Run `npx astro add db` to install `@astrojs/db` and add it to your Astro config.'
+ );
+ }
+
+ if (config.output !== 'hybrid' && config.output !== 'server') {
+ throw new AstroError(
+ 'No SSR adapter found.',
+ '`@astrojs/web-vitals` requires your site to be built with `hybrid` or `server` output.\n' +
+ 'Please add an SSR adapter: https://docs.astro.build/en/guides/server-side-rendering/'
+ );
+ }
+
+ // Middleware that adds a `<meta>` tag to each page.
+ addMiddleware({ entrypoint: '@astrojs/web-vitals/middleware', order: 'post' });
+ // Endpoint that collects metrics and inserts them in Astro DB.
+ injectRoute({
+ entrypoint: '@astrojs/web-vitals/endpoint',
+ pattern: WEB_VITALS_ENDPOINT_PATH,
+ prerender: false,
+ });
+ // Client-side performance measurement script.
+ injectScript('page', `import '@astrojs/web-vitals/client-script';`);
+ },
+ },
+ });
+}