Individually enable Speed Insights and Web Analytics

This commit is contained in:
Chris 2023-08-10 15:13:35 +02:00
parent 1e3c9f515b
commit 4a7bad48f0
28 changed files with 418 additions and 53 deletions

View file

@ -0,0 +1,7 @@
---
'@astrojs/vercel': major
---
Enable Vercel Speed Insights and Vercel Web Analytics individually.
Allow configuration of Web Analytics with all available configuration options.
Bumps @vercel/analytics package to the latest version.

View file

@ -87,13 +87,14 @@ vercel deploy --prebuilt
To configure this adapter, pass an object to the `vercel()` function call in `astro.config.mjs`:
### analytics
### Web Analytics
**Type:** `boolean`<br>
**Type:** `VercelWebAnalyticsConfig`<br>
**Available for:** Serverless, Edge, Static<br>
**Added in:** `@astrojs/vercel@3.1.0`
**Added in:** `@astrojs/vercel@3.8.0`
You can enable [Vercel Analytics](https://vercel.com/analytics) (including Web Vitals and Audiences) by setting `analytics: true`. This will inject Vercels tracking scripts into all your pages.
You can enable [Vercel Web Analytics](https://vercel.com/docs/concepts/analytics) by setting `webAnalytics: { enabled: true }`. This will inject Vercels tracking scripts into all of your pages.
Alternatively, you can pass all [available configuration options](https://vercel.com/docs/concepts/analytics/package) via the `config` property inside `webAnalytics`.
```js
// astro.config.mjs
@ -103,7 +104,40 @@ import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
output: 'server',
adapter: vercel({
analytics: true,
webAnalytics: {
enabled: true,
config: {
beforeSend: (event) => {
// Ignore all events that have a `/private` inside the URL
if (event.url.includes('/private')) {
return null;
}
return event;
}
}
}
}),
});
```
### Speed Insights
You can enable [Vercel Speed Insights](https://vercel.com/docs/concepts/speed-insights) by setting `speedInsights: { enabled: true }`. This will collect and send Web Vital data to Vercel.
**Type:** `VercelSpeedInsightsConfig`<br>
**Available for:** Serverless, Edge, Static<br>
**Added in:** `@astrojs/vercel@3.8.0`
```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
output: 'server',
adapter: vercel({
speedInsights: {
enabled: true,
}
}),
});
```

View file

@ -22,7 +22,7 @@
"./serverless": "./dist/serverless/adapter.js",
"./serverless/entrypoint": "./dist/serverless/entrypoint.js",
"./static": "./dist/static/adapter.js",
"./analytics": "./dist/analytics.js",
"./speed-insights": "./dist/speed-insights.js",
"./build-image-service": "./dist/image/build-service.js",
"./dev-image-service": "./dist/image/dev-service.js",
"./package.json": "./package.json"
@ -53,7 +53,7 @@
"dependencies": {
"@astrojs/internal-helpers": "^0.1.2",
"@astrojs/webapi": "^2.2.0",
"@vercel/analytics": "^0.1.11",
"@vercel/analytics": "~1.0.0",
"@vercel/nft": "^0.22.6",
"esbuild": "^0.17.19",
"fast-glob": "^3.2.12",

View file

@ -10,7 +10,6 @@ import {
throwIfAssetsNotEnabled,
type VercelImageConfig,
} from '../image/shared.js';
import { exposeEnv } from '../lib/env.js';
import {
copyFilesToFunction,
getFilesFromFolder,
@ -19,6 +18,14 @@ import {
writeJson,
} from '../lib/fs.js';
import { getRedirects } from '../lib/redirects.js';
import {
getInjectableWebAnalyticsContent,
type VercelWebAnalyticsConfig,
} from '../lib/web-analytics.js';
import {
getSpeedInsightsViteConfig,
type VercelSpeedInsightsConfig,
} from '../lib/speed-insights.js';
const PACKAGE_NAME = '@astrojs/vercel/edge';
@ -31,15 +38,17 @@ function getAdapter(): AstroAdapter {
}
export interface VercelEdgeConfig {
webAnalytics?: VercelWebAnalyticsConfig;
speedInsights?: VercelSpeedInsightsConfig;
includeFiles?: string[];
analytics?: boolean;
imageService?: boolean;
imagesConfig?: VercelImageConfig;
}
export default function vercelEdge({
webAnalytics,
speedInsights,
includeFiles = [],
analytics,
imageService,
imagesConfig,
}: VercelEdgeConfig = {}): AstroIntegration {
@ -52,11 +61,19 @@ export default function vercelEdge({
name: PACKAGE_NAME,
hooks: {
'astro:config:setup': ({ command, config, updateConfig, injectScript }) => {
if (command === 'build' && analytics) {
injectScript('page', 'import "@astrojs/vercel/analytics"');
if (webAnalytics?.enabled) {
injectScript(
'page',
getInjectableWebAnalyticsContent({
...webAnalytics.config,
mode: command === 'dev' ? 'development' : 'production',
})
);
}
if (command === 'build' && speedInsights?.enabled) {
injectScript('page', 'import "@astrojs/vercel/speed-insights"');
}
const outDir = getVercelOutput(config.root);
const viteDefine = exposeEnv(['VERCEL_ANALYTICS_ID']);
updateConfig({
outDir,
build: {
@ -65,7 +82,7 @@ export default function vercelEdge({
server: new URL('./dist/', config.root),
},
vite: {
define: viteDefine,
...getSpeedInsightsViteConfig(speedInsights?.enabled),
ssr: {
external: ['@vercel/nft'],
},

View file

@ -0,0 +1,15 @@
import { exposeEnv } from './env';
export type VercelSpeedInsightsConfig = {
enabled: boolean;
};
export function getSpeedInsightsViteConfig(enabled?: boolean) {
if (enabled) {
return {
define: exposeEnv(['VERCEL_ANALYTICS_ID']),
};
}
return {};
}

View file

@ -0,0 +1,15 @@
import type { AnalyticsProps } from '@vercel/analytics';
export type VercelWebAnalyticsConfig = {
enabled: boolean;
config?: AnalyticsProps;
};
export function getInjectableWebAnalyticsContent(config?: AnalyticsProps) {
return `import { inject } from '@vercel/analytics';
inject({
mode: ${config?.mode},
beforeSend: ${config?.beforeSend},
debug: ${config?.debug}
});`;
}

View file

@ -9,11 +9,18 @@ import {
throwIfAssetsNotEnabled,
type VercelImageConfig,
} from '../image/shared.js';
import { exposeEnv } from '../lib/env.js';
import { getVercelOutput, removeDir, writeJson } from '../lib/fs.js';
import { copyDependenciesToFunction } from '../lib/nft.js';
import { getRedirects } from '../lib/redirects.js';
import { generateEdgeMiddleware } from './middleware.js';
import {
getInjectableWebAnalyticsContent,
type VercelWebAnalyticsConfig,
} from '../lib/web-analytics.js';
import {
getSpeedInsightsViteConfig,
type VercelSpeedInsightsConfig,
} from '../lib/speed-insights.js';
const PACKAGE_NAME = '@astrojs/vercel/serverless';
export const ASTRO_LOCALS_HEADER = 'x-astro-locals';
@ -38,17 +45,19 @@ function getAdapter(): AstroAdapter {
}
export interface VercelServerlessConfig {
webAnalytics?: VercelWebAnalyticsConfig;
speedInsights?: VercelSpeedInsightsConfig;
includeFiles?: string[];
excludeFiles?: string[];
analytics?: boolean;
imageService?: boolean;
imagesConfig?: VercelImageConfig;
}
export default function vercelServerless({
webAnalytics,
speedInsights,
includeFiles,
excludeFiles,
analytics,
imageService,
imagesConfig,
}: VercelServerlessConfig = {}): AstroIntegration {
@ -89,11 +98,19 @@ export default function vercelServerless({
name: PACKAGE_NAME,
hooks: {
'astro:config:setup': ({ command, config, updateConfig, injectScript }) => {
if (command === 'build' && analytics) {
injectScript('page', 'import "@astrojs/vercel/analytics"');
if (webAnalytics?.enabled) {
injectScript(
'page',
getInjectableWebAnalyticsContent({
...webAnalytics.config,
mode: command === 'dev' ? 'development' : 'production',
})
);
}
if (command === 'build' && speedInsights?.enabled) {
injectScript('page', 'import "@astrojs/vercel/speed-insights"');
}
const outDir = getVercelOutput(config.root);
const viteDefine = exposeEnv(['VERCEL_ANALYTICS_ID']);
updateConfig({
outDir,
build: {
@ -102,7 +119,7 @@ export default function vercelServerless({
server: new URL('./dist/', config.root),
},
vite: {
define: viteDefine,
...getSpeedInsightsViteConfig(speedInsights?.enabled),
ssr: {
external: ['@vercel/nft'],
},

View file

@ -1,8 +1,7 @@
import { inject } from '@vercel/analytics';
import type { Metric } from 'web-vitals';
import { getCLS, getFCP, getFID, getLCP, getTTFB } from 'web-vitals';
import { onCLS, onFCP, onFID, onLCP, onTTFB } from 'web-vitals';
const vitalsUrl = 'https://vitals.vercel-analytics.com/v1/vitals';
const SPEED_INSIGHTS_INTAKE = 'https://vitals.vercel-analytics.com/v1/vitals';
type Options = { path: string; analyticsId: string };
@ -14,7 +13,7 @@ const getConnectionSpeed = () => {
: '';
};
const sendToAnalytics = (metric: Metric, options: Options) => {
const sendToSpeedInsights = (metric: Metric, options: Options) => {
const body = {
dsn: options.analyticsId,
id: metric.id,
@ -28,9 +27,9 @@ const sendToAnalytics = (metric: Metric, options: Options) => {
type: 'application/x-www-form-urlencoded',
});
if (navigator.sendBeacon) {
navigator.sendBeacon(vitalsUrl, blob);
navigator.sendBeacon(SPEED_INSIGHTS_INTAKE, blob);
} else
fetch(vitalsUrl, {
fetch(SPEED_INSIGHTS_INTAKE, {
body: blob,
method: 'POST',
credentials: 'omit',
@ -38,27 +37,26 @@ const sendToAnalytics = (metric: Metric, options: Options) => {
});
};
function webVitals() {
function collectWebVitals() {
const analyticsId = (import.meta as any).env.PUBLIC_VERCEL_ANALYTICS_ID;
if (!analyticsId) {
console.error('[Analytics] VERCEL_ANALYTICS_ID not found');
console.error('[Speed Insights] VERCEL_ANALYTICS_ID not found');
return;
}
const options: Options = { path: window.location.pathname, analyticsId };
try {
getFID((metric) => sendToAnalytics(metric, options));
getTTFB((metric) => sendToAnalytics(metric, options));
getLCP((metric) => sendToAnalytics(metric, options));
getCLS((metric) => sendToAnalytics(metric, options));
getFCP((metric) => sendToAnalytics(metric, options));
onFID((metric) => sendToSpeedInsights(metric, options));
onTTFB((metric) => sendToSpeedInsights(metric, options));
onLCP((metric) => sendToSpeedInsights(metric, options));
onCLS((metric) => sendToSpeedInsights(metric, options));
onFCP((metric) => sendToSpeedInsights(metric, options));
} catch (err) {
console.error('[Analytics]', err);
console.error('[Speed Insights]', err);
}
}
const mode = (import.meta as any).env.MODE as 'development' | 'production';
inject({ mode });
if (mode === 'production') {
webVitals();
collectWebVitals();
}

View file

@ -6,10 +6,17 @@ import {
throwIfAssetsNotEnabled,
type VercelImageConfig,
} from '../image/shared.js';
import { exposeEnv } from '../lib/env.js';
import { emptyDir, getVercelOutput, writeJson } from '../lib/fs.js';
import { isServerLikeOutput } from '../lib/prerender.js';
import { getRedirects } from '../lib/redirects.js';
import {
getSpeedInsightsViteConfig,
type VercelSpeedInsightsConfig,
} from '../lib/speed-insights.js';
import {
getInjectableWebAnalyticsContent,
type VercelWebAnalyticsConfig,
} from '../lib/web-analytics.js';
const PACKAGE_NAME = '@astrojs/vercel/static';
@ -18,13 +25,15 @@ function getAdapter(): AstroAdapter {
}
export interface VercelStaticConfig {
analytics?: boolean;
webAnalytics?: VercelWebAnalyticsConfig;
speedInsights?: VercelSpeedInsightsConfig;
imageService?: boolean;
imagesConfig?: VercelImageConfig;
}
export default function vercelStatic({
analytics,
webAnalytics,
speedInsights,
imageService,
imagesConfig,
}: VercelStaticConfig = {}): AstroIntegration {
@ -34,11 +43,19 @@ export default function vercelStatic({
name: '@astrojs/vercel',
hooks: {
'astro:config:setup': ({ command, config, injectScript, updateConfig }) => {
if (command === 'build' && analytics) {
injectScript('page', 'import "@astrojs/vercel/analytics"');
if (webAnalytics?.enabled) {
injectScript(
'page',
getInjectableWebAnalyticsContent({
...webAnalytics.config,
mode: command === 'dev' ? 'development' : 'production',
})
);
}
if (command === 'build' && speedInsights?.enabled) {
injectScript('page', 'import "@astrojs/vercel/speed-insights"');
}
const outDir = new URL('./static/', getVercelOutput(config.root));
const viteDefine = exposeEnv(['VERCEL_ANALYTICS_ID']);
updateConfig({
outDir,
build: {
@ -46,7 +63,7 @@ export default function vercelStatic({
redirects: false,
},
vite: {
define: viteDefine,
...getSpeedInsightsViteConfig(speedInsights?.enabled),
},
...getImageConfig(imageService, imagesConfig, command),
});

View file

@ -0,0 +1,10 @@
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
adapter: vercel({
speedInsights: {
enabled: true
}
})
});

View file

@ -0,0 +1,9 @@
{
"name": "@test/astro-vercel-with-speed-insights-enabled-output-as-server",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/vercel": "workspace:*",
"astro": "workspace:*"
}
}

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
</body>
</html>

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>Two</title>
</head>
<body>
<h1>Two</h1>
</body>
</html>

View file

@ -0,0 +1,10 @@
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/static';
export default defineConfig({
adapter: vercel({
speedInsights: {
enabled: true
}
})
});

View file

@ -0,0 +1,9 @@
{
"name": "@test/astro-vercel-with-speed-insights-enabled-output-as-static",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/vercel": "workspace:*",
"astro": "workspace:*"
}
}

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
</body>
</html>

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>Two</title>
</head>
<body>
<h1>Two</h1>
</body>
</html>

View file

@ -0,0 +1,10 @@
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
adapter: vercel({
webAnalytics: {
enabled: true
}
})
});

View file

@ -0,0 +1,9 @@
{
"name": "@test/astro-vercel-with-web-analytics-enabled-output-as-server",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/vercel": "workspace:*",
"astro": "workspace:*"
}
}

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
</body>
</html>

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>Two</title>
</head>
<body>
<h1>Two</h1>
</body>
</html>

View file

@ -0,0 +1,10 @@
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/static';
export default defineConfig({
adapter: vercel({
webAnalytics: {
enabled: true
}
})
});

View file

@ -0,0 +1,9 @@
{
"name": "@test/astro-vercel-with-web-analytics-enabled-output-as-static",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/vercel": "workspace:*",
"astro": "workspace:*"
}
}

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
</body>
</html>

View file

@ -0,0 +1,8 @@
<html>
<head>
<title>Two</title>
</head>
<body>
<h1>Two</h1>
</body>
</html>

View file

@ -0,0 +1,46 @@
import { loadFixture } from './test-utils.js';
import { expect } from 'chai';
describe.only('Vercel Speed Insights', () => {
describe('output: server', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/with-speed-insights-enabled/output-as-server/',
output: 'server',
});
await fixture.build();
});
it('ensures that Vercel Speed Insights is present in the bundle', async () => {
const [page] = await fixture.readdir('../.vercel/output/static/_astro');
const bundle = await fixture.readFile(`../.vercel/output/static/_astro/${page}`);
expect(bundle).to.contain('https://vitals.vercel-analytics.com/v1/vitals');
});
});
describe('output: static', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/with-speed-insights-enabled/output-as-static/',
output: 'static',
});
await fixture.build();
});
it('ensures that Vercel Speed Insights is present in the bundle', async () => {
const [page] = await fixture.readdir('../.vercel/output/static/_astro');
const bundle = await fixture.readFile(`../.vercel/output/static/_astro/${page}`);
expect(bundle).to.contain('https://vitals.vercel-analytics.com/v1/vitals');
});
});
});

View file

@ -0,0 +1,46 @@
import { loadFixture } from './test-utils.js';
import { expect } from 'chai';
describe.only('Vercel Web Analytics', () => {
describe('output: server', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/with-web-analytics-enabled/output-as-server/',
output: 'server',
});
await fixture.build();
});
it('ensures that Vercel Web Analytics is present in the bundle', async () => {
const [page] = await fixture.readdir('../.vercel/output/static/_astro');
const bundle = await fixture.readFile(`../.vercel/output/static/_astro/${page}`);
expect(bundle).to.contain('/_vercel/insights');
});
});
describe('output: static', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;
before(async () => {
fixture = await loadFixture({
root: './fixtures/with-web-analytics-enabled/output-as-static/',
output: 'static',
});
await fixture.build();
});
it('ensures that Vercel Web Analytics is present in the bundle', async () => {
const [page] = await fixture.readdir('../.vercel/output/static/_astro');
const bundle = await fixture.readFile(`../.vercel/output/static/_astro/${page}`);
expect(bundle).to.contain('/_vercel/insights');
});
});
});

31
pnpm-lock.yaml generated
View file

@ -4953,8 +4953,8 @@ importers:
specifier: ^2.2.0
version: link:../../webapi
'@vercel/analytics':
specifier: ^0.1.11
version: 0.1.11
specifier: ~1.0.0
version: 1.0.2
'@vercel/nft':
specifier: ^0.22.6
version: 0.22.6
@ -5071,6 +5071,24 @@ importers:
specifier: workspace:*
version: link:../../../../../astro
packages/integrations/vercel/test/fixtures/with-speed-insights-enabled/output-as-server:
dependencies:
'@astrojs/vercel':
specifier: workspace:*
version: link:../../../..
astro:
specifier: workspace:*
version: link:../../../../../../astro
packages/integrations/vercel/test/fixtures/with-speed-insights-enabled/output-as-static:
dependencies:
'@astrojs/vercel':
specifier: workspace:*
version: link:../../../..
astro:
specifier: workspace:*
version: link:../../../../../../astro
packages/integrations/vercel/test/hosted/hosted-astro-project:
dependencies:
'@astrojs/vercel':
@ -9304,13 +9322,8 @@ packages:
resolution: {integrity: sha512-TSVh8CpnwNAsPC5wXcIyh92Bv1gq6E9cNDeeLu7Z4h8V4/qWtXJp7y42qljRkqcpmsve1iozwv1wr+3BNdILCg==}
dev: true
/@vercel/analytics@0.1.11:
resolution: {integrity: sha512-mj5CPR02y0BRs1tN3oZcBNAX9a8NxsIUl9vElDPcqxnMfP0RbRc9fI9Ud7+QDg/1Izvt5uMumsr+6YsmVHcyuw==}
peerDependencies:
react: ^16.8||^17||^18
peerDependenciesMeta:
react:
optional: true
/@vercel/analytics@1.0.2:
resolution: {integrity: sha512-BZFxVrv24VbNNl5xMxqUojQIegEeXMI6rX3rg1uVLYUEXsuKNBSAEQf4BWEcjQDp/8aYJOj6m8V4PUA3x/cxgg==}
dev: false
/@vercel/edge@0.3.4: