Skip to main content
This tutorial mirrors the Python tutorial — same API shape, camelCase names, async callbacks instead of context managers.
Assumes TRULAYER_API_KEY and OPENAI_API_KEY are exported. Install: npm install @trulayer/sdk openai anthropic ai.

1. Initialise the SDK

In long-lived apps (Next.js, Fastify, Hono), create one TruLayer instance at module scope and reuse it.

2. Trace a block of code

The callback runs with the trace as its argument; when it resolves, the trace is sealed and queued for ingest.

3. Add spans

4. Auto-instrument OpenAI

5. Auto-instrument Anthropic

6. Vercel AI SDK

The Vercel AI SDK has first-class support via instrumentVercelAI(). It hooks into generateText, streamText, generateObject, and streamObject so every call is traced without further changes.
See Vercel AI SDK integration for streaming and tool-calling specifics.

7. Next.js App Router

Instrument once in instrumentation.ts at your app root — Next.js loads this file before any route handler runs.
Then from a route handler:

8. Edge runtimes (Vercel Edge, Cloudflare Workers)

The SDK works in Edge runtimes — it uses native fetch with no Node-specific APIs. One caveat: Edge runtimes terminate the isolate quickly, so always await tl.flush() before returning your response.

9. Group into a session

10. Attach metadata

11. Submit feedback

Return trace.id from your handler so the client can attach feedback to the right trace.

12. PII redaction

13. Graceful shutdown

Serverless functions should flush before returning; long-lived services should flush on SIGTERM.