emit-io-next
v3.0.0
Published
Next.js bindings for emit-io — middleware, route handlers, RSC support
Maintainers
Readme
emit-io-next
Next.js bindings for emit-io-core — middleware logging and App Router route handler instrumentation.
Install
npm install emit-io-core emit-io-nextQuick Start
// lib/emit.ts
import { EmitIoStrategy, JSONTransport, LogLevelEnum } from 'emit-io-core'
export const emit = new EmitIoStrategy({
transports: [new JSONTransport({ minLevel: LogLevelEnum.INFO })],
})// middleware.ts
import { withLogger } from 'emit-io-next'
import { NextResponse } from 'next/server'
import { emit } from './lib/emit'
export default withLogger(
async (req) => NextResponse.next(),
{ logger: emit, trackPageviews: true }
)
export const config = { matcher: ['/((?!_next|favicon).*)'] }// app/api/orders/route.ts
import { instrumentRoute } from 'emit-io-next'
import { emit } from './lib/emit'
export const GET = instrumentRoute(
async (req) => Response.json({ orders: [] }),
{ logger: emit, eventName: 'get-orders' }
)API
withLogger(handler, options)
Wraps a Next.js middleware function. Adds:
requestIdfromx-request-idheader (or generates a UUID)- ALS context with
{ requestId, path }for the duration of the request - Auto-logs request start, completion, and errors via
emit.info/emit.error - Propagates
x-request-idheader in the response - Optional
pageviewanalytics event on GET requests
import { withLogger } from 'emit-io-next'
import type { MiddlewareOptions } from 'emit-io-next'
const options: MiddlewareOptions = {
logger: emit,
extractRequestId: (req) => req.headers.get('x-trace-id') ?? undefined,
trackPageviews: true, // default: true
}
export default withLogger(myHandler, options)instrumentRoute(handler, options)
Wraps an App Router route handler (GET, POST, etc.). Adds:
requestId+ ALS context with{ requestId, path, method }- Logs completion with
statusanddurationMs - Catches errors and logs them before re-throwing
import { instrumentRoute } from 'emit-io-next'
import type { RouteHandlerOptions } from 'emit-io-next'
export const POST = instrumentRoute(
async (req, ctx) => {
const { id } = await ctx.params
return Response.json({ id })
},
{ logger: emit, eventName: 'create-order' }
)ALS Context in Route Handlers
Both withLogger and instrumentRoute use runWithContext internally. Any log calls made within the handler automatically include requestId and other bound fields without manual threading.
// Inside a route wrapped with instrumentRoute:
emit.info('processing order', { orderId: '123' })
// → { msg: 'processing order', context: { requestId: 'uuid', path: '/api/orders', method: 'POST', orderId: '123' } }Peer Dependencies
| Package | Version |
|---|---|
| emit-io-core | ^1.0.0 |
| next | ^14.0.0 \|\| ^15.0.0 |
License
MIT
