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:const { withAxiom } = require('next-axiom');
module.exports = withAxiom({
// Your existing configuration.
});To capture traffic requests, create a middleware.ts file in the root folder of your Next.js app:
import { Logger } from 'next-axiom'
import { NextResponse } from 'next/server'
import type { NextFetchEvent, NextRequest } from 'next/server'
export async function middleware(request: NextRequest, event: NextFetchEvent) {
const logger = new Logger({ source: 'middleware' }); // traffic, request
logger.middleware(request)
event.waitUntil(logger.flush())
return NextResponse.next()
// For more information, see Matching Paths below
export const config = {
}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.export async function middleware(request: NextRequest, event: NextFetchEvent) {
const logger = new Logger({ source: "middleware" });
await logger.middleware(request, { logRequestDetails: ["body", "nextUrl"] });
event.waitUntil(logger.flush());
return NextResponse.next();
}To send Web Vitals to Axiom, add the AxiomWebVitals component from next-axiom to the app/layout.tsx file:
import { AxiomWebVitals } from 'next-axiom';
export default function RootLayout() {
return (
<html>
...
<AxiomWebVitals />
<div>...</div>
</html>
);
}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.
log.debug('Login attempt', { user: 'j_doe', status: 'success' }); // Results in {"message": "Login attempt", "fields": {"user": "j_doe", "status": "success"}}
log.info('Payment completed', { userID: '123', amount: '25USD' });
log.warn('API rate limit exceeded', { endpoint: '/users/1', rateLimitRemaining: 0 });
log.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:
import { withAxiom, AxiomRequest } from 'next-axiom';
export const GET = withAxiom((req: AxiomRequest) => {
req.log.info('Login function called');
// You can create intermediate loggers
const log = req.log.with({ scope: 'user' });
log.info('User logged in', { userId: 42 });
return NextResponse.json({ hello: 'world' });
});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:
export const GET = withAxiom(
async () => {
return new Response("Hello World!");
},
{
logRequestDetails: ['body', 'nextUrl'], // { logRequestDetails: true } is also valid
NotFoundLogLevel: 'error',
RedirectLogLevel: 'debug',
}
);To send logs from client components, add useLogger from next-axiom to your component:
'use client';
import { useLogger } from 'next-axiom';
export default function ClientComponent() {
const log = useLogger();
log.debug('User logged in', { userId: 42 });
return <h1>Logged in</h1>;
}To send logs from server components, add Logger from next-axiom to your component, and call flush before returning:
import { Logger } from 'next-axiom';
export default async function ServerComponent() {
const log = new Logger();
log.info('User logged in', { userId: 42 });
// ...
await log.flush();
return <h1>Logged in</h1>;
}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.infowarnerror 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:
export NEXT_PUBLIC_AXIOM_LOG_LEVEL=infoTo 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:"use client";
import { useLogger, LogLevel } from "next-axiom";
import { usePathname } from "next/navigation";
export default function ErrorPage({
error,
}: {
error: Error & { digest?: string };
}) {
const pathname = usePathname()
const log = useLogger({ source: "error.tsx" });
let status = error.message == 'Invalid URL' ? 404 : 500;
log.logHttpRequest(
LogLevel.error,
error.message,
{
host: window.location.href,
path: pathname,
statusCode: status,
},
{
error: error.name,
cause: error.cause,
stack: error.stack,
digest: error.digest,
},
);
return (
<div className="p-8">
Ops! An Error has occurred:{" "}
<p className="text-red-400 px-8 py-2 text-lg">`{error.message}`</p>
<div className="w-1/3 mt-8">
<NavTable />
</div>
</div>
);
}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_TOKENuseLogger 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:
const logger = userLogger().with({ userId: 42 });
logger.info('Hi'); // will ingest { ..., "message": "Hi", "fields" { "userId": 42 }}Distributed under the MIT License.