Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add vercel analytics support #6148

Merged
merged 18 commits into from
Feb 8, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
25 changes: 25 additions & 0 deletions packages/integrations/vercel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ To configure this adapter, pass an object to the `vercel()` function call in `as

Use this property to force files to be bundled with your function. This is helpful when you notice missing files.

__`astro.config.mjs`__
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved

```js
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
Expand All @@ -117,6 +119,8 @@ export default defineConfig({

Use this property to exclude any files from the bundling process that would otherwise be included.

__`astro.config.mjs`__

```js
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
Expand All @@ -129,6 +133,27 @@ export default defineConfig({
});
```

### analytics

> **Type:** `boolean`
> **Available for:** Serverless

Use this property to enable Vercel Analytics (including Web Vitals and Audiences).

__`astro.config.mjs`__

jsun969 marked this conversation as resolved.
Show resolved Hide resolved
```js
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
output: 'server',
adapter: vercel({
analytics: true
})
});
```

### Vercel Middleware

You can use Vercel middleware to intercept a request and redirect before sending a response. Vercel middleware can run for Edge, SSR, and Static deployments. You don't need to install `@vercel/edge` to write middleware, but you do need to install it to use features such as geolocation. For more information see [Vercel’s middleware documentation](https://vercel.com/docs/concepts/functions/edge-middleware).
Expand Down
63 changes: 63 additions & 0 deletions packages/integrations/vercel/analytics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { inject } from '@vercel/analytics';
import { getCLS, getFCP, getFID, getLCP, getTTFB } from 'web-vitals';

const vitalsUrl = 'https://vitals.vercel-analytics.com/v1/vitals';

const getConnectionSpeed = () => {
return 'connection' in navigator &&
navigator['connection'] &&
'effectiveType' in navigator['connection']
? navigator['connection']['effectiveType']
: '';
};

const sendToAnalytics = (metric, options) => {
const body = {
dsn: options.analyticsId,
id: metric.id,
page: options.path,
href: location.href,
event_name: metric.name,
value: metric.value.toString(),
speed: getConnectionSpeed(),
};

if (options.debug) {
console.log('[Analytics]', metric.name, JSON.stringify(body, null, 2));
}

const blob = new Blob([new URLSearchParams(body).toString()], {
type: 'application/x-www-form-urlencoded',
});
if (navigator.sendBeacon) {
navigator.sendBeacon(vitalsUrl, blob);
} else
fetch(vitalsUrl, {
body: blob,
method: 'POST',
credentials: 'omit',
keepalive: true,
});
};

function webVitals() {
const options = {
path: window.location.pathname,
analyticsId: import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID,
};
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));
} catch (err) {
console.error('[Analytics]', err);
}
}

const mode = import.meta.env.MODE;
inject({ mode });
if (mode === 'production') {
webVitals();
}
6 changes: 4 additions & 2 deletions packages/integrations/vercel/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@astrojs/vercel",
"description": "Deploy your site to Vercel",
"version": "3.0.1",
"version": "3.1.0",
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved
"type": "module",
"author": "withastro",
"license": "MIT",
Expand Down Expand Up @@ -45,9 +45,11 @@
},
"dependencies": {
"@astrojs/webapi": "^2.0.0",
"@vercel/analytics": "^0.1.8",
"@vercel/nft": "^0.22.1",
"fast-glob": "^3.2.11",
"set-cookie-parser": "^2.5.1"
"set-cookie-parser": "^2.5.1",
"web-vitals": "^3.1.1"
},
"peerDependencies": {
"astro": "workspace:^2.0.6"
Expand Down
11 changes: 10 additions & 1 deletion packages/integrations/vercel/src/serverless/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AstroAdapter, AstroConfig, AstroIntegration } from 'astro';

import glob from 'fast-glob';
import { readFileSync } from 'node:fs';
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved
JuanM04 marked this conversation as resolved.
Show resolved Hide resolved
import { pathToFileURL } from 'url';
import { getVercelOutput, removeDir, writeJson } from '../lib/fs.js';
import { copyDependenciesToFunction } from '../lib/nft.js';
Expand All @@ -19,11 +20,13 @@ function getAdapter(): AstroAdapter {
export interface VercelServerlessConfig {
includeFiles?: string[];
excludeFiles?: string[];
analytics?: boolean;
}

export default function vercelServerless({
includeFiles,
excludeFiles,
analytics,
}: VercelServerlessConfig = {}): AstroIntegration {
let _config: AstroConfig;
let buildTempFolder: URL;
Expand All @@ -33,7 +36,13 @@ export default function vercelServerless({
return {
name: PACKAGE_NAME,
hooks: {
'astro:config:setup': ({ config, updateConfig }) => {
'astro:config:setup': ({ config, updateConfig, injectScript }) => {
if (analytics) {
injectScript(
'page',
readFileSync(new URL('../../analytics.js', import.meta.url), { encoding: 'utf-8' })
);
}
const outDir = getVercelOutput(config.root);
updateConfig({
outDir,
Expand Down
17 changes: 17 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.