Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/axiomhq/next-axiom
The official Next.js library for Axiom.
https://github.com/axiomhq/next-axiom
axiom javascript logging nextjs typescript vercel web-vitals
Last synced: 5 days ago
JSON representation
The official Next.js library for Axiom.
- Host: GitHub
- URL: https://github.com/axiomhq/next-axiom
- Owner: axiomhq
- License: mit
- Created: 2022-04-28T11:59:37.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-09-24T04:38:23.000Z (about 1 month ago)
- Last Synced: 2024-10-15T12:03:36.289Z (19 days ago)
- Topics: axiom, javascript, logging, nextjs, typescript, vercel, web-vitals
- Language: TypeScript
- Homepage: https://axiom.co/vercel
- Size: 15 MB
- Stars: 363
- Watchers: 4
- Forks: 27
- Open Issues: 31
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# next-axiom
[![build](https://img.shields.io/github/actions/workflow/status/axiomhq/next-axiom/ci.yml?branch=main&ghcache=unused)](https://github.com/axiomhq/next-axiom/actions?query=workflow%3ACI)
[![Latest release](https://img.shields.io/github/release/axiomhq/next-axiom.svg)](https://github.com/axiomhq/next-axiom/releases/latest)
[![License](https://img.shields.io/github/license/axiomhq/next-axiom.svg?color=blue)](https://opensource.org/licenses/MIT)[Axiom](https://axiom.co) unlocks observability at any scale.
- **Ingest with ease, store without limits:** Axiom’s next-generation datastore enables ingesting petabytes of data with ultimate efficiency. Ship logs from Kubernetes, AWS, Azure, Google Cloud, DigitalOcean, Nomad, and others.
- **Query everything, all the time:** Whether DevOps, SecOps, or EverythingOps, query all your data no matter its age. No provisioning, no moving data from cold/archive to “hot”, and no worrying about slow queries. All your data, all. the. time.
- **Powerful dashboards, for continuous observability:** Build dashboards to collect related queries and present information that’s quick and easy to digest for you and your team. Dashboards can be kept private or shared with others, and are the perfect way to bring together data from different sources.For more information, check out the [official documentation](https://axiom.co/docs).
## Introduction
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 for `0.x`](https://github.com/axiomhq/next-axiom/blob/v0.x/README.md).
## Prerequisites
- [Create an Axiom account](https://app.axiom.co/).
- [Create a dataset in Axiom](/docs/reference/datasets) where you send your data.
- [Create an API token in Axiom](/docs/reference/tokens) with permissions to create, read, update, and delete datasets.
- [A new or existing Next.js app](https://nextjs.org/).## Install next-axiom
1. In your terminal, go to the root folder of your Next.js app, and then run `npm install --save next-axiom` to install the latest version of next-axiom.
2. Add the following environment variables to your Next.js app. For more information, see the [Vercel documentation](https://vercel.com/docs/projects/environment-variables).
- `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.
3. In the `next.config.ts` file, wrap your Next.js configuration in `withAxiom`:```js
const { withAxiom } = require('next-axiom');module.exports = withAxiom({
// Your existing configuration.
});
```## Capture traffic requests
To capture traffic requests, create a `middleware.ts` file in the root folder of your Next.js app:
```ts
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 = {
}
```## Web Vitals
To send Web Vitals to Axiom, add the `AxiomWebVitals` component from next-axiom to the `app/layout.tsx` file:
```ts
import { AxiomWebVitals } from 'next-axiom';export default function RootLayout() {
return (
...
...
);
}
```Web Vitals are only sent from production deployments.
## Logs
Send logs to Axiom from different parts of your app. Each log function call takes a message and an optional `fields` object.
```ts
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' });
```### Route handlers
Wrap your route handlers in `withAxiom` to add a logger to your request and log exceptions automatically:
```ts
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' });
});
```### Client components
To send logs from client components, add `useLogger` from next-axiom to your component:
```ts
'use client';
import { useLogger } from 'next-axiom';export default function ClientComponent() {
const log = useLogger();
log.debug('User logged in', { userId: 42 });
returnLogged in
;
}
```### Server components
To send logs from server components, add `Logger` from next-axiom to your component, and call flush before returning:
```ts
import { Logger } from 'next-axiom';export default async function ServerComponent() {
const log = new Logger();
log.info('User logged in', { userId: 42 });// ...
await log.flush();
returnLogged in
;
}
```### Log levels
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:
```sh
export NEXT_PUBLIC_AXIOM_LOG_LEVEL=info
```## Capture errors
To capture routing errors, use the [error handling mechanism of Next.js](https://nextjs.org/docs/app/building-your-application/routing/error-handling):
1. Go to the `app` folder.
2. Create an `error.tsx` file.
3. Inside your component function, add `useLogger` from next-axiom to send the error to Axiom. For example:```ts
"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 (
Ops! An Error has occurred:{" "}
`{error.message}`
);
}
```## Upgrade to the App Router
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:
- Upgrade next-axiom to version 1.0.0 or higher
- Make sure that exported variables has `NEXT_PUBLIC_` prefix, e.g: `NEXT_PUBLIC_AXIOM_TOKEN`
- Use `useLogger` hook in client components instead of `log` prop
- For server side components, you will need to create an instance of `Logger` and flush the logs before component returns.
- For web-vitals, remove `reportWebVitals()` and instead add the `AxiomWebVitals` component to your layout.## FAQ
### How can I send logs from Vercel preview deployments?
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.
### How can I extend the logger?
You can use `log.with` to create an intermediate logger, for example:
```typescript
const logger = userLogger().with({ userId: 42 });
logger.info('Hi'); // will ingest { ..., "message": "Hi", "fields" { "userId": 42 }}
```## License
Distributed under the [MIT License](LICENSE).