Skip to content

Commit

Permalink
Improved server side events (#92)
Browse files Browse the repository at this point in the history
* Add more error logs

* rename to withSessionContext

* Throw error when no headers are found

* update version

* Update packages/web/src/server/index.ts

Co-authored-by: Chris <[email protected]>

* Update packages/web/src/server/index.ts

Co-authored-by: Chris <[email protected]>

---------

Co-authored-by: Chris <[email protected]>
  • Loading branch information
tobiaslins and chriswdmr authored Aug 8, 2023
1 parent 1825c2e commit c8b7ea8
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 12 deletions.
5 changes: 2 additions & 3 deletions apps/nextjs/app/api/edge/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { track } from '@vercel/analytics/server';
import { withRequestContext } from '@vercel/analytics/server';
import { withSessionContext, track } from '@vercel/analytics/server';

export const runtime = 'edge';

Expand All @@ -12,4 +11,4 @@ async function handler() {
return new Response('OK');
}

export const GET = withRequestContext(handler);
export const GET = withSessionContext(handler);
5 changes: 2 additions & 3 deletions apps/nextjs/app/api/serverless/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { withRequestContext, track } from '@vercel/analytics/server';
import { NextRequest } from 'next/server';
import { withSessionContext, track } from '@vercel/analytics/server';

async function handler() {
await track('Serverless Event', {
Expand All @@ -9,4 +8,4 @@ async function handler() {
return new Response('OK');
}

export const GET = withRequestContext(handler);
export const GET = withSessionContext(handler);
2 changes: 1 addition & 1 deletion packages/web/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@vercel/analytics",
"version": "1.1.0-beta.2",
"version": "1.1.0-beta.3",
"description": "Gain real-time traffic insights with Vercel Web Analytics",
"keywords": [
"analytics",
Expand Down
21 changes: 17 additions & 4 deletions packages/web/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import type { AllowedPropertyValues } from '../types';
import type { StorageData } from './request-context';

export { withRequestContext } from './request-context';
export { withSessionContext } from './request-context';

const ENDPOINT = process.env.VERCEL_URL || process.env.VERCEL_ANALYTICS_URL;
const ENV = process.env.NODE_ENV;
Expand Down Expand Up @@ -80,10 +80,22 @@ export async function track(

const hasHeaders = Boolean(headers);

// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
if (!hasHeaders) {
throw new Error(
'No session context found. Wrap your API route handler with `withSessionContext` or pass `request` or `headers` to the `track` function.',
);
}

if (!ENDPOINT) {
throw new Error(
'`process.env.VERCEL_URL` is not defined in your environment variables.',
);
}

const promise = fetch(`https://${ENDPOINT}/_vercel/insights/event`, {
headers: {
'content-type': 'application/json',
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- The throwing is temporary until we add support for non Vercel hosted environments
...(hasHeaders
? {
'user-agent': tmp['user-agent'] as string,
Expand All @@ -97,9 +109,10 @@ export async function track(
body: JSON.stringify(body),
method: 'POST',
}).catch((err: unknown) => {
if (!(err instanceof Error)) return;
if ('response' in err) {
if (err instanceof Error && 'response' in err) {
console.error(err.response);
} else {
console.error(err);
}
});

Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/server/request-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export interface StorageData {
request: Request;
}

export const withRequestContext =
export const withSessionContext =
<T extends Request>(next: (req: any, res: any) => Promise<Response | void>) =>
async (request: T, secondParam: Response): Promise<Response | void> => {
const asyncLocalStorage = new AsyncLocalStorage<StorageData>();
Expand Down

0 comments on commit c8b7ea8

Please sign in to comment.