Gathering detailed insights and metrics for next-axiom
Gathering detailed insights and metrics for next-axiom
Gathering detailed insights and metrics for next-axiom
Gathering detailed insights and metrics for next-axiom
npm install next-axiom
Typescript
Module System
Min. Node Version
Node Version
NPM Version
62.4
Supply Chain
84.1
Quality
91.8
Maintenance
100
Vulnerability
92.3
License
TypeScript (99.79%)
Nix (0.21%)
Total Downloads
2,756,165
Last Day
3,789
Last Week
17,974
Last Month
114,242
Last Year
1,474,752
376 Stars
587 Commits
29 Forks
4 Watching
36 Branches
24 Contributors
Minified
Minified + Gzipped
Latest Version
1.9.1
Package Id
next-axiom@1.9.1
Unpacked Size
736.72 kB
Size
197.56 kB
File Count
111
NPM Version
10.8.2
Node Version
20.18.1
Publised On
18 Dec 2024
Cumulative downloads
Total Downloads
Last day
-14.1%
3,789
Compared to previous day
Last week
-35.3%
17,974
Compared to previous week
Last month
-12.8%
114,242
Compared to previous month
Last year
42.4%
1,474,752
Compared to previous year
2
Axiom unlocks observability at any scale.
For more information, check out the official documentation.
This library allows you to send Web Vitals as well as structured logs from your Next.js application to Axiom.
Using the Pages Router? Use version
0.*
which continues to receive security patches. Here's the README for0.x
.
npm install --save next-axiom
to install the latest version of next-axiom.NEXT_PUBLIC_AXIOM_DATASET
is the name of the Axiom dataset where you want to send data.NEXT_PUBLIC_AXIOM_TOKEN
is the Axiom API token you have generated.next.config.ts
file, wrap your Next.js configuration in withAxiom
:1const { withAxiom } = require('next-axiom'); 2 3module.exports = withAxiom({ 4 // Your existing configuration. 5});
To capture traffic requests, create a middleware.ts
file in the root folder of your Next.js app:
1import { Logger } from 'next-axiom' 2import { NextResponse } from 'next/server' 3import type { NextFetchEvent, NextRequest } from 'next/server' 4 5export async function middleware(request: NextRequest, event: NextFetchEvent) { 6 const logger = new Logger({ source: 'middleware' }); // traffic, request 7 logger.middleware(request) 8 9 event.waitUntil(logger.flush()) 10 return NextResponse.next() 11 12// For more information, see Matching Paths below 13export const config = { 14}
logger.middleware
accepts a configuration object as the second argument. This object can contain the following properties:
logRequestDetails
: Accepts a boolean or an array of keys. If you pass true
, it will add all the request details to the log (method, URL, headers, etc.). If you pass an array of strings, it will only add the specified keys. See Request and NextRequest for documentation on the available keys. If logRequestDetails
is enabled the function will return a Promise that needs to be awaited.1export async function middleware(request: NextRequest, event: NextFetchEvent) { 2 const logger = new Logger({ source: "middleware" }); 3 await logger.middleware(request, { logRequestDetails: ["body", "nextUrl"] }); 4 5 event.waitUntil(logger.flush()); 6 return NextResponse.next(); 7}
To send Web Vitals to Axiom, add the AxiomWebVitals
component from next-axiom to the app/layout.tsx
file:
1import { AxiomWebVitals } from 'next-axiom'; 2 3export default function RootLayout() { 4 return ( 5 <html> 6 ... 7 <AxiomWebVitals /> 8 <div>...</div> 9 </html> 10 ); 11}
Web Vitals are only sent from production deployments.
Send logs to Axiom from different parts of your app. Each log function call takes a message and an optional fields
object.
1log.debug('Login attempt', { user: 'j_doe', status: 'success' }); // Results in {"message": "Login attempt", "fields": {"user": "j_doe", "status": "success"}} 2log.info('Payment completed', { userID: '123', amount: '25USD' }); 3log.warn('API rate limit exceeded', { endpoint: '/users/1', rateLimitRemaining: 0 }); 4log.error('System Error', { code: '500', message: 'Internal server error' });
Wrap your route handlers in withAxiom
to add a logger to your request and log exceptions automatically:
1import { withAxiom, AxiomRequest } from 'next-axiom'; 2 3export const GET = withAxiom((req: AxiomRequest) => { 4 req.log.info('Login function called'); 5 6 // You can create intermediate loggers 7 const log = req.log.with({ scope: 'user' }); 8 log.info('User logged in', { userId: 42 }); 9 10 return NextResponse.json({ hello: 'world' }); 11});
Route handlers accept a configuration object as the second argument. This object can contain the following properties:
logRequestDetails
: Accepts a boolean or an array of keys. If you pass true
, it will add all the request details to the log (method, URL, headers, etc.). If you pass an array of strings, it will only add the specified keys. See Request and NextRequest for documentation on the available keys.
NotFoundLogLevel
: Override the log level for NOT_FOUND errors. Defaults to warn
.
RedirectLogLevel
: Override the log level for NEXT_REDIRECT errors. Defaults to info
.
Config example:
1export const GET = withAxiom( 2 async () => { 3 return new Response("Hello World!"); 4 }, 5 { 6 logRequestDetails: ['body', 'nextUrl'], // { logRequestDetails: true } is also valid 7 NotFoundLogLevel: 'error', 8 RedirectLogLevel: 'debug', 9 } 10);
To send logs from client components, add useLogger
from next-axiom to your component:
1'use client'; 2import { useLogger } from 'next-axiom'; 3 4export default function ClientComponent() { 5 const log = useLogger(); 6 log.debug('User logged in', { userId: 42 }); 7 return <h1>Logged in</h1>; 8}
To send logs from server components, add Logger
from next-axiom to your component, and call flush before returning:
1import { Logger } from 'next-axiom'; 2 3export default async function ServerComponent() { 4 const log = new Logger(); 5 log.info('User logged in', { userId: 42 }); 6 7 // ... 8 9 await log.flush(); 10 return <h1>Logged in</h1>; 11}
The log level defines the lowest level of logs sent to Axiom. Choose one of the following levels (from lowest to highest):
debug
is the default setting. It means that you send all logs to Axiom.info
warn
error
means that you only send the highest-level logs to Axiom.off
means that you don't send any logs to Axiom.For example, to send all logs except for debug logs to Axiom:
1export NEXT_PUBLIC_AXIOM_LOG_LEVEL=info
To capture routing errors, use the error handling mechanism of Next.js:
app
folder.error.tsx
file.useLogger
from next-axiom to send the error to Axiom. For example:1"use client";
2
3import { useLogger, LogLevel } from "next-axiom";
4import { usePathname } from "next/navigation";
5
6export default function ErrorPage({
7 error,
8}: {
9 error: Error & { digest?: string };
10}) {
11 const pathname = usePathname()
12 const log = useLogger({ source: "error.tsx" });
13 let status = error.message == 'Invalid URL' ? 404 : 500;
14
15 log.logHttpRequest(
16 LogLevel.error,
17 error.message,
18 {
19 host: window.location.href,
20 path: pathname,
21 statusCode: status,
22 },
23 {
24 error: error.name,
25 cause: error.cause,
26 stack: error.stack,
27 digest: error.digest,
28 },
29 );
30
31 return (
32 <div className="p-8">
33 Ops! An Error has occurred:{" "}
34 <p className="text-red-400 px-8 py-2 text-lg">`{error.message}`</p>
35 <div className="w-1/3 mt-8">
36 <NavTable />
37 </div>
38 </div>
39 );
40}
next-axiom switched to support the App Router starting with version 1.0. If you are upgrading a Pages Router app with next-axiom v0.x to the App Router, you will need to make the following changes:
NEXT_PUBLIC_
prefix, e.g: NEXT_PUBLIC_AXIOM_TOKEN
useLogger
hook in client components instead of log
propLogger
and flush the logs before component returns.reportWebVitals()
and instead add the AxiomWebVitals
component to your layout.The Axiom Vercel integration sets up an environment variable called NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT
, which by default is only enabled for the production environment. To send logs from preview deployments, go to your site settings in Vercel and enable preview deployments for that environment variable.
You can use log.with
to create an intermediate logger, for example:
1const logger = userLogger().with({ userId: 42 }); 2logger.info('Hi'); // will ingest { ..., "message": "Hi", "fields" { "userId": 42 }}
Distributed under the MIT License.
No vulnerabilities found.
No security vulnerabilities found.