Send Web-Vitals from Vercel to Axiom.

Overview

next-axiom CI

Send Web-Vitals and logs from Next.js to Axiom.

Get started

  1. Make sure you have the Axiom Vercel integration installed or export NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT
  2. In your Next.js project, run npm install --save next-axiom
  3. Wrap your Next.js config in withAxiom like this in next.config.js:
const { withAxiom } = require('next-axiom')

module.exports = withAxiom({
  // ... your existing config
})

This will proxy the Axiom ingest call from the frontend to improve deliverability.

Reporting WebVitals

Go to pages/_app.js or pages/_app.ts and add the following line:

export { reportWebVitals } from 'next-axiom'

Note: WebVitals are only sent from production deployments.

Sending Logs

  1. Import Axiom's logger
import { log } from 'next-axiom';
  1. If you want to log from a function, wrap it using withAxiom like this:
// serverless function
async function handler(req, res) {
  log.info("hello from function")
  res.status(200).text('hi')
}

export default withAxiom(handler)
// middleware function
import { NextResponse } from 'next/server'

async function handler(req, ev) {
  log.info("hello from middleware")
  return NextResponse.next()
}

export default withAxiom(handler)

This will log exceptions as well as making sure logs are flushed.

  1. Use the logger to send logs to Axiom, you can attach other metadata to your logs by passing them as parameters:
log.info('hello, world!')
log.debug('debugging information', { foo: 'bar', x: 'y' })
log.warn('be careful!')
log.error('oops!')

If you have fields you want to log with all messages, you can create an intermediate logger like this:

const logger = log.with({ scope: 'user' })
logger.info('User logged in', { userId: 42 })
// { 
//   "level": "info", 
//   "_time": "2022-07-04T09:49:42Z", 
//   "message": "User logged in", 
//   "fields": {
//     "scope": "user",
//     "userId": 42,
//   }
// }
  1. Deploy your site and watch data coming into your Axiom dataset.

Note: Logs are only sent to Axiom from production deployments.

Configuration

When env vars are not detected, Pretty printing to console is enabled by default, to disable it set the environment variable:

