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
yarn add posthog-node
pnpm add posthog-node
bun add 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!