Next.js logs installation
Logs is free to use whilst in beta, though we'd love to hear your feedback in app.
- 1
Install OpenTelemetry packages
RequiredTerminal - 2
Get your project API key
RequiredYou'll need your PostHog project API key to authenticate log requests. This is the same key you use for capturing events and exceptions with the PostHog SDK.
Important: Use your project API key which starts with
phc_. Do not use a personal API key (which starts withphx_).You can find your project API key in Project Settings under "Project Variables" → "Project API key".
- 3
Enable instrumentation in Next.js
RequiredNote: For Next.js 15 and later, the instrumentation hook is enabled by default. You can skip this step if you're on Next.js 15+.
Add the following to your
next.config.js(ornext.config.mjs) to enable the instrumentation hook:JavaScript - 4
Create the instrumentation file
RequiredCreate an
instrumentation.ts(orinstrumentation.js) file in the root of your project (or insidesrc/if you use that folder).typescriptNote: The
loggerProvideris created outside ofregister()so it can be exported and used to flush logs in route handlers. This pattern is necessary because Route Handlers complete execution before batched logs have a chance to be sent to the collector. By exporting the provider, we can manually flush logs at the end of each request.Important: The
Content-Type: application/jsonheader is required.Alternatively, you can pass the API key as a query parameter:
typescript - 5
Use OpenTelemetry logging
RequiredNow you can use OpenTelemetry logging in your server-side code (API routes, Server Components, etc.):
typescriptImportant: Without calling
forceFlush(), your logs may not be sent. Route Handlers complete execution before the OpenTelemetry batch processor has a chance to send logs to the collector. Theafter()function fromnext/serverruns code after the response is sent, ensuring logs are flushed before the serverless function freezes. - 6
Next steps
CheckpointWhat you can do with your logs