AXIOM_PRETTY_PRINT_ENABLED=false
Comments
  • `withAxiom` does not support next.js' `basePath`

    `withAxiom` does not support next.js' `basePath`

    I have my next.js app set up with the basePath option meaning that it's running on example.com/foo instead of example.com. Unfortunately, withAxiom sets up its endpoints in a way that does not seem to support basePath:

    source: `${proxyPath}/web-vitals`,
    

    where proxyPath = export const proxyPath = '/_axiom';.

    I can see in the devtools' network tab that the request is being fired at example.com/_axiom/web-vitals. Would it be possible to support the basePath option so that axiom's requests would be fired at, e.g., example.com/foo/_axiom/web-vitals?

    opened by klapec 17
  • attach request info to log events

    attach request info to log events

    when we print logs to vercel console we receive request information with the logs. Those are missing when we send logs using axiom logger. This collects the request information and attach them as part of the fields object, they would be parsed in the backend.

    opened by schehata 9
  • [Q&A] Where do I put my API token?

    [Q&A] Where do I put my API token?

    I just started using Axiom and next-axiom and I'm a little lost... So any help is appreciated 👍

    From the docs I found the ingest api url should be like: https://cloud.axiom.co/api/v1/datasets/$DATASET_NAME/ingest. However, I'm getting status 403, so my question is where do I need to put my API token? Just in the .env file or somewhere else?

    opened by zanzlender 8
  • DX-196; use axiom ingest endpoints

    DX-196; use axiom ingest endpoints

    • [X] Separate vercel, netlify and generic config handlers
    • [x] ensure all variables work with vercel deployments
    • [x] ensure all variables work with netlify deployments
    • [x] find a way to pass auth through navigator.beacon (didn't work, beacon will only be used with verbal for now)
    • [x] review namings and code structure
    • [x] update README/docs for vercel and non-vercel usage
    • [x] compare verbal schema before and after change
    • [x] send web vitals one by one on non-vercel platforms
    opened by schehata 5
  • How to i set up axiom with getServerSideProps while using Next-Redux-Wrapper ??

    How to i set up axiom with getServerSideProps while using Next-Redux-Wrapper ??

    i'm using next-redux-wrapper to get redux store on the server side., i'm trying to console.log() the token in production to debug an issue i'm having So i'm using axiom like this

    import { wrapper } from '../redux/store'
    import { log } from 'next-axiom';
    
    export const getServerSideProps = wrapper.getServerSideProps((store) => async () => {
    
      const token = store.getState().auth.token;
      console.log(token);
     log.info('CONSOLE.LOGGING MY TOKEN', { Type: 'YOUR TOKEN ', Token: token })
      if (token) return {
        redirect: { destination: '/dashboard', permanent: false, }
      } // Redirect to Dashboard if there is a token
    
      return { props: {} }
    })
    

    But i don't think i'm going about it the right way, please can you help me out

    opened by DevYemi 5
  • Typescript support?

    Typescript support?

    Perhaps I'm missing something obvious here, but I can't see anywhere in the docs where we can add the type declaration to the NextApiRequest type to be able to do req.log.

    opened by mclean25 4
  • 403 Forbidden error

    403 Forbidden error

    I’m receiving a 403 error in production (“message”: “Forbidden”) and am wondering if it’s because I didn’t add an API token.

    Following your next-axiom instructions, I also added the NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT to my project so that it points to a custom dataset. However, where/how do I add the corresponding API token so that the ingest endpoint can be accessed?

    Since this is a custom dataset, I don’t have the Vercel integration installed via the Vercel dashboard.

    opened by heymartinadams 4
  • Logging on non-Nextjs frontend?

    Logging on non-Nextjs frontend?

    My company has a NextJS web app running on Vercel, We also have a Chrome Extension version with duplicate front-end code utilizing the same api backend.

    Would we be able to use the your logging functionality on both front-end implementations? (Assuming we set the correct environment variables for the Chrome extension in production)

    opened by mysteryhobo 3
  • Allow sending logs and web vitals from non-production deployments

    Allow sending logs and web vitals from non-production deployments

    👋

    We would like to be able to send logs and web vitals from non-production Next.js deployments on Vercel.

    Our use case is a canary deployment that we would like to open up to users for early feedback and testing. We would ideally receive logs and web vitals from that deployment so we can compare them with our production deployment and spot issues sooner rather than later.

    Is this something you would consider supporting?

    opened by nickrttn 3
  • Can't see the logs printed out in production

    Can't see the logs printed out in production

    Hi! I'm new to Axiom, this looks like an awesome tool, thank you for building it!

    I'm trying to set it up with Next.js and Vercel, and ran into an issue - in my production deployment, I don't see the logs printed out in the devtools console or in the function logs in Vercel's UI.

    In your README it says:

    When env vars are not detected, Pretty printing to console is enabled by default, to disable it set the environment variable: AXIOM_PRETTY_PRINT_ENABLED=false

    My guess was that if I'd set this variable to true in production, it should enable printing the logs into the console, but it doesn't look like it's working. Even with this variable set to true, I don't see errors in my devtools.

    Can you help me out? How can I enable pretty printing logs in production?

    opened by lumenwrites 3
  • 404 on _axiom/logs and _axiom/web-vitals

    404 on _axiom/logs and _axiom/web-vitals

    Hi there, i'm trying to set this up in a standard vercel project using the integration, and in my production deployment I get 404's on both the /logs and /web-vitals requests from my frontend.

    Screenshot 2022-12-20 at 10 43 37 PM

    Looks like axiom has spun up some lambdas in my project but my build output doesnt show them.

    Screenshot 2022-12-20 at 10 43 53 PM

    A look at the log stream for the apis shows this message: INVALID_REQUEST_METHOD: This Request was not made with an accepted method, so I guess the lambda does exist it just doesnt know how to handle a post request 🤔

    What have I done wrong? I've just followed the standard setup instructions from the vercel integration page.

    opened by reubenjh 2
  • Add a HOF for wrapping getServerSideProps handlers

    Add a HOF for wrapping getServerSideProps handlers

    • Add withAxiomNextServerSidePropsHandler
    • Export all withAxiom functions
    • Change type signature for withAxiomNextApiHandler
    • Change type signature for withAxiom
    opened by haydn 2
  • Usage with TRPC - how does this look?

    Usage with TRPC - how does this look?

    Hey, I'm building an application with the T3 stack and wanted to check if there is a better way to use Axiom with TRPC's router in a Next API route. Let me know if you see room for improvement or want more context on this.

    1. Wrap the handler function in [trpc].ts with withAxiom like the docs say to.
    import { createNextApiHandler } from "@trpc/server/adapters/next";
    import { appRouter } from "../../../server/router";
    import { createContext } from "../../../server/router/context";
    import { withAxiom } from 'next-axiom'
    
    // export API handler
    export default withAxiom(
      createNextApiHandler({
        router: appRouter,
        createContext,
      })
    );
    
    1. Inside context.ts, add anisAxiomAPIRequest type guard to make sure req.log exists and confirm the request is an AxiomAPIRequest, not NextApiRequest. This will get us type safety both at compile time and runtime. Feel free to make this check more exhaustive (eg check the with function exists on log).

      Extra context: This is where the NextAPIRequest/AxiomAPIRequest is transformed into part of TRPC's own req object.

    // 1 new import
    import { AxiomAPIRequest } from "next-axiom/dist/withAxiom";
    
    const isAxiomAPIRequest = (
      req?: NextApiRequest | AxiomAPIRequest
    ): req is AxiomAPIRequest => {
      return Boolean((req as AxiomAPIRequest)?.log);
    };
    
    export const createContext = async (
      opts?: trpcNext.CreateNextContextOptions
    ) => {
      const req = opts?.req;
      const res = opts?.res;
    
      if (!isAxiomAPIRequest(req)) {
        throw new Error("this is not the request type I expected");
      }
    
      const session =
        req && res && (await getServerSession(req, res, nextAuthOptions));
    
      const log = session ? req.log.with({ userId: session.user.id }) : req.log;
    
      return {
        req,
        res,
        session,
        prisma,
        log,
      };
    };
    
    1. Inside your TRPC queries and mutations, use and re-assign the logger as needed. Here, req is a TRPC request, not a NextApiResponse or AxiomAPIRequest, but we can access the logger on req.ctx.log with the expected type information.
    .mutation("create-signed-url", {
      async resolve(req) {
    
        // add some data to all following log messages by creating a new logger using `with`
        req.ctx.log = req.ctx.log.with({ data })
    
        // or log a message
        req.ctx.log.info(
          'Here\'s some info', { mediaInfo }
        )
      }
    })
    
    1. Inside your main router in server/router/index.ts, add middleware to copy the reference to the newest logger back on to the AxiomAPIRequest (ctx.req) so that Axiom will flush the correct instance of the logger when the request is about to be finished.
    export const appRouter = createRouter()
      .middleware(async ({ ctx, next }) => {
        const result = await next();
        (ctx.req as AxiomAPIRequest).log = ctx.log;
        return result
      })
      .merge("example.", exampleRouter)
      .merge("auth.", authRouter);
    
    opened by adamsullovey 3
  • TypeError: Cannot read properties of undefined (reading '_log')

    TypeError: Cannot read properties of undefined (reading '_log')

    Sometimes I'm seeing a popup that looks like this: Screen Shot 2022-08-31 at 17 12 29

    Screen Shot 2022-08-31 at 17 13 23

    And there's no way for me to know where this error is coming from, or what's causing this.

    There should probably be a more meaningful error message that would help people understand what's going on.

    But meanwhile - can you help me figure out how to find the source of the problem and fix it?

    opened by lumenwrites 3
Releases(v0.16.0)
Whatsapp-web-clone MERN project deployed on vercel and heruku

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Shreyansh Singh 3 Dec 17, 2022
Konbini Otaku, Web E-Commerce del proyecto Estación Otaku, desarrollada con Next.js y desplegada con Vercel

Konbini Otaku ?? ?? ⛩️ ?? - Reto Final (parte 2) Este proyecto constó de proponer "Konbini Otaku", la cual es una tienda virtual en la que podrás adqu

null 2 Apr 28, 2022
📄 UI clone from vercel old site (Using basic tools)

vercel old site A portfolio site, made using the latest technologies. In the construction of the site using Sass. Quality: 1) Benchmark test using a s

Pedromdsn 2 Mar 1, 2022
Vercel's engineering style guide

The Vercel Style Guide This repository is the home of Vercel's style guide, which includes configs for popular linting and styling tools. The followin

Vercel 409 Jan 6, 2023
My personal website built with Next.js, TypeScript, twin.macro, Framer Motion, MDX and deployed on Vercel.

chrvaskos.com My personal website / blog built with some of my favorite technologies where I can showcase my work and write articles about anything ne

Vasilis Christoforidis 4 Mar 25, 2022
A database of all websites built on Vercel.

This is a Next.js project bootstrapped with create-next-app. You can clone & create this repo with the following command npx create-next-app nextjs-ty

Steven Tey 3 May 16, 2022
The Remix Stack for deploying to Vercel with testing, linting, formatting, structure and mock for 3rd party API integration.

Remix DnB Stack See it live: https://dnb-stack.vercel.app/ Learn more about Remix Stacks. npx create-remix --template robipop22/dnb-stack What's in th

Robert Pop 61 Dec 13, 2022
Remix Stack for deploying to Vercel with remix-auth, Planetscale, Radix UI, TailwindCSS, formatting, linting etc. Written in Typescript.

Remix Synthwave Stack Learn more about Remix Stacks. npx create-remix --template ilangorajagopal/synthwave-stack What's in the stack Vercel deploymen

Ilango 56 Dec 25, 2022
A Notion themed portfolio developed with NextJS, deployed on Vercel.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Mackenzie 4 Jul 19, 2022
A simple daily news, used the api of Zhihu Daily, deployed on Vercel.

Daily News Introduction | 介绍 A simple daily news website, used the api of Zhihu Daily, deployed on Vercel. Inspired by @zkeq/news. 一个简单的,使用知乎日报api的,部署

Lockinwize Lolite 4 Jul 26, 2022
simple irc using next.js and @hopinc hosted on @vercel

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

funny 16 Oct 3, 2022
Dashboard for adding, removing, and viewing Vercel redirects.

?? Next.js Redirect Manager Starter for Vercel Dashboard for adding, removing, and viewing Vercel redirects. ⚡️ Quick Start ?? Getting Started ?? What

Colby Fayock 9 Nov 29, 2022
Student reviews for OMS courses. Built with NextJS and Typescript. Backed by Sanity CMS. Deployed on Vercel.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

OMS Tech 27 Dec 3, 2022
▲ Vercel Preview Github Action

Vercel Preview Deployments Github Action Trigger Vercel preview deployments when you want to integrate with external services smoothly. Vercel preview

Snaplet 13 Dec 16, 2022
🍣 CLI to handle Private Git Submodules in your Vercel Project

vercel-submodules: The CLI to handle Private Git Submodules in your Vercel Project This project is community-driven and not affiliated with Vercel in

Juno 37 Jan 1, 2023
Minimal, SEO-focused website starter kit powered by Notion, GitHub, and Vercel.

wr8 wr8 lets you create a website in Notion with better SEO. It is a customized version of nextjs-notion-starter-kit, based on NotionX. Introduction T

Verfasor 7 Dec 22, 2022
🌟 My Website/Blog using Next.js, Tailwind CSS and Vercel (v3)

My Website made using Next.js, Tailwind CSS, and Vercel. Screenshots ?? ?? Live at - https://arunava.tech Features ?? Next.js Tailwind CSS Vercel Dark

Arunava Ghosh 9 Dec 22, 2022
Vercel NextJS Conf Prism + P5.js flashlight tracking

This project was bootstrapped with Create React App. Below you will find some information on how to perform common tasks. You can find the most recent

Chun Rapeepat 5 Oct 27, 2022