Code·September 18, 2025

Setting up PostHog Error Tracking for Nitro

How I set up Posthog Error Tracking for Nitro

PostHog Dashboard

Attribution: posthog.com

If you're like me and absolutely love PostHog, you've probably got it set up in you frontend for analytics, error tracking, etc... You don't really want a seperate tool just for error tracking you backend or API. So, I set up PostHog Error Tracking as a Nitro plugin.

Setup

1. Install posthog-node

npm install --save posthog-node

2. Create posthog.ts in ~/server/plugins/posthog.ts

server/plugins/posthog.ts
import { PostHog } from "posthog-node";

// HTTP methods that typically include request bodies
const METHODS_WITH_BODY = new Set(["POST", "PUT", "PATCH"]);

const hasRequestBody = (method: string) => METHODS_WITH_BODY.has(method);

export default defineNitroPlugin((nitro) => {
  // Skip PostHog initialization in development
  if (import.meta.dev) {
    console.log("PostHog disabled in development mode (server)");
    return;
  }

  // Capture server-side errors
  nitro.hooks.hook("error", async (error, { event }) => {
    if (!event) return;

    const config = useRuntimeConfig(event);
    const client = new PostHog(config.public.posthogPublicKey);

    client.captureException(error, undefined, {
      path: event.path,
      method: event.method,
      query: JSON.stringify(getQuery(event)),
      headers: JSON.stringify(getHeaders(event)),
      body: hasRequestBody(event.method) ? readRawBody(event) : undefined,
    });

    await client.shutdown();
  });
});

Conclusion

This setup will give you PostHog error tracking in your Nitro backend. Happy coding!

Hey! 👋

I hope you enjoyed this post!

I post whatever is on my mind, whether it's life, code, theology, or something random. Follow me on X if you'd like a heads up on new posts.