Skip to content

Commit

Permalink
Merge pull request #12 from axiomhq/avoid-logging-network-errors
Browse files Browse the repository at this point in the history
fix: avoid network errors if envVars are not set
  • Loading branch information
dasfmi authored Jun 21, 2022
2 parents 6518f11 + 497e05a commit 56db98c
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 10 deletions.
2 changes: 2 additions & 0 deletions __tests__/log.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/**
* @jest-environment jsdom
*/
// set axiom env vars before importing logger
process.env.AXIOM_INGEST_ENDPOINT = 'https://example.co/api/test';
import { log } from '../src/logger';

global.fetch = jest.fn() as jest.Mock;
Expand Down
27 changes: 27 additions & 0 deletions __tests__/noEnvVars.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @jest-environment jsdom
*/

// clear Axiom env vars
process.env.AXIOM_INGEST_ENDPOINT = '';
process.env.NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT = '';
import { NextWebVitalsMetric } from 'next/app';
import { log } from '../src/logger';
import { reportWebVitals } from '../src/webVitals';

global.fetch = jest.fn() as jest.Mock;
const mockedLog = jest.spyOn(global.console, 'log').mockImplementation();

test('sending logs on localhost should fallback to console', () => {
log.info('hello, world!');
jest.advanceTimersByTime(1000);
expect(fetch).toHaveBeenCalledTimes(0);
expect(mockedLog).toHaveBeenCalledTimes(1);
});

test('webVitals should not be sent when envVars are not set', () => {
const metric: NextWebVitalsMetric = { id: '1', startTime: 1234, value: 1, name: 'FCP', label: 'web-vital' };
reportWebVitals(metric);
jest.advanceTimersByTime(1000);
expect(fetch).toHaveBeenCalledTimes(0);
});
3 changes: 2 additions & 1 deletion __tests__/webvitals.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* @jest-environment jsdom
*/

import { jest } from '@jest/globals';
import { NextWebVitalsMetric } from 'next/app';
// set axiom env vars before importing webvitals
process.env.AXIOM_INGEST_ENDPOINT = 'https://example.co/api/test';
import { reportWebVitals } from '../src/webVitals';

global.fetch = jest.fn() as jest.Mock;
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "next-axiom",
"description": "Send WebVitals from your Next.js project to Axiom.",
"version": "0.7.0",
"version": "0.8.0",
"author": "Axiom, Inc.",
"license": "MIT",
"contributors": [
Expand Down Expand Up @@ -51,4 +51,4 @@
"dependencies": {
"cross-fetch": "^3.1.5"
}
}
}
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ export function withAxiom(nextConfig: NextConfig): NextConfig {
const webVitalsEndpoint = getIngestURL(EndpointType.webVitals);
const logsEndpoint = getIngestURL(EndpointType.logs);
if (!webVitalsEndpoint && !logsEndpoint) {
console.warn(
'axiom - Envvars not detected. If this is production please see https://github.com/axiomhq/next-axiom for help'
);
console.warn('axiom - Sending Web Vitals to /dev/null');
console.warn('axiom - Sending logs to console');
return rewrites || []; // nothing to do
}

Expand Down
12 changes: 9 additions & 3 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { proxyPath, isBrowser, EndpointType, getIngestURL } from './shared';
import { proxyPath, isBrowser, EndpointType, getIngestURL, isEnvVarsSet } from './shared';
import { throttle } from './shared';

const url = isBrowser ? `${proxyPath}/logs` : getIngestURL(EndpointType.logs);
const throttledSendLogs = throttle(sendLogs, 1000);
let logEvents: any[] = [];

function _log(level: string, message: string, args: any = {}) {
if (!url) {
console.warn('axiom: NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT is not defined');
if (!isEnvVarsSet) {
// if AXIOM ingesting url is not set, fallback to printing to console
// to avoid network errors in development environments
let fields = '';
if (Object.keys(args).length) {
fields = args;
}
console.log(`${level} - ${message}`, fields);
return;
}

Expand Down
1 change: 1 addition & 0 deletions src/shared.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export const proxyPath = '/_axiom';

export const isBrowser = typeof window !== 'undefined';
export const isEnvVarsSet = process.env.AXIOM_INGEST_ENDPOINT || process.env.NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT;

export enum EndpointType {
webVitals = 'web-vitals',
Expand Down
8 changes: 6 additions & 2 deletions src/webVitals.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { NextWebVitalsMetric } from 'next/app';
import { isBrowser, proxyPath } from './shared';
import { throttle } from './shared';
import { isBrowser, proxyPath, isEnvVarsSet, throttle } from './shared';

export { log } from './logger';

Expand All @@ -13,6 +12,11 @@ let collectedMetrics: WebVitalsMetric[] = [];

export function reportWebVitals(metric: NextWebVitalsMetric) {
collectedMetrics.push({ route: window.__NEXT_DATA__?.page, ...metric });
// if Axiom env vars are not set, do nothing,
// otherwise devs will get errors on dev environments
if (!isEnvVarsSet) {
return;
}
throttledSendMetrics();
}

Expand Down

1 comment on commit 56db98c

@vercel
Copy link

@vercel vercel bot commented on 56db98c Jun 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.