Skip to content

The only tool you need to know what is happening and how to fix it.

js to otel

dduxf02b4cbd070d
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.go
index 00d5cd0f..0a2241f7 100644
--- a/backend/app/controllers/auth.controller.go
+++ b/backend/app/controllers/auth.controller.go
@@ -154,7 +154,7 @@ func (a authController) Register(c *gin.Context) {
if !validFrameworks[request.Framework] {
traceway.CaptureMessage("Invalid framework received during registration: " + request.Framework)
- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, nextjs, nestjs, express, remix, cloudflare, opentelemetry"})
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, hono, cloudflare, opentelemetry, symfony"})
return
}
diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.go
index 62d0851a..30b130aa 100644
--- a/backend/app/controllers/project.controller.go
+++ b/backend/app/controllers/project.controller.go
@@ -34,6 +34,7 @@ var validFrameworks = map[string]bool{
"express": true,
"remix": true,
"jquery": true,
+ "hono": true,
"cloudflare": true,
"opentelemetry": true,
// PHP frameworks
@@ -85,7 +86,7 @@ func (p projectController) CreateProject(c *gin.Context) {
if !validFrameworks[request.Framework] {
traceway.CaptureMessage("Invalid framework received: " + request.Framework)
- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, nextjs, nestjs, express, remix, jquery, cloudflare, opentelemetry, symfony"})
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, hono, cloudflare, opentelemetry, symfony"})
return
}
diff --git a/docs/components/FrameworkPicker.jsx b/docs/components/FrameworkPicker.jsx
index 4a60e0f7..e55e3788 100644
--- a/docs/components/FrameworkPicker.jsx
+++ b/docs/components/FrameworkPicker.jsx
@@ -91,19 +91,27 @@ const FRAMEWORKS = [
{
value: "js-node",
label: "Node.js",
- description: "Node.js backend SDK with trace context, spans, and metrics.",
+ description: "Node.js backend with OpenTelemetry traces and metrics.",
icon: "/node.png",
href: "/client/node-sdk",
- badge: "new",
+ badge: "production",
},
{
value: "js-nestjs",
label: "NestJS",
- description: "NestJS framework with module, middleware, and decorators.",
+ description: "NestJS framework with OpenTelemetry auto-instrumentation.",
icon: "/nestjs.png",
href: "/client/nestjs",
badge: "production",
},
+ {
+ value: "js-hono",
+ label: "Hono",
+ description: "Lightweight multi-runtime framework with OpenTelemetry.",
+ icon: "/hono.png",
+ href: "/client/hono",
+ badge: "new",
+ },
{
value: "js-react",
label: "React",
diff --git a/docs/components/SdkContext.jsx b/docs/components/SdkContext.jsx
index 0dfeffab..bc1d72a2 100644
--- a/docs/components/SdkContext.jsx
+++ b/docs/components/SdkContext.jsx
@@ -8,8 +8,9 @@ export const SDK_OPTIONS = [
{ value: 'go-fasthttp', label: 'Go FastHTTP' },
{ value: 'go-http', label: 'Go Http' },
{ value: 'go-generic', label: 'Go Generic' },
- { value: 'js-node', label: 'Node.js' },
- { value: 'js-nestjs', label: 'NestJS' },
+ { value: 'js-node', label: 'Node.js (OTel)' },
+ { value: 'js-nestjs', label: 'NestJS (OTel)' },
+ { value: 'js-hono', label: 'Hono' },
{ value: 'js-react', label: 'React' },
{ value: 'js-vue', label: 'Vue.js' },
{ value: 'js-svelte', label: 'Svelte' },
@@ -32,6 +33,7 @@ const PATH_SDK_MAP = {
'http-middleware': 'go-http',
'node-sdk': 'js-node',
'nestjs': 'js-nestjs',
+ 'hono': 'js-hono',
'react': 'js-react',
'vue': 'js-vue',
'svelte': 'js-svelte',
diff --git a/docs/pages/client/_meta.json b/docs/pages/client/_meta.json
index 5bb3bb6a..af4cadc3 100644
--- a/docs/pages/client/_meta.json
+++ b/docs/pages/client/_meta.json
@@ -11,8 +11,9 @@
"fasthttp-middleware": "FastHTTP Middleware",
"http-middleware": "HTTP Middleware",
"sdk": "SDK Reference",
- "node-sdk": "Node.js SDK",
- "nestjs": "NestJS",
+ "node-sdk": "Node.js (OTel)",
+ "nestjs": "NestJS (OTel)",
+ "hono": "Hono",
"react": "React",
"vue": "Vue.js",
"svelte": "Svelte",
diff --git a/docs/pages/client/hono/_meta.json b/docs/pages/client/hono/_meta.json
new file mode 100644
index 00000000..13ec779a
--- /dev/null
+++ b/docs/pages/client/hono/_meta.json
@@ -0,0 +1,4 @@
+{
+ "index": "Quick Start",
+ "traces": "Traces"
+}
diff --git a/docs/pages/client/hono/index.mdx b/docs/pages/client/hono/index.mdx
new file mode 100644
index 00000000..48ac80a3
--- /dev/null
+++ b/docs/pages/client/hono/index.mdx
@@ -0,0 +1,133 @@
+# Hono
+
+Instrument your Hono application with OpenTelemetry and export traces and metrics to Traceway. Hono runs on multiple runtimes — this guide covers the Node.js setup. For Cloudflare Workers, see the [Cloudflare guide](/client/cloudflare).
+
+## Installation
+
+```bash
+npm install hono @hono/node-server \
+ @opentelemetry/sdk-node \
+ @opentelemetry/auto-instrumentations-node \
+ @opentelemetry/exporter-trace-otlp-http \
+ @opentelemetry/exporter-metrics-otlp-http
+```
+
+## Setup
+
+Create an `instrumentation.ts` file at the root of your project:
+
+```typescript
+import { NodeSDK } from "@opentelemetry/sdk-node";
+import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
+import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
+import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
+import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
+
+const sdk = new NodeSDK({
+ serviceName: "my-hono-app",
+ serviceVersion: "1.0.0",
+
+ traceExporter: new OTLPTraceExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/traces",
+ headers: { Authorization: "Bearer your-project-token" },
+ }),
+
+ metricReader: new PeriodicExportingMetricReader({
+ exporter: new OTLPMetricExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/metrics",
+ headers: { Authorization: "Bearer your-project-token" },
+ }),
+ exportIntervalMillis: 30_000,
+ }),
+
+ instrumentations: [getNodeAutoInstrumentations()],
+});
+
+sdk.start();
+```
+
+## Application Code
+
+```typescript
+import { serve } from "@hono/node-server";
+import { Hono } from "hono";
+
+const app = new Hono();
+
+app.get("/api/users", (c) => {
+ return c.json({ users: [] });
+});
+
+app.get("/api/users/:id", (c) => {
+ const id = c.req.param("id");
+ return c.json({ id, name: "John" });
+});
+
+serve({ fetch: app.fetch, port: 3000 });
+```
+
+## Running Your App
+
+Load the instrumentation file before your application code:
+
+```bash
+# CommonJS
+node --require ./instrumentation.js server.js
+
+# ESM / TypeScript (with tsx)
+node --import ./instrumentation.ts server.ts
+```
+
+Or set via environment variable:
+
+```bash
+export NODE_OPTIONS="--require ./instrumentation.js"
+node server.js
+```
+
+## What Gets Captured
+
+Hono on Node.js uses `@hono/node-server`, which creates a standard Node.js HTTP server. OTel auto-instrumentation captures:
+
+| Layer | What's Captured |
+|-------|-----------------|
+| HTTP server | Incoming requests with method, route, status code, duration |
+| HTTP client (fetch) | Outgoing HTTP request spans |
+| Database (pg, mysql2, etc.) | Query spans |
+
+Root SERVER spans become **Endpoints** in Traceway (e.g., `GET /api/users`), child spans become **Spans**, and exception events become **Issues**.
+
+## Environment Variable Alternative
+
+```bash
+export OTEL_SERVICE_NAME="my-hono-app"
+export OTEL_EXPORTER_OTLP_ENDPOINT="https://your-traceway-instance.com/api/otel"
+export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
+```
+
+## Test Your Integration
+
+Add a test endpoint:
+
+```typescript
+app.get("/test-error", () => {
+ throw new Error("Test error from Hono");
+});
+```
+
+Visit `/test-error` and check your Traceway dashboard — the error should appear under **Issues** with a full stack trace.
+
+## Multi-Runtime Notes
+
+| Runtime | Instrumentation |
+|---------|----------------|
+| **Node.js** | OTel Node SDK (this guide) |
+| **Cloudflare Workers** | Native OTLP export — see [Cloudflare guide](/client/cloudflare) |
+| **Deno** | Use [Deno OTel](https://docs.deno.com/runtime/fundamentals/open_telemetry/) with OTLP/HTTP export to Traceway |
+| **Bun** | Use `@opentelemetry/sdk-node` (Bun supports most Node.js OTel packages) |
+
+## Next Steps
+
+- [Traces](/client/hono/traces) — manual spans and middleware instrumentation
+- [Node.js OTel Guide](/client/node-sdk) — general Node.js setup details
+- [OTel Overview](/client/otel) — protocol details and authentication
diff --git a/docs/pages/client/hono/traces.mdx b/docs/pages/client/hono/traces.mdx
new file mode 100644
index 00000000..e10bbea4
--- /dev/null
+++ b/docs/pages/client/hono/traces.mdx
@@ -0,0 +1,107 @@
+# Traces
+
+Auto-instrumentation handles HTTP request tracing automatically. This page covers manual spans and Hono middleware instrumentation.
+
+## Manual Spans
+
+Use `@opentelemetry/api` to create custom spans for operations that aren't auto-instrumented:
+
+```typescript
+import { trace, SpanStatusCode } from "@opentelemetry/api";
+
+const tracer = trace.getTracer("my-hono-app");
+
+app.get("/api/orders/:id", async (c) => {
+ const orderId = c.req.param("id");
+
+ return tracer.startActiveSpan("fetch-order", async (span) => {
+ try {
+ span.setAttribute("order.id", orderId);
+ const order = await db.orders.findById(orderId);
+
+ if (!order) {
+ span.setStatus({ code: SpanStatusCode.ERROR, message: "Order not found" });
+ span.end();
+ return c.json({ error: "Not found" }, 404);
+ }
+
+ span.end();
+ return c.json(order);
+ } catch (error) {
+ span.recordException(error);
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
+ span.end();
+ throw error;
+ }
+ });
+});
+```
+
+## Tracing Middleware
+
+Create a Hono middleware that adds attributes to the current span:
+
+```typescript
+import { trace } from "@opentelemetry/api";
+import { createMiddleware } from "hono/factory";
+
+const addUserContext = createMiddleware(async (c, next) => {
+ const span = trace.getActiveSpan();
+ const userId = c.get("userId");
+
+ if (span && userId) {
+ span.setAttribute("user.id", userId);
+ }
+
+ await next();
+});
+
+app.use("/api/*", addUserContext);
+```
+
+## Exception Recording
+
+Capture exceptions on the active span so they appear as Issues in Traceway:
+
+```typescript
+import { trace, SpanStatusCode } from "@opentelemetry/api";
+
+app.onError((err, c) => {
+ const span = trace.getActiveSpan();
+ if (span) {
+ span.recordException(err);
+ span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
+ }
+ return c.json({ error: "Internal Server Error" }, 500);
+});
+```
+
+## Nested Spans
+
+Spans created inside an active span are automatically linked as children:
+
+```typescript
+const tracer = trace.getTracer("my-hono-app");
+
+async function processPayment(orderId: string) {
+ return tracer.startActiveSpan("process-payment", async (span) => {
+ try {
+ await validateCard(orderId);
+ await chargeAmount(orderId);
+ span.setStatus({ code: SpanStatusCode.OK });
+ } catch (error) {
+ span.recordException(error);
+ span.setStatus({ code: SpanStatusCode.ERROR });
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
+}
+```
+
+## Next Steps
+
+- [Quick Start](/client/hono) — setup and installation
+- [Node.js Traces](/client/node-sdk/traces) — more on manual spans and context propagation
+- [Node.js Metrics](/client/node-sdk/metrics) — custom metrics with OTel
diff --git a/docs/pages/client/nestjs/_meta.json b/docs/pages/client/nestjs/_meta.json
index a498d528..5347dd77 100644
--- a/docs/pages/client/nestjs/_meta.json
+++ b/docs/pages/client/nestjs/_meta.json
@@ -1,8 +1,4 @@
{
"index": "Quick Start",
- "module": "TracewayModule",
- "middleware": "Middleware",
- "filter": "Exception Filter",
- "service": "TracewayService",
- "decorators": "Decorators"
+ "custom-instrumentation": "Custom Instrumentation"
}
diff --git a/docs/pages/client/nestjs/custom-instrumentation.mdx b/docs/pages/client/nestjs/custom-instrumentation.mdx
new file mode 100644
index 00000000..234ebce6
--- /dev/null
+++ b/docs/pages/client/nestjs/custom-instrumentation.mdx
@@ -0,0 +1,149 @@
+# Custom Instrumentation
+
+Add manual spans, custom decorators, and explicit exception capture to your NestJS services using the OpenTelemetry API.
+
+## Setup
+
+Install the OTel API package (if not already installed via `@opentelemetry/sdk-node`):
+
+```bash
+npm install @opentelemetry/api
+```
+
+## Manual Spans in Services
+
+Create spans for operations that aren't auto-instrumented:
+
+```typescript
+import { Injectable } from "@nestjs/common";
+import { trace, SpanStatusCode } from "@opentelemetry/api";
+
+const tracer = trace.getTracer("my-nestjs-app");
+
+@Injectable()
+export class UsersService {
+ async findAll() {
+ return tracer.startActiveSpan("db.users.findAll", async (span) => {
+ try {
+ const users = await this.userRepository.find();
+ span.setAttribute("user.count", users.length);
+ return users;
+ } catch (error) {
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
+ span.recordException(error);
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
+ }
+}
+```
+
+## Custom @Span Decorator
+
+Create a reusable decorator that wraps methods in OTel spans:
+
+```typescript
+import { trace, SpanStatusCode } from "@opentelemetry/api";
+
+const tracer = trace.getTracer("my-nestjs-app");
+
+export function Span(name?: string): MethodDecorator {
+ return (target, propertyKey, descriptor: PropertyDescriptor) => {
+ const originalMethod = descriptor.value;
+ const spanName = name || `${target.constructor.name}.${String(propertyKey)}`;
+
+ descriptor.value = function (...args: any[]) {
+ return tracer.startActiveSpan(spanName, async (span) => {
+ try {
+ const result = await originalMethod.apply(this, args);
+ span.setStatus({ code: SpanStatusCode.OK });
+ return result;
+ } catch (error) {
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
+ span.recordException(error);
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
+ };
+
+ return descriptor;
+ };
+}
+```
+
+Use it on any service method:
+
+```typescript
+import { Injectable } from "@nestjs/common";
+import { Span } from "./span.decorator";
+
+@Injectable()
+export class OrdersService {
+ @Span("orders.process")
+ async processOrder(orderId: string) {
+ // Span is automatically created and ended
+ await this.validate(orderId);
+ await this.charge(orderId);
+ await this.ship(orderId);
+ }
+
+ @Span()
+ async validate(orderId: string) {
+ // Span name defaults to "OrdersService.validate"
+ }
+}
+```
+
+## Exception Capture
+
+Record exceptions on the active span:
+
+```typescript
+import { Injectable } from "@nestjs/common";
+import { trace, SpanStatusCode } from "@opentelemetry/api";
+
+@Injectable()
+export class PaymentService {
+ async charge(amount: number) {
+ const span = trace.getActiveSpan();
+
+ try {
+ await this.gateway.charge(amount);
+ } catch (error) {
+ if (span) {
+ span.recordException(error);
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
+ }
+ throw error;
+ }
+ }
+}
+```
+
+Exceptions recorded as span events appear as **Issues** in Traceway with full stack traces.
+
+## Span Attributes
+
+Add context to spans for richer trace data:
+
+```typescript
+const span = trace.getActiveSpan();
+if (span) {
+ span.setAttribute("user.id", userId);
+ span.setAttribute("order.total", orderTotal);
+ span.setAttributes({
+ "payment.method": "credit_card",
+ "payment.currency": "USD",
+ });
+}
+```
+
+## Next Steps
+
+- [Quick Start](/client/nestjs) — setup and auto-instrumentation
+- [Node.js Traces](/client/node-sdk/traces) — more on manual spans and context propagation
+- [Node.js Metrics](/client/node-sdk/metrics) — custom metrics with OTel
diff --git a/docs/pages/client/nestjs/decorators.mdx b/docs/pages/client/nestjs/decorators.mdx
deleted file mode 100644
index c9c01800..00000000
--- a/docs/pages/client/nestjs/decorators.mdx
+++ /dev/null
@@ -1,171 +0,0 @@
-# Decorators
-
-The `@tracewayapp/nestjs` package provides the `@Span` decorator for automatic span creation around methods.
-
-## @Span Decorator
-
-The `@Span` decorator wraps a method to automatically create and end a span, timing the method's execution.
-
-### Basic Usage
-
-```typescript
-import { Injectable } from "@nestjs/common";
-import { Span } from "@tracewayapp/nestjs";
-
-@Injectable()
-export class UsersService {
- @Span("db.users.findAll")
- async findAll() {
- return this.userRepository.find();
- }
-
- @Span("db.users.findOne")
- async findOne(id: string) {
- return this.userRepository.findOne(id);
- }
-
- @Span("db.users.create")
- async create(data: CreateUserDto) {
- return this.userRepository.save(data);
- }
-}
-```
-
-### Default Span Name
-
-If no name is provided, the method name is used:
-
-```typescript
-@Injectable()
-export class UsersService {
- @Span() // Span name will be "findAll"
- async findAll() {
- return this.userRepository.find();
- }
-}
-```
-
-### With Async Methods
-
-The decorator handles both sync and async methods:
-
-```typescript
-@Injectable()
-export class CacheService {
- @Span("cache.get")
- async get(key: string): Promise<string | null> {
- // Async operation
- return this.redis.get(key);
- }
-
- @Span("cache.compute")
- computeHash(data: string): string {
- // Sync operation
- return crypto.createHash("sha256").update(data).digest("hex");
- }
-}
-```
-
-### Error Handling
-
-The span is ended even if the method throws an error:
-
-```typescript
-@Injectable()
-export class PaymentService {
- @Span("payment.process")
- async processPayment(amount: number) {
- // If this throws, the span is still ended
- // and the error propagates normally
- await this.gateway.charge(amount);
- }
-}
-```
-
-## Naming Conventions
-
-Use descriptive, hierarchical span names:
-
-| Pattern | Example | Use Case |
-|---------|---------|----------|
-| `db.<table>.<operation>` | `db.users.findOne` | Database operations |
-| `cache.<operation>` | `cache.get` | Cache operations |
-| `http.<service>` | `http.payment-api` | External HTTP calls |
-| `queue.<action>` | `queue.publish` | Message queue operations |
-| `<service>.<method>` | `email.send` | Service method calls |
-
-## Combining with TracewayService
-
-You can use `@Span` alongside `TracewayService` for more control:
-
-```typescript
-@Injectable()
-export class OrdersService {
- constructor(private readonly traceway: TracewayService) {}
-
- @Span("orders.process")
- async processOrder(orderId: string) {
- // Set attributes for the trace
- this.traceway.setTraceAttribute("orderId", orderId);
-
- // Create nested spans manually
- const validationSpan = this.traceway.startSpan("orders.validate");
- await this.validateOrder(orderId);
- this.traceway.endSpan(validationSpan);
-
- // The @Span decorator handles the outer span
- await this.fulfillOrder(orderId);
- }
-}
-```
-
-## Limitations
-
-### Class Methods Only
-
-The decorator only works on class methods, not standalone functions:
-
-```typescript
-// Works
-@Injectable()
-class MyService {
- @Span("operation")
- doSomething() {}
-}
-
-// Does NOT work
-@Span("operation") // Error: decorators on functions not supported
-function standalone() {}
-```
-
-### No Parameter Access
-
-The span name is static and cannot access method parameters:
-
-```typescript
-@Injectable()
-class UsersService {
- // Span name is always "db.users.findOne"
- // Cannot be "db.users.findOne:123" based on id parameter
- @Span("db.users.findOne")
- async findOne(id: string) {}
-}
-```
-
-For dynamic span names, use `TracewayService.startSpan()` manually:
-
-```typescript
-@Injectable()
-class UsersService {
- constructor(private readonly traceway: TracewayService) {}
-
- async findOne(id: string) {
- const span = this.traceway.startSpan(`db.users.findOne:${id}`);
- try {
- return await this.userRepository.findOne(id);
- } finally {
- this.traceway.endSpan(span);
- }
- }
-}
-```
diff --git a/docs/pages/client/nestjs/filter.mdx b/docs/pages/client/nestjs/filter.mdx
deleted file mode 100644
index f2979bc4..00000000
--- a/docs/pages/client/nestjs/filter.mdx
+++ /dev/null
@@ -1,174 +0,0 @@
-# TracewayExceptionFilter
-
-The `TracewayExceptionFilter` is a global exception filter that captures unhandled exceptions and sends them to Traceway with full stack traces and request context.
-
-## Setup
-
-Register the filter globally in your app module:
-
-```typescript
-import { Module } from "@nestjs/common";
-import { APP_FILTER } from "@nestjs/core";
-import { TracewayModule, TracewayExceptionFilter } from "@tracewayapp/nestjs";
-
-@Module({
- imports: [
- TracewayModule.forRoot({
- connectionString: "your-token@https://traceway.example.com/api/report",
- onErrorRecording: ["url", "query", "body", "headers"],
- }),
- ],
- providers: [
- {
- provide: APP_FILTER,
- useClass: TracewayExceptionFilter,
- },
- ],
-})
-export class AppModule {}
-```
-
-## What Gets Captured
-
-When an exception is thrown:
-
-| Data | Condition |
-|------|-----------|
-| Error message | Always |
-| Stack trace | Always |
-| Trace ID | If within a traced request |
-| Trace attributes | If within a traced request |
-| User agent | Always |
-| URL | If `onErrorRecording` includes `"url"` |
-| Query params | If `onErrorRecording` includes `"query"` |
-| Request body | If `onErrorRecording` includes `"body"` (JSON only) |
-| Headers | If `onErrorRecording` includes `"headers"` |
-
-## Error Recording Options
-
-Configure what request data to include with captured exceptions:
-
-```typescript
-TracewayModule.forRoot({
- connectionString: "...",
- onErrorRecording: ["url", "query", "body", "headers"],
-})
-```
-
-### URL Recording
-
-```typescript
-onErrorRecording: ["url"]
-```
-
-Captures the request path:
-```
-url: "/api/users/123"
-```
-
-### Query Recording
-
-```typescript
-onErrorRecording: ["query"]
-```
-
-Captures query parameters as JSON:
-```
-query: {"page":"1","limit":"10"}
-```
-
-### Body Recording
-
-```typescript
-onErrorRecording: ["body"]
-```
-
-Captures request body for JSON requests (max 64KB):
-```
-body: {"name":"John","email":"[email protected]"}
-```
-
-### Headers Recording
-
-```typescript
-onErrorRecording: ["headers"]
-```
-
-Captures request headers (excluding `authorization` and `cookie` for security):
-```
-headers: {"content-type":"application/json","x-request-id":"abc123"}
-```
-
-## Exception Types
-
-### Client Errors (4xx)
-
-For `HttpException` errors with 4xx status codes, the filter:
-- Returns the standard NestJS error response
-- Does **not** capture to Traceway (client errors are expected)
-
-### Server Errors (5xx)
-
-For server errors (status code >= 500), including 5xx `HttpException`s and unhandled exceptions:
-- Captures the exception to Traceway
-- Returns the appropriate error response
-
-```typescript
-@Get("crash")
-crash() {
- // Captured — unhandled error becomes 500
- throw new Error("Something went wrong");
-}
-
-@Get("bad-gateway")
-badGateway() {
- // Captured — HttpException with 5xx status
- throw new HttpException("Bad Gateway", 502);
-}
-
-@Get("not-found")
-notFound() {
- // NOT captured — 4xx client error
- throw new NotFoundException("User not found");
-}
-```
-
-## Combining with Other Filters
-
-If you have other exception filters, ensure `TracewayExceptionFilter` runs first by registering it before other filters:
-
-```typescript
-providers: [
- {
- provide: APP_FILTER,
- useClass: TracewayExceptionFilter,
- },
- {
- provide: APP_FILTER,
- useClass: YourCustomFilter,
- },
-],
-```
-
-## Manual Exception Capture
-
-For errors you catch and handle yourself, use `TracewayService`:
-
-```typescript
-@Injectable()
-export class PaymentService {
- constructor(private readonly traceway: TracewayService) {}
-
- async processPayment(amount: number) {
- try {
- await this.paymentGateway.charge(amount);
- } catch (error) {
- // Capture but don't re-throw
- this.traceway.captureException(error);
-
- // Handle gracefully
- return { success: false, error: "Payment failed" };
- }
- }
-}
-```
diff --git a/docs/pages/client/nestjs/index.mdx b/docs/pages/client/nestjs/index.mdx
index 473d4fa8..ed28bd32 100644
--- a/docs/pages/client/nestjs/index.mdx
+++ b/docs/pages/client/nestjs/index.mdx
@@ -1,145 +1,103 @@
-# NestJS Quick Start
+# NestJS (OpenTelemetry)
-Integrate Traceway into your NestJS application with the `@tracewayapp/nestjs` package.
+Instrument your NestJS application with OpenTelemetry and export traces and metrics to Traceway. No vendor-specific NestJS modules needed — OTel auto-instrumentation handles everything.
## Installation
```bash
-npm install @tracewayapp/nestjs
+npm install @opentelemetry/sdk-node \
+ @opentelemetry/auto-instrumentations-node \
+ @opentelemetry/exporter-trace-otlp-http \
+ @opentelemetry/exporter-metrics-otlp-http
```
## Setup
-### 1. Import TracewayModule
-
-Add `TracewayModule.forRoot()` to your app module:
+Create an `instrumentation.ts` file at the root of your NestJS project:
```typescript
-import { Module } from "@nestjs/common";
-import { TracewayModule } from "@tracewayapp/nestjs";
-
-@Module({
- imports: [
- TracewayModule.forRoot({
- connectionString: "your-token@https://traceway.example.com/api/report",
+import { NodeSDK } from "@opentelemetry/sdk-node";
+import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
+import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
+import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
+import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
+
+const sdk = new NodeSDK({
+ serviceName: "my-nestjs-app",
+ serviceVersion: "1.0.0",
+
+ traceExporter: new OTLPTraceExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/traces",
+ headers: { Authorization: "Bearer your-project-token" },
+ }),
+
+ metricReader: new PeriodicExportingMetricReader({
+ exporter: new OTLPMetricExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/metrics",
+ headers: { Authorization: "Bearer your-project-token" },
}),
- ],
-})
-export class AppModule {}
+ exportIntervalMillis: 30_000,
+ }),
+
+ instrumentations: [getNodeAutoInstrumentations()],
+});
+
+sdk.start();
```
-### 2. Add Middleware for Request Tracing
+## Running Your App
-Apply `TracewayMiddleware` to trace all HTTP requests:
+The instrumentation file must load **before** NestJS boots. Use the `--require` flag:
-```typescript
-import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
-import { TracewayModule, TracewayMiddleware } from "@tracewayapp/nestjs";
+```bash
+# Development
+node --require ./instrumentation.js -e "require('./dist/main.js')"
-@Module({
- imports: [
- TracewayModule.forRoot({
- connectionString: "your-token@https://traceway.example.com/api/report",
- }),
- ],
-})
-export class AppModule implements NestModule {
- configure(consumer: MiddlewareConsumer) {
- consumer.apply(TracewayMiddleware).forRoutes("*");
- }
-}
-```
+# Or with ts-node
+node --require ts-node/register --require ./instrumentation.ts src/main.ts
-### 3. Add Exception Filter
+# Or set via environment variable
+export NODE_OPTIONS="--require ./instrumentation.js"
+npm run start
+```
-Register `TracewayExceptionFilter` globally to capture unhandled exceptions:
+If you use the NestJS CLI (`nest start`), set `NODE_OPTIONS` in your environment or add a custom script to `package.json`:
-```typescript
-import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
-import { APP_FILTER } from "@nestjs/core";
-import {
- TracewayModule,
- TracewayMiddleware,
- TracewayExceptionFilter,
-} from "@tracewayapp/nestjs";
-
-@Module({
- imports: [
- TracewayModule.forRoot({
- connectionString: "your-token@https://traceway.example.com/api/report",
- debug: true,
- onErrorRecording: ["url", "query", "body", "headers"],
- }),
- ],
- providers: [
- {
- provide: APP_FILTER,
- useClass: TracewayExceptionFilter,
- },
- ],
-})
-export class AppModule implements NestModule {
- configure(consumer: MiddlewareConsumer) {
- consumer.apply(TracewayMiddleware).forRoutes("*");
+```json
+{
+ "scripts": {
+ "start:traced": "NODE_OPTIONS='--require ./instrumentation.js' nest start"
}
}
```
-## What Gets Captured
-
-| Data | Description |
-|------|-------------|
-| Endpoint | HTTP method and route (e.g., `GET /users/:id`) |
-| Duration | Request processing time |
-| Status Code | HTTP response status |
-| Client IP | Client IP address from headers or socket |
-| Exceptions | Unhandled errors with full stack traces |
-| Spans | Custom spans created within the request |
+## What Gets Auto-Instrumented
-## Using TracewayService
+OTel auto-instrumentation for Node.js captures the following without any code changes:
-Inject `TracewayService` to capture errors and create spans manually:
-
-```typescript
-import { Injectable } from "@nestjs/common";
-import { TracewayService, Span } from "@tracewayapp/nestjs";
+| Layer | What's Captured |
+|-------|-----------------|
+| HTTP (Express/Fastify) | Incoming requests with route, method, status code, duration |
+| Database (TypeORM, Prisma, pg, mysql2) | Query spans with SQL statements |
+| Redis / ioredis | Cache operation spans |
+| HTTP client (axios, fetch) | Outgoing HTTP request spans |
+| gRPC | gRPC call spans |
-@Injectable()
-export class UsersService {
- constructor(private readonly traceway: TracewayService) {}
+NestJS uses Express (or Fastify) under the hood, so all HTTP requests are automatically traced as **Endpoints** in Traceway.
- @Span("db.users.findAll")
- async findAll() {
- // Span automatically created and ended
- return this.userRepository.find();
- }
+## Environment Variable Alternative
- async createUser(data: CreateUserDto) {
- // Manual span
- const span = this.traceway.startSpan("db.users.create");
- try {
- const user = await this.userRepository.save(data);
- return user;
- } finally {
- this.traceway.endSpan(span);
- }
- }
+Instead of hardcoding the endpoint and token, you can use standard OTel environment variables:
- async riskyOperation() {
- try {
- await this.externalApi.call();
- } catch (error) {
- // Manual exception capture
- this.traceway.captureException(error);
- throw error;
- }
- }
-}
+```bash
+export OTEL_SERVICE_NAME="my-nestjs-app"
+export OTEL_EXPORTER_OTLP_ENDPOINT="https://your-traceway-instance.com/api/otel"
+export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
```
## Test Your Integration
-Create a test endpoint that throws an error:
+Add a test endpoint:
```typescript
import { Controller, Get } from "@nestjs/common";
@@ -153,12 +111,10 @@ export class AppController {
}
```
-Visit `/test-error` and check your Traceway dashboard to verify the error appears with a full stack trace.
+Visit `/test-error` and check your Traceway dashboard — the error should appear under **Issues** with a full stack trace.
## Next Steps
-- [TracewayModule](/client/nestjs/module) - Configuration options and async setup
-- [Middleware](/client/nestjs/middleware) - Request tracing details
-- [Exception Filter](/client/nestjs/filter) - Error recording options
-- [TracewayService](/client/nestjs/service) - Manual instrumentation
-- [Decorators](/client/nestjs/decorators) - @Span decorator usage
+- [Custom Instrumentation](/client/nestjs/custom-instrumentation) — manual spans, decorators, and exception capture
+- [Node.js OTel Guide](/client/node-sdk) — general Node.js setup details
+- [OTel Trace Mapping](/client/otel/traces) — how OTel spans map to Traceway concepts
diff --git a/docs/pages/client/nestjs/middleware.mdx b/docs/pages/client/nestjs/middleware.mdx
deleted file mode 100644
index 72f1fe37..00000000
--- a/docs/pages/client/nestjs/middleware.mdx
+++ /dev/null
@@ -1,125 +0,0 @@
-# TracewayMiddleware
-
-The `TracewayMiddleware` wraps each HTTP request in a trace context, automatically capturing request timing, status codes, and any spans created during the request.
-
-## Setup
-
-Apply the middleware in your app module:
-
-```typescript
-import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
-import { TracewayModule, TracewayMiddleware } from "@tracewayapp/nestjs";
-
-@Module({
- imports: [
- TracewayModule.forRoot({
- connectionString: "your-token@https://traceway.example.com/api/report",
- }),
- ],
-})
-export class AppModule implements NestModule {
- configure(consumer: MiddlewareConsumer) {
- consumer.apply(TracewayMiddleware).forRoutes("*");
- }
-}
-```
-
-## Selective Routes
-
-Apply middleware to specific routes only:
-
-```typescript
-export class AppModule implements NestModule {
- configure(consumer: MiddlewareConsumer) {
- consumer
- .apply(TracewayMiddleware)
- .forRoutes("users", "orders", "products");
- }
-}
-```
-
-Or exclude specific routes:
-
-```typescript
-export class AppModule implements NestModule {
- configure(consumer: MiddlewareConsumer) {
- consumer
- .apply(TracewayMiddleware)
- .exclude("health", "metrics")
- .forRoutes("*");
- }
-}
-```
-
-## What Gets Captured
-
-For each request, the middleware captures:
-
-| Field | Description |
-|-------|-------------|
-| `endpoint` | HTTP method and route path (e.g., `GET /users/:id`) |
-| `clientIP` | Client IP from X-Forwarded-For header or socket |
-| `statusCode` | HTTP response status code |
-| `bodySize` | Response body size from Content-Length header |
-| `duration` | Total request processing time |
-| `spans` | Any spans created during the request |
-| `attributes` | Custom attributes set via `TracewayService` |
-
-## How It Works
-
-1. **Request Start**: Creates a new trace context with `withTraceContext()`
-2. **Distributed Trace ID**: If the request contains a `traceway-trace-id` header (sent by the frontend SDK), the middleware reads it, echoes it back in the response, and stores it in the trace context
-3. **Request Processing**: Your controllers and services run within the trace context
-4. **Response Finish**: On the `res.finish` event:
- - Records status code and body size with `setTraceResponseInfo()`
- - Captures the trace with `captureCurrentTrace()`
-
-## Distributed Tracing
-
-The middleware automatically supports distributed tracing between the Traceway frontend SDK and your backend. When the frontend SDK sends a `traceway-trace-id` header (automatically via `fetch` instrumentation or manually via the Axios interceptor), the middleware:
-
-1. Reads the header from the incoming request
-2. Echoes it back in the response header (useful for debugging)
-3. Passes it into the trace context — all traces and exceptions captured during that request are tagged with the distributed trace ID
-
-This lets you correlate frontend errors with their triggering backend requests in the Traceway dashboard. No extra configuration is needed — if the middleware is installed, distributed tracing works out of the box.
-
-See the [JS SDK Distributed Tracing](/client/js-sdk/distributed-tracing) guide for frontend setup details.
-
-## Ignored Routes
-
-Use the `ignoredRoutes` option in `TracewayModule.forRoot()` to skip tracing for specific routes:
-
-```typescript
-TracewayModule.forRoot({
- connectionString: "...",
- ignoredRoutes: ["/health", "/metrics", "/favicon.ico"],
-})
-```
-
-## Trace Context
-
-The middleware establishes a trace context that propagates through all async operations. This means:
-
-- Exceptions captured with `TracewayService.captureException()` are linked to the trace
-- Spans created with `TracewayService.startSpan()` are added to the trace
-- Attributes set with `TracewayService.setTraceAttribute()` are included in the trace
-
-```typescript
-@Injectable()
-export class UsersService {
- constructor(private readonly traceway: TracewayService) {}
-
- async findOne(id: string) {
- // This attribute will be included in the current request's trace
- this.traceway.setTraceAttribute("userId", id);
-
- // This span will be part of the current request's trace
- const span = this.traceway.startSpan("db.query");
- const user = await this.userRepository.findOne(id);
- this.traceway.endSpan(span);
-
- return user;
- }
-}
-```
diff --git a/docs/pages/client/nestjs/module.mdx b/docs/pages/client/nestjs/module.mdx
deleted file mode 100644
index e0c97fb0..00000000
--- a/docs/pages/client/nestjs/module.mdx
+++ /dev/null
@@ -1,124 +0,0 @@
-# TracewayModule
-
-The `TracewayModule` is a global NestJS module that initializes Traceway and provides the `TracewayService` throughout your application.
-
-## Static Configuration
-
-Use `forRoot()` for static configuration:
-
-```typescript
-import { Module } from "@nestjs/common";
-import { TracewayModule } from "@tracewayapp/nestjs";
-
-@Module({
- imports: [
- TracewayModule.forRoot({
- connectionString: "your-token@https://traceway.example.com/api/report",
- debug: true,
- version: "1.0.0",
- serverName: "api-server-1",
- sampleRate: 1.0,
- errorSampleRate: 1.0,
- ignoredRoutes: ["/health", "/metrics"],
- onErrorRecording: ["url", "query", "body", "headers"],
- }),
- ],
-})
-export class AppModule {}
-```
-
-## Async Configuration
-
-Use `forRootAsync()` when you need to load configuration from environment variables or a config service:
-
-```typescript
-import { Module } from "@nestjs/common";
-import { ConfigModule, ConfigService } from "@nestjs/config";
-import { TracewayModule } from "@tracewayapp/nestjs";
-
-@Module({
- imports: [
- ConfigModule.forRoot(),
- TracewayModule.forRootAsync({
- imports: [ConfigModule],
- useFactory: (config: ConfigService) => ({
- connectionString: config.get("TRACEWAY_CONNECTION_STRING"),
- debug: config.get("NODE_ENV") !== "production",
- version: config.get("APP_VERSION"),
- serverName: config.get("HOSTNAME"),
- }),
- inject: [ConfigService],
- }),
- ],
-})
-export class AppModule {}
-```
-
-### Using useClass
-
-You can also use a factory class:
-
-```typescript
-import { Injectable } from "@nestjs/common";
-import { TracewayModule, TracewayOptionsFactory, TracewayModuleOptions } from "@tracewayapp/nestjs";
-
-@Injectable()
-class TracewayConfigService implements TracewayOptionsFactory {
- createTracewayOptions(): TracewayModuleOptions {
- return {
- connectionString: process.env.TRACEWAY_CONNECTION_STRING,
- debug: process.env.NODE_ENV !== "production",
- };
- }
-}
-
-@Module({
- imports: [
- TracewayModule.forRootAsync({
- useClass: TracewayConfigService,
- }),
- ],
-})
-export class AppModule {}
-```
-
-## Configuration Options
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `connectionString` | `string` | Required | Connection string in format `token@endpoint` |
-| `debug` | `boolean` | `false` | Enable debug logging |
-| `version` | `string` | `""` | Application version |
-| `serverName` | `string` | hostname | Server identifier |
-| `sampleRate` | `number` | `1.0` | Trace sampling rate (0-1) |
-| `errorSampleRate` | `number` | `1.0` | Error trace sampling rate (0-1) |
-| `ignoredRoutes` | `string[]` | `[]` | Routes to skip tracing |
-| `onErrorRecording` | `Array` | `[]` | Data to include with errors |
-
-### onErrorRecording Options
-
-When an exception is captured, you can include additional request data:
-
-| Value | Description |
-|-------|-------------|
-| `"url"` | Request URL path |
-| `"query"` | Query parameters as JSON |
-| `"body"` | Request body (JSON only, max 64KB) |
-| `"headers"` | Request headers (excludes Authorization and Cookie) |
-
-## Lifecycle
-
-- **Initialization**: Traceway is initialized when the module loads
-- **Shutdown**: Traceway flushes pending data and shuts down when the module is destroyed
-
-The module implements `OnModuleDestroy` to ensure graceful shutdown:
-
-```typescript
-async onModuleDestroy(): Promise<void> {
- await this.tracewayService.shutdownAsync();
-}
-```
-
-## Global Module
-
-`TracewayModule` is decorated with `@Global()`, so `TracewayService` is available for injection in any module without needing to import `TracewayModule` again.
diff --git a/docs/pages/client/nestjs/service.mdx b/docs/pages/client/nestjs/service.mdx
deleted file mode 100644
index a3bcae3f..00000000
--- a/docs/pages/client/nestjs/service.mdx
+++ /dev/null
@@ -1,234 +0,0 @@
-# TracewayService
-
-The `TracewayService` is an injectable service that provides methods for manual error capture, span creation, and trace attribute management.
-
-## Injection
-
-Inject `TracewayService` into any service or controller:
-
-```typescript
-import { Injectable } from "@nestjs/common";
-import { TracewayService } from "@tracewayapp/nestjs";
-
-@Injectable()
-export class UsersService {
- constructor(private readonly traceway: TracewayService) {}
-}
-```
-
-## Methods
-
-### captureException
-
-Capture an error with automatic trace context:
-
-```typescript
-captureException(error: Error): void
-```
-
-```typescript
-try {
- await this.externalApi.call();
-} catch (error) {
- this.traceway.captureException(error);
- throw error; // Re-throw or handle gracefully
-}
-```
-
-### captureExceptionWithAttributes
-
-Capture an error with custom attributes:
-
-```typescript
-captureExceptionWithAttributes(
- error: Error,
- attributes?: Record<string, string>,
- traceId?: string
-): void
-```
-
-```typescript
-this.traceway.captureExceptionWithAttributes(error, {
- userId: user.id,
- action: "checkout",
- cartTotal: String(cart.total),
-});
-```
-
-### captureMessage
-
-Capture an informational message:
-
-```typescript
-captureMessage(msg: string, attributes?: Record<string, string>): void
-```
-
-```typescript
-this.traceway.captureMessage("User completed onboarding", {
- userId: user.id,
- plan: user.plan,
-});
-```
-
-### startSpan / endSpan
-
-Create custom spans for timing operations:
-
-```typescript
-startSpan(name: string): SpanHandle
-endSpan(span: SpanHandle, addToContext?: boolean): void
-```
-
-```typescript
-async findUserWithOrders(userId: string) {
- const userSpan = this.traceway.startSpan("db.users.findOne");
- const user = await this.userRepository.findOne(userId);
- this.traceway.endSpan(userSpan);
-
- const ordersSpan = this.traceway.startSpan("db.orders.findByUser");
- const orders = await this.orderRepository.findByUser(userId);
- this.traceway.endSpan(ordersSpan);
-
- return { user, orders };
-}
-```
-
-### measureTask
-
-Measure a background task:
-
-```typescript
-measureTask(title: string, fn: () => void | Promise<void>): void
-```
-
-```typescript
-// Fire and forget background task
-this.traceway.measureTask("send-welcome-email", async () => {
- await this.emailService.sendWelcome(user.email);
-});
-```
-
-### setTraceAttribute / setTraceAttributes
-
-Add attributes to the current trace:
-
-```typescript
-setTraceAttribute(key: string, value: string): void
-setTraceAttributes(attributes: Record<string, string>): void
-```
-
-```typescript
-async handleRequest(userId: string, action: string) {
- // Single attribute
- this.traceway.setTraceAttribute("userId", userId);
-
- // Multiple attributes
- this.traceway.setTraceAttributes({
- action,
- timestamp: new Date().toISOString(),
- });
-}
-```
-
-### getTraceId
-
-Get the current trace ID:
-
-```typescript
-getTraceId(): string | undefined
-```
-
-```typescript
-async processOrder(order: Order) {
- const traceId = this.traceway.getTraceId();
-
- // Include trace ID in external API calls for correlation
- await this.fulfillmentApi.submit(order, {
- headers: { "X-Trace-ID": traceId },
- });
-}
-```
-
-### getTraceContext
-
-Get the full trace context:
-
-```typescript
-getTraceContext(): TraceContext | undefined
-```
-
-```typescript
-const ctx = this.traceway.getTraceContext();
-if (ctx) {
- console.log("Trace ID:", ctx.traceId);
- console.log("Endpoint:", ctx.endpoint);
- console.log("Spans:", ctx.spans.length);
-}
-```
-
-### withTraceContext
-
-Run a function within a new trace context:
-
-```typescript
-withTraceContext<T>(options: TraceContextOptions, fn: () => T): T
-```
-
-```typescript
-// Useful for background jobs or non-HTTP contexts
-this.traceway.withTraceContext(
- { endpoint: "cron.cleanup", isTask: true },
- async () => {
- await this.cleanupOldRecords();
- }
-);
-```
-
-## Example: Full Service
-
-```typescript
-import { Injectable } from "@nestjs/common";
-import { TracewayService, Span } from "@tracewayapp/nestjs";
-
-@Injectable()
-export class OrdersService {
- constructor(
- private readonly traceway: TracewayService,
- private readonly orderRepository: OrderRepository,
- private readonly paymentService: PaymentService,
- private readonly emailService: EmailService,
- ) {}
-
- @Span("orders.create")
- async createOrder(userId: string, items: OrderItem[]) {
- // Set trace attributes for debugging
- this.traceway.setTraceAttributes({
- userId,
- itemCount: String(items.length),
- });
-
- // Create order with span
- const orderSpan = this.traceway.startSpan("db.orders.create");
- const order = await this.orderRepository.create({ userId, items });
- this.traceway.endSpan(orderSpan);
-
- // Process payment
- const paymentSpan = this.traceway.startSpan("payment.process");
- try {
- await this.paymentService.charge(order.total);
- } catch (error) {
- this.traceway.captureException(error);
- throw error;
- } finally {
- this.traceway.endSpan(paymentSpan);
- }
-
- // Send confirmation email (background task)
- this.traceway.measureTask("email.order-confirmation", async () => {
- await this.emailService.sendOrderConfirmation(order);
- });
-
- return order;
- }
-}
-```
diff --git a/docs/pages/client/node-sdk/_meta.json b/docs/pages/client/node-sdk/_meta.json
index 985c511d..772acc0f 100644
--- a/docs/pages/client/node-sdk/_meta.json
+++ b/docs/pages/client/node-sdk/_meta.json
@@ -1,9 +1,5 @@
{
- "index": "Overview",
- "initialization": "Initialization",
- "exceptions": "Exceptions",
+ "index": "Quick Start",
"traces": "Traces",
- "spans": "Spans",
- "metrics": "Metrics",
- "tasks": "Tasks"
+ "metrics": "Metrics"
}
diff --git a/docs/pages/client/node-sdk/exceptions.mdx b/docs/pages/client/node-sdk/exceptions.mdx
deleted file mode 100644
index 31eb6524..00000000
--- a/docs/pages/client/node-sdk/exceptions.mdx
+++ /dev/null
@@ -1,191 +0,0 @@
-# Exceptions
-
-Capture Node.js errors and exceptions with full stack traces.
-
-## captureException
-
-Capture an error with its stack trace:
-
-```typescript
-import { captureException } from "@tracewayapp/backend";
-
-try {
- await riskyOperation();
-} catch (error) {
- captureException(error);
-}
-```
-
-The SDK extracts the error type, message, and stack trace automatically.
-
-## Trace Context Integration
-
-When called inside a trace context, exceptions are automatically linked to the current trace:
-
-```typescript
-import { captureException, withTraceContext } from "@tracewayapp/backend";
-
-await withTraceContext({ endpoint: "GET /api/users" }, async () => {
- try {
- await fetchUsers();
- } catch (error) {
- // This exception is automatically linked to the trace
- captureException(error);
- }
-});
-```
-
-## captureExceptionWithAttributes
-
-Capture an error with additional metadata:
-
-```typescript
-import { captureExceptionWithAttributes } from "@tracewayapp/backend";
-
-try {
- await processOrder(orderId);
-} catch (error) {
- captureExceptionWithAttributes(error, {
- orderId,
- userId: currentUser.id,
- action: "checkout",
- });
-}
-```
-
-Attributes appear as tags in the Traceway dashboard for filtering and debugging.
-
-## captureMessage
-
-Send a custom message (non-error):
-
-```typescript
-import { captureMessage } from "@tracewayapp/backend";
-
-// Log significant events
-captureMessage("Payment processed successfully");
-
-// With context
-captureMessage(`User ${userId} logged in from ${ipAddress}`);
-```
-
-Messages appear in the exceptions view but are marked as messages rather than errors.
-
-## Attribute Best Practices
-
-**Do include:**
-- User identifiers (anonymized if needed)
-- Request/transaction IDs
-- Relevant business context (order ID, product ID)
-- Feature flags or A/B test variants
-
-**Avoid including:**
-- Sensitive data (passwords, tokens, PII)
-- Large objects or arrays
-- Circular references
-
-## Error Handling Patterns
-
-### Express Error Middleware
-
-```typescript
-import { captureException } from "@tracewayapp/backend";
-
-app.use((err, req, res, next) => {
- captureException(err);
- res.status(500).json({ error: "Internal server error" });
-});
-```
-
-### Async/Await Pattern
-
-```typescript
-async function safeOperation() {
- try {
- return await riskyOperation();
- } catch (error) {
- captureException(error);
- throw error; // Re-throw if needed
- }
-}
-```
-
-### Promise Rejection Handler
-
-```typescript
-process.on("unhandledRejection", (reason) => {
- if (reason instanceof Error) {
- captureException(reason);
- }
-});
-```
-
-### Uncaught Exception Handler
-
-```typescript
-process.on("uncaughtException", (error) => {
- captureException(error);
- // Give time for the exception to be sent
- setTimeout(() => process.exit(1), 1000);
-});
-```
-
-## Stack Trace Formatting
-
-The SDK automatically formats Node.js stack traces, normalizing:
-
-- Absolute file paths to relative paths
-- Memory addresses
-- Node.js internal frames
-
-This ensures consistent grouping of identical errors across different environments.
-
-## Custom Error Types
-
-Custom error classes are fully supported:
-
-```typescript
-class ValidationError extends Error {
- constructor(
- message: string,
- public field: string,
- ) {
- super(message);
- this.name = "ValidationError";
- }
-}
-
-try {
- throw new ValidationError("Invalid email", "email");
-} catch (error) {
- captureExceptionWithAttributes(error, {
- field: error.field,
- });
-}
-```
-
-## Linking Exceptions to Traces
-
-Exceptions captured within a `withTraceContext` block are automatically linked:
-
-```typescript
-withTraceContext({ endpoint: "POST /api/orders" }, async () => {
- try {
- await createOrder(data);
- } catch (error) {
- // Linked to this trace via the trace ID
- captureException(error);
- throw error;
- }
-});
-```
-
-To manually link an exception to a trace:
-
-```typescript
-import { getTraceId, captureExceptionWithAttributes } from "@tracewayapp/backend";
-
-captureExceptionWithAttributes(error, {
- customAttribute: "value",
-}, getTraceId());
-```
diff --git a/docs/pages/client/node-sdk/index.mdx b/docs/pages/client/node-sdk/index.mdx
index 84bd537e..f82ce24c 100644
--- a/docs/pages/client/node-sdk/index.mdx
+++ b/docs/pages/client/node-sdk/index.mdx
@@ -1,139 +1,161 @@
-# Node.js Backend SDK
+# Node.js (OpenTelemetry)
-The `@tracewayapp/backend` package is a complete Node.js SDK for server-side applications. It provides error tracking, distributed tracing, span management, and metrics collection.
+Instrument any Node.js backend — Express, Fastify, Koa, Hono, NestJS, or plain HTTP — with OpenTelemetry and export traces and metrics to Traceway.
## Installation
```bash
-npm install @tracewayapp/backend
+npm install @opentelemetry/sdk-node \
+ @opentelemetry/auto-instrumentations-node \
+ @opentelemetry/exporter-trace-otlp-http \
+ @opentelemetry/exporter-metrics-otlp-http
```
-## Features
+## Setup
-| Feature | Description |
-|---------|-------------|
-| **Error Capture** | Capture exceptions and messages with full stack traces |
-| **Trace Context** | AsyncLocalStorage-based trace propagation across async operations |
-| **Span Management** | Time sub-operations within traces |
-| **Metrics** | Capture custom metrics and system metrics |
-| **Background Tasks** | Measure background jobs and async tasks |
-| **Sampling** | Configure sample rates for normal and error traces |
-
-## Quick Start
+Create an `instrumentation.ts` (or `.js`) file at the root of your project. This file must be loaded **before** your application code.
```typescript
-import {
- init,
- captureException,
- withTraceContext,
- startSpan,
- endSpan,
- captureCurrentTrace,
- shutdown,
-} from "@tracewayapp/backend";
-
-// Initialize once at startup
-init("your-token@https://traceway.example.com/api/report");
-
-// Use trace context for HTTP requests
-async function handleRequest(req, res) {
- await withTraceContext(
- {
- endpoint: `${req.method} ${req.path}`,
- clientIP: req.ip,
- },
- async () => {
- try {
- // Start a span for database work
- const dbSpan = startSpan("database-query");
- const users = await db.query("SELECT * FROM users");
- endSpan(dbSpan);
-
- res.json(users);
- } catch (error) {
- captureException(error);
- res.status(500).json({ error: "Internal error" });
- } finally {
- captureCurrentTrace();
- }
- }
- );
-}
-
-// Graceful shutdown
-process.on("SIGTERM", async () => {
- await shutdown();
- process.exit(0);
+import { NodeSDK } from "@opentelemetry/sdk-node";
+import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
+import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
+import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
+import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
+
+const sdk = new NodeSDK({
+ serviceName: "my-service",
+ serviceVersion: "1.0.0",
+
+ traceExporter: new OTLPTraceExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/traces",
+ headers: { Authorization: "Bearer your-project-token" },
+ }),
+
+ metricReader: new PeriodicExportingMetricReader({
+ exporter: new OTLPMetricExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/metrics",
+ headers: { Authorization: "Bearer your-project-token" },
+ }),
+ exportIntervalMillis: 30_000,
+ }),
+
+ instrumentations: [getNodeAutoInstrumentations()],
});
+
+sdk.start();
```
-## When to Use
+## Running Your App
-Use `@tracewayapp/backend` when:
+Load the instrumentation file before everything else using Node's `--require` (CommonJS) or `--import` (ESM) flag:
-- Building Node.js/Express/Fastify/Koa servers
-- Running background workers or task processors
-- Need distributed tracing across async operations
-- Want automatic trace context propagation
+```bash
+# CommonJS
+node --require ./instrumentation.js server.js
-For browser applications, use [`@tracewayapp/frontend`](/client/js-sdk) or framework-specific packages.
+# ESM / TypeScript (with tsx or ts-node)
+node --import ./instrumentation.ts server.ts
+```
-## Connection String Format
+Or set it via environment variable:
+```bash
+export NODE_OPTIONS="--require ./instrumentation.js"
+node server.js
```
-<project_token>@<server_url>/api/report
+
+## Environment Variable Alternative
+
+Instead of hardcoding the endpoint and token, you can use standard OTel environment variables:
+
+```bash
+export OTEL_SERVICE_NAME="my-service"
+export OTEL_EXPORTER_OTLP_ENDPOINT="https://your-traceway-instance.com/api/otel"
+export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
```
-Example:
+With these set, the SDK picks them up automatically — your `instrumentation.ts` can omit the exporter URLs and headers.
+
+## What Gets Auto-Instrumented
+
+The `@opentelemetry/auto-instrumentations-node` package automatically instruments:
+
+| Library | What's Captured |
+|---------|-----------------|
+| `http` / `https` | Incoming and outgoing HTTP requests |
+| `express` | Route-level spans with `http.route` |
+| `fastify` | Route-level spans |
+| `koa` | Middleware and route spans |
+| `hono` | HTTP request spans (via `http` instrumentation) |
+| `pg` / `mysql2` / `mongodb` | Database query spans |
+| `redis` / `ioredis` | Cache operation spans |
+| `grpc` | gRPC call spans |
+| `fs` | File system operation spans |
+
+Root SERVER spans become **Endpoints** in Traceway, child spans become **Spans**, and exception events become **Issues**. See [Traces](/client/otel/traces) for the full mapping.
+
+## Framework Quick Start
+
+### Express
+
+```typescript
+import express from "express";
+
+const app = express();
+
+app.get("/api/users", (req, res) => {
+ res.json({ users: [] });
+});
+
+app.listen(3000);
```
-abc123def456@https://traceway.example.com/api/report
+
+No extra code needed — auto-instrumentation captures all requests, routes, and database calls.
+
+### Fastify
+
+```typescript
+import Fastify from "fastify";
+
+const app = Fastify();
+
+app.get("/api/users", async () => {
+ return { users: [] };
+});
+
+app.listen({ port: 3000 });
```
-Find your connection string in the Traceway dashboard under **Project Settings**.
+### Hono
-## Exports
+See the dedicated [Hono guide](/client/hono) for multi-runtime setup.
```typescript
-// Core functions
-export { init, shutdown } from "@tracewayapp/backend";
-
-// Exception capture
-export { captureException, captureExceptionWithAttributes, captureMessage } from "@tracewayapp/backend";
-
-// Trace context (AsyncLocalStorage-based)
-export {
- withTraceContext,
- runWithTraceContext,
- getTraceContext,
- getTraceId,
- hasTraceContext,
- setTraceAttribute,
- setTraceAttributes,
- setTraceResponseInfo,
- forkTraceContext,
-} from "@tracewayapp/backend";
-
-// Trace capture
-export { captureCurrentTrace, captureTrace, captureTask } from "@tracewayapp/backend";
-
-// Span management
-export { startSpan, endSpan, addSpanToContext, getTraceSpans, getTraceDuration } from "@tracewayapp/backend";
-
-// Metrics
-export { captureMetric } from "@tracewayapp/backend";
-
-// Task measurement
-export { measureTask } from "@tracewayapp/backend";
-
-// Types
-export type { TracewayOptions, TraceContext, TraceContextOptions, SpanHandle } from "@tracewayapp/backend";
+import { serve } from "@hono/node-server";
+import { Hono } from "hono";
+
+const app = new Hono();
+
+app.get("/api/users", (c) => c.json({ users: [] }));
+
+serve({ fetch: app.fetch, port: 3000 });
```
+## Test Your Integration
+
+Add a route that throws an error:
+
+```typescript
+app.get("/test-error", () => {
+ throw new Error("Test error from Traceway integration");
+});
+```
+
+Visit `/test-error` and check your Traceway dashboard — the error should appear under **Issues** with a full stack trace.
+
## Next Steps
-- [Initialization](/client/node-sdk/initialization) — Configuration options and setup
-- [Exceptions](/client/node-sdk/exceptions) — Capturing errors and messages
-- [Traces](/client/node-sdk/traces) — Trace context management
-- [Spans](/client/node-sdk/spans) — Timing sub-operations
-- [Metrics](/client/node-sdk/metrics) — Custom and system metrics
-- [Tasks](/client/node-sdk/tasks) — Background task measurement
+- [Traces](/client/node-sdk/traces) — manual spans, exception recording, context propagation
+- [Metrics](/client/node-sdk/metrics) — custom counters, histograms, and gauges
+- [OTel Overview](/client/otel) — protocol details and authentication
+- [OTel Trace Mapping](/client/otel/traces) — how OTel spans map to Traceway concepts
diff --git a/docs/pages/client/node-sdk/initialization.mdx b/docs/pages/client/node-sdk/initialization.mdx
deleted file mode 100644
index c9dd47e6..00000000
--- a/docs/pages/client/node-sdk/initialization.mdx
+++ /dev/null
@@ -1,169 +0,0 @@
-# Initialization
-
-Initialize the SDK once at application startup, before capturing any events.
-
-## Basic Initialization
-
-```typescript
-import { init } from "@tracewayapp/backend";
-
-init("your-token@https://traceway.example.com/api/report");
-```
-
-## With Options
-
-```typescript
-import { init } from "@tracewayapp/backend";
-
-init("your-token@https://traceway.example.com/api/report", {
- debug: true,
- version: "1.2.3",
- sampleRate: 0.1,
- errorSampleRate: 1.0,
-});
-```
-
-## Options Reference
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `debug` | `boolean` | `false` | Log captured events to stdout |
-| `version` | `string` | `""` | Application version (shown in dashboard) |
-| `serverName` | `string` | Auto-detected | Server identifier (defaults to `os.hostname()`) |
-| `maxCollectionFrames` | `number` | `12` | Maximum frames in ring buffer before oldest are dropped |
-| `collectionInterval` | `number` | `5000` | Milliseconds between frame rotations |
-| `uploadThrottle` | `number` | `2000` | Milliseconds between upload attempts |
-| `metricsInterval` | `number` | `30000` | Milliseconds between system metrics collection |
-| `sampleRate` | `number` | `1.0` | Percentage of normal traces to record (0.0–1.0) |
-| `errorSampleRate` | `number` | `1.0` | Percentage of error traces to record (0.0–1.0) |
-
-## Ring Buffer Batching
-
-The SDK uses a ring buffer system for efficient data collection:
-
-1. **Collection** — Traces, exceptions, and metrics are collected into the current frame
-2. **Rotation** — After `collectionInterval` (default 5s), the frame rotates into the send queue
-3. **Upload** — Frames are gzip-compressed and sent to the backend
-4. **Cleanup** — Successfully uploaded frames are removed from the buffer
-
-If the backend is temporarily unreachable, frames remain in the buffer. At default settings (12 frames × 5s interval), roughly 60 seconds of data is buffered before the oldest frames are dropped.
-
-## Sampling
-
-Control what percentage of traces are recorded:
-
-```typescript
-init("your-token@...", {
- // Record 10% of normal traces
- sampleRate: 0.1,
- // Record all error traces (status >= 500)
- errorSampleRate: 1.0,
-});
-```
-
-A trace is considered an error when:
-- The HTTP status code is >= 500
-- An exception was captured within the trace
-
-## Server Name
-
-By default, the SDK uses `os.hostname()` as the server identifier. Override for custom identification:
-
-```typescript
-init("your-token@...", {
- serverName: "api-server-1",
-});
-```
-
-The server name appears in the dashboard, useful for debugging distributed systems.
-
-## Debug Mode
-
-Enable debug logging to see captured events:
-
-```typescript
-init("your-token@...", {
- debug: process.env.NODE_ENV === "development",
-});
-```
-
-Debug output includes:
-- Captured exceptions and messages
-- Trace capture events
-- Upload success/failure status
-
-## Single Initialization
-
-The SDK can only be initialized once. Calling `init()` a second time throws an error:
-
-```typescript
-init("token@url"); // OK
-init("token@url"); // Throws: "Traceway: already initialized. Call shutdown() first."
-```
-
-To reinitialize, first call `shutdown()`:
-
-```typescript
-import { init, shutdown } from "@tracewayapp/backend";
-
-init("token@url");
-// ... later ...
-await shutdown();
-init("new-token@url"); // OK
-```
-
-## Express Example
-
-```typescript
-import express from "express";
-import { init, shutdown } from "@tracewayapp/backend";
-
-const app = express();
-
-// Initialize before setting up routes
-init(process.env.TRACEWAY_CONNECTION!, {
- version: process.env.npm_package_version,
- debug: process.env.NODE_ENV === "development",
-});
-
-app.get("/api/users", async (req, res) => {
- // Your route handler
-});
-
-const server = app.listen(3000);
-
-// Graceful shutdown
-process.on("SIGTERM", async () => {
- await shutdown();
- server.close();
-});
-```
-
-## Environment Configuration
-
-Store your connection string in environment variables:
-
-```bash
-# .env
-TRACEWAY_CONNECTION=your-token@https://traceway.example.com/api/report
-```
-
-```typescript
-init(process.env.TRACEWAY_CONNECTION!);
-```
-
-## TypeScript
-
-Full TypeScript support is included:
-
-```typescript
-import { init, type TracewayOptions } from "@tracewayapp/backend";
-
-const options: TracewayOptions = {
- debug: true,
- version: "1.0.0",
- sampleRate: 0.5,
-};
-
-init("your-token@https://traceway.example.com/api/report", options);
-```
diff --git a/docs/pages/client/node-sdk/metrics.mdx b/docs/pages/client/node-sdk/metrics.mdx
index c4aa422d..d34d1c87 100644
--- a/docs/pages/client/node-sdk/metrics.mdx
+++ b/docs/pages/client/node-sdk/metrics.mdx
@@ -1,211 +1,104 @@
# Metrics
-See [Metrics concepts](/learn/metrics) for how metrics appear in the dashboard.
+Export custom application metrics from your Node.js app to Traceway using the OpenTelemetry Metrics API.
-Capture custom metrics to track application-specific values over time.
+## Setup
-## captureMetric
-
-Record a metric value:
-
-```typescript
-import { captureMetric } from "@tracewayapp/backend";
-
-// Capture a custom metric
-captureMetric("queue.length", 42);
-captureMetric("cache.hit_rate", 0.85);
-captureMetric("api.response_time_ms", 150);
-```
-
-Metrics are batched and sent with the next collection frame.
-
-## Metric Names
-
-Use dot-separated names for organization:
+Metrics export is configured in your `instrumentation.ts` via the `PeriodicExportingMetricReader`. If you followed the [Quick Start](/client/node-sdk), metrics are already enabled.
```typescript
-// Good naming
-captureMetric("orders.processed", count);
-captureMetric("orders.value_usd", totalValue);
-captureMetric("users.active", activeCount);
-captureMetric("cache.memory_mb", memoryUsage);
-
-// Bad naming
-captureMetric("processed", count); // Too vague
-captureMetric("orderCount", count); // Inconsistent style
+import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
+import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
+
+// In your NodeSDK config:
+metricReader: new PeriodicExportingMetricReader({
+ exporter: new OTLPMetricExporter({
+ url: "https://your-traceway-instance.com/api/otel/v1/metrics",
+ headers: { Authorization: "Bearer your-project-token" },
+ }),
+ exportIntervalMillis: 30_000,
+}),
```
-## Use Cases
+## Creating Custom Metrics
-### Business Metrics
+Use `@opentelemetry/api` to create meters and instruments:
```typescript
-// Track order processing
-captureMetric("orders.created", 1);
-captureMetric("orders.total_value", order.total);
+import { metrics } from "@opentelemetry/api";
-// Track user activity
-captureMetric("users.signups", 1);
-captureMetric("users.logins", 1);
+const meter = metrics.getMeter("my-service");
```
-### Performance Metrics
-
-```typescript
-// Track external API response times
-const start = Date.now();
-await externalApi.call();
-captureMetric("external.api_ms", Date.now() - start);
+## Metric Types
-// Track database query times
-captureMetric("db.query_ms", queryDuration);
-```
+### Counter
-### Resource Metrics
+Monotonically increasing value — use for counts of events:
```typescript
-// Track queue depth
-captureMetric("queue.pending", queue.length);
-
-// Track cache usage
-captureMetric("cache.entries", cache.size);
-captureMetric("cache.memory_mb", cache.memoryUsage / 1024 / 1024);
-```
-
-### Rate Metrics
-
-```typescript
-// Track success/failure rates
-captureMetric("payments.success", 1);
-captureMetric("payments.failed", 0);
+const requestCounter = meter.createCounter("app.requests.total", {
+ description: "Total number of requests",
+});
-// Track feature usage
-captureMetric("feature.dark_mode", user.darkModeEnabled ? 1 : 0);
+// Increment
+requestCounter.add(1, { endpoint: "/api/users", method: "GET" });
```
-## Periodic Metrics Collection
+### UpDownCounter
-For metrics that should be collected periodically:
+Value that can increase or decrease — use for gauges like active connections:
```typescript
-import { captureMetric } from "@tracewayapp/backend";
-
-// Collect queue metrics every 10 seconds
-setInterval(() => {
- captureMetric("queue.pending", jobQueue.length);
- captureMetric("queue.processing", activeJobs.size);
- captureMetric("queue.completed", completedJobs.count);
-}, 10000);
-```
-
-## System Metrics
-
-The SDK automatically collects system metrics when configured. These are collected at the `metricsInterval` (default: 30 seconds):
-
-| Metric | Description |
-|--------|-------------|
-| Memory usage | Process memory consumption |
-| CPU usage | Process CPU utilization |
-
-To customize the collection interval:
-
-```typescript
-import { init } from "@tracewayapp/backend";
-
-init("your-token@...", {
- metricsInterval: 60000, // Collect every 60 seconds
+const activeConnections = meter.createUpDownCounter("app.connections.active", {
+ description: "Number of active connections",
});
-```
-## Histogram Pattern
-
-For tracking distributions, capture individual values:
-
-```typescript
-// Track response times
-function trackResponseTime(durationMs: number) {
- captureMetric("http.response_time_ms", durationMs);
-}
-
-// The dashboard aggregates these into percentiles
+activeConnections.add(1); // connection opened
+activeConnections.add(-1); // connection closed
```
-## Counter Pattern
+### Histogram
-For counting events, increment by 1:
+Distribution of values — use for durations and sizes:
```typescript
-function trackOrder(order: Order) {
- captureMetric("orders.count", 1);
- captureMetric("orders.items", order.items.length);
- captureMetric("orders.value", order.total);
-}
-```
-
-## Gauge Pattern
-
-For point-in-time values:
+const requestDuration = meter.createHistogram("app.request.duration", {
+ description: "Request duration in milliseconds",
+ unit: "ms",
+});
-```typescript
-function reportQueueStatus() {
- captureMetric("queue.size", queue.length);
- captureMetric("queue.oldest_age_s", queue.oldestItemAge / 1000);
-}
+const start = performance.now();
+await handleRequest();
+requestDuration.record(performance.now() - start, {
+ endpoint: "/api/users",
+});
```
-## Express Metrics Middleware
-
-```typescript
-import { captureMetric } from "@tracewayapp/backend";
-
-app.use((req, res, next) => {
- const start = Date.now();
+### Observable Gauge
- res.on("finish", () => {
- const duration = Date.now() - start;
- captureMetric("http.request_ms", duration);
- captureMetric(`http.status.${res.statusCode}`, 1);
- });
+Asynchronously observed value — use for system metrics:
- next();
+```typescript
+meter.createObservableGauge("app.memory.heap_used", {
+ description: "Heap memory usage in bytes",
+ unit: "bytes",
+}).addCallback((result) => {
+ result.observe(process.memoryUsage().heapUsed);
});
```
-## Database Metrics
+## How Metrics Appear in Traceway
-```typescript
-import { captureMetric } from "@tracewayapp/backend";
-
-async function trackedQuery<T>(sql: string): Promise<T> {
- const start = Date.now();
- try {
- const result = await db.query(sql);
- captureMetric("db.query_ms", Date.now() - start);
- captureMetric("db.query_success", 1);
- return result;
- } catch (error) {
- captureMetric("db.query_ms", Date.now() - start);
- captureMetric("db.query_error", 1);
- throw error;
- }
-}
-```
+| OTel Type | Traceway Handling |
+|-----------|-------------------|
+| Gauge | Stored as-is |
+| Sum (Counter) | Stored as-is |
+| Histogram | Converted to `{name}.avg` and `{name}.count` |
-## Caching Metrics
+See [OTel Metrics](/client/otel/metrics) for full details on histogram handling and supported types.
-```typescript
-import { captureMetric } from "@tracewayapp/backend";
-
-async function cachedFetch<T>(key: string, fetchFn: () => Promise<T>): Promise<T> {
- const cached = await cache.get(key);
- if (cached) {
- captureMetric("cache.hit", 1);
- return cached;
- }
-
- captureMetric("cache.miss", 1);
- const value = await fetchFn();
- await cache.set(key, value);
- return value;
-}
-```
+## Next Steps
+
+- [Traces](/client/node-sdk/traces) — manual spans and exception recording
+- [Quick Start](/client/node-sdk) — setup and installation
diff --git a/docs/pages/client/node-sdk/spans.mdx b/docs/pages/client/node-sdk/spans.mdx
deleted file mode 100644
index 9e0e2f71..00000000
--- a/docs/pages/client/node-sdk/spans.mdx
+++ /dev/null
@@ -1,226 +0,0 @@
-# Spans
-
-Spans measure the duration of sub-operations within a trace. Use them to identify slow database queries, external API calls, or any operation you want to time.
-
-## startSpan / endSpan
-
-Start and end a span:
-
-```typescript
-import { startSpan, endSpan } from "@tracewayapp/backend";
-
-const span = startSpan("database-query");
-const users = await db.query("SELECT * FROM users");
-endSpan(span);
-```
-
-When called within a trace context, spans are automatically added to the trace.
-
-## SpanHandle
-
-`startSpan` returns a `SpanHandle` object:
-
-```typescript
-interface SpanHandle {
- id: string; // Unique span ID (UUID)
- name: string; // Span name
- startTime: string; // ISO timestamp
- startedAt: number; // Unix timestamp (ms)
-}
-```
-
-## Auto-Context Integration
-
-Spans are automatically added to the current trace context:
-
-```typescript
-import { withTraceContext, startSpan, endSpan, captureCurrentTrace } from "@tracewayapp/backend";
-
-await withTraceContext({ endpoint: "GET /api/users" }, async () => {
- const dbSpan = startSpan("db-query");
- const users = await db.query("SELECT * FROM users");
- endSpan(dbSpan);
-
- const cacheSpan = startSpan("cache-write");
- await cache.set("users", users);
- endSpan(cacheSpan);
-
- // Trace includes both spans
- captureCurrentTrace();
-});
-```
-
-## Disabling Auto-Add
-
-To end a span without adding it to the context:
-
-```typescript
-const span = startSpan("optional-operation");
-await doWork();
-const completedSpan = endSpan(span, false); // Second param disables auto-add
-```
-
-## Manual Span Addition
-
-Add a span to the context manually:
-
-```typescript
-import { addSpanToContext } from "@tracewayapp/backend";
-
-const span = {
- id: "custom-id",
- name: "external-api",
- startTime: new Date().toISOString(),
- duration: 150000000, // nanoseconds
-};
-
-addSpanToContext(span);
-```
-
-## Getting Trace Spans
-
-### getTraceSpans
-
-Get all spans from the current trace:
-
-```typescript
-import { getTraceSpans } from "@tracewayapp/backend";
-
-const spans = getTraceSpans();
-// Returns empty array if not in a trace context
-```
-
-## Nested Spans
-
-Spans can represent nested operations:
-
-```typescript
-await withTraceContext({ endpoint: "POST /api/orders" }, async () => {
- const orderSpan = startSpan("create-order");
-
- // Nested spans
- const validateSpan = startSpan("validate-items");
- await validateOrderItems(items);
- endSpan(validateSpan);
-
- const inventorySpan = startSpan("check-inventory");
- await checkInventory(items);
- endSpan(inventorySpan);
-
- const paymentSpan = startSpan("process-payment");
- await processPayment(paymentInfo);
- endSpan(paymentSpan);
-
- endSpan(orderSpan);
- captureCurrentTrace();
-});
-```
-
-## Error Handling
-
-Always end spans, even on error:
-
-```typescript
-const span = startSpan("risky-operation");
-try {
- await riskyOperation();
-} finally {
- endSpan(span);
-}
-```
-
-Or use a helper:
-
-```typescript
-async function withSpan<T>(name: string, fn: () => Promise<T>): Promise<T> {
- const span = startSpan(name);
- try {
- return await fn();
- } finally {
- endSpan(span);
- }
-}
-
-// Usage
-const users = await withSpan("database-query", () =>
- db.query("SELECT * FROM users")
-);
-```
-
-## Span Naming Conventions
-
-Use descriptive names that indicate the operation type:
-
-| Good | Bad |
-|------|-----|
-| `db-query-users` | `query` |
-| `redis-cache-get` | `cache` |
-| `stripe-api-charge` | `api` |
-| `s3-upload-image` | `upload` |
-| `kafka-publish-event` | `publish` |
-
-## Database Wrapper Example
-
-```typescript
-import { startSpan, endSpan } from "@tracewayapp/backend";
-
-class TracedDatabase {
- constructor(private db: Database) {}
-
- async query<T>(sql: string, params?: unknown[]): Promise<T> {
- const span = startSpan("db-query");
- try {
- return await this.db.query(sql, params);
- } finally {
- endSpan(span);
- }
- }
-
- async transaction<T>(fn: (tx: Transaction) => Promise<T>): Promise<T> {
- const span = startSpan("db-transaction");
- try {
- return await this.db.transaction(fn);
- } finally {
- endSpan(span);
- }
- }
-}
-```
-
-## HTTP Client Wrapper Example
-
-```typescript
-import { startSpan, endSpan } from "@tracewayapp/backend";
-
-async function tracedFetch(url: string, options?: RequestInit): Promise<Response> {
- const span = startSpan(`fetch-${new URL(url).hostname}`);
- try {
- return await fetch(url, options);
- } finally {
- endSpan(span);
- }
-}
-```
-
-## Parallel Operations with Forked Context
-
-When running parallel operations, use `forkTraceContext` to isolate spans:
-
-```typescript
-import { forkTraceContext, startSpan, endSpan } from "@tracewayapp/backend";
-
-await Promise.all([
- forkTraceContext(async () => {
- const span = startSpan("fetch-users");
- await fetchUsers();
- endSpan(span);
- }),
- forkTraceContext(async () => {
- const span = startSpan("fetch-orders");
- await fetchOrders();
- endSpan(span);
- }),
-]);
-```
-
-Without forking, spans from parallel operations might interleave unpredictably.
diff --git a/docs/pages/client/node-sdk/tasks.mdx b/docs/pages/client/node-sdk/tasks.mdx
deleted file mode 100644
index 867c92fd..00000000
--- a/docs/pages/client/node-sdk/tasks.mdx
+++ /dev/null
@@ -1,240 +0,0 @@
-# Tasks
-
-Measure background tasks and async jobs with automatic timing and error capture.
-
-## measureTask
-
-Measure a synchronous or async function:
-
-```typescript
-import { measureTask } from "@tracewayapp/backend";
-
-// Async function
-measureTask("send-welcome-emails", async () => {
- await sendWelcomeEmails();
-});
-
-// Sync function
-measureTask("process-batch", () => {
- processBatch(items);
-});
-```
-
-`measureTask` automatically:
-- Generates a unique trace ID
-- Records start/end times
-- Captures exceptions if the task fails
-- Applies sampling rules
-
-## Task vs Trace
-
-Tasks are traces marked with `isTask: true`. They appear in a separate "Tasks" section in the dashboard, keeping them distinct from HTTP requests.
-
-| Aspect | HTTP Traces | Tasks |
-|--------|-------------|-------|
-| Endpoint | `"GET /api/users"` | `"process-emails"` |
-| Status code | 200, 500, etc. | Always 0 |
-| Client IP | Request IP | Empty |
-| Dashboard | Endpoints view | Tasks view |
-
-## Error Handling
-
-If a task throws, the error is captured and re-thrown:
-
-```typescript
-measureTask("risky-task", async () => {
- throw new Error("Task failed");
-});
-// Error is captured to Traceway, then re-thrown
-```
-
-## Sampling
-
-Tasks respect the configured sample rates:
-
-```typescript
-import { init } from "@tracewayapp/backend";
-
-init("your-token@...", {
- sampleRate: 0.1, // 10% of successful tasks
- errorSampleRate: 1.0, // 100% of failed tasks
-});
-```
-
-## captureTask
-
-Capture a task with explicit parameters:
-
-```typescript
-import { captureTask } from "@tracewayapp/backend";
-
-const traceId = crypto.randomUUID();
-const startedAt = new Date();
-
-await doWork();
-
-const durationMs = Date.now() - startedAt.getTime();
-
-captureTask(
- traceId,
- "background-job", // task name
- durationMs,
- startedAt,
- { jobId: "123" }, // attributes (optional)
- spans, // spans array (optional)
-);
-```
-
-## withTraceContext for Tasks
-
-For more control, use `withTraceContext` with `isTask: true`:
-
-```typescript
-import {
- withTraceContext,
- startSpan,
- endSpan,
- setTraceAttribute,
- captureCurrentTrace,
- captureException,
-} from "@tracewayapp/backend";
-
-await withTraceContext(
- { isTask: true, endpoint: "sync-inventory" },
- async () => {
- try {
- setTraceAttribute("batchSize", items.length.toString());
-
- const fetchSpan = startSpan("fetch-inventory");
- const inventory = await fetchInventory();
- endSpan(fetchSpan);
-
- const updateSpan = startSpan("update-database");
- await updateDatabase(inventory);
- endSpan(updateSpan);
- } catch (error) {
- captureException(error);
- throw error;
- } finally {
- captureCurrentTrace();
- }
- }
-);
-```
-
-## Cron Job Example
-
-```typescript
-import { measureTask } from "@tracewayapp/backend";
-import cron from "node-cron";
-
-// Run every hour
-cron.schedule("0 * * * *", () => {
- measureTask("hourly-cleanup", async () => {
- await cleanupExpiredSessions();
- await archiveOldRecords();
- await sendPendingNotifications();
- });
-});
-```
-
-## Queue Worker Example
-
-```typescript
-import { measureTask, captureException } from "@tracewayapp/backend";
-
-queue.process("email", async (job) => {
- await measureTask(`email:${job.data.type}`, async () => {
- await sendEmail(job.data);
- });
-});
-```
-
-## Bull Queue Example
-
-```typescript
-import { withTraceContext, captureCurrentTrace, setTraceAttribute } from "@tracewayapp/backend";
-import Bull from "bull";
-
-const emailQueue = new Bull("email");
-
-emailQueue.process(async (job) => {
- return withTraceContext(
- { isTask: true, endpoint: `email:${job.data.type}` },
- async () => {
- setTraceAttribute("jobId", job.id.toString());
- setTraceAttribute("emailType", job.data.type);
-
- await sendEmail(job.data);
-
- captureCurrentTrace();
- }
- );
-});
-```
-
-## Periodic Tasks
-
-```typescript
-import { measureTask } from "@tracewayapp/backend";
-
-// Run every 5 minutes
-setInterval(() => {
- measureTask("health-check", async () => {
- await checkDatabaseConnection();
- await checkCacheConnection();
- await checkExternalApis();
- });
-}, 5 * 60 * 1000);
-```
-
-## Batch Processing
-
-```typescript
-import { measureTask, captureMetric } from "@tracewayapp/backend";
-
-async function processBatch(items: Item[]) {
- await measureTask("process-batch", async () => {
- let processed = 0;
- let failed = 0;
-
- for (const item of items) {
- try {
- await processItem(item);
- processed++;
- } catch (error) {
- failed++;
- // Individual errors are logged but don't fail the batch
- }
- }
-
- captureMetric("batch.processed", processed);
- captureMetric("batch.failed", failed);
- });
-}
-```
-
-## Long-Running Tasks
-
-For long-running tasks, consider capturing intermediate progress:
-
-```typescript
-import { withTraceContext, setTraceAttribute, captureCurrentTrace } from "@tracewayapp/backend";
-
-await withTraceContext(
- { isTask: true, endpoint: "data-migration" },
- async () => {
- const total = await countRecords();
- let processed = 0;
-
- for await (const batch of getBatches()) {
- await processBatch(batch);
- processed += batch.length;
-
- setTraceAttribute("progress", `${processed}/${total}`);
- }
-
- captureCurrentTrace();
- }
-);
-```
diff --git a/docs/pages/client/node-sdk/traces.mdx b/docs/pages/client/node-sdk/traces.mdx
index 9edd2983..7f85a8c8 100644
--- a/docs/pages/client/node-sdk/traces.mdx
+++ b/docs/pages/client/node-sdk/traces.mdx
@@ -1,328 +1,120 @@
# Traces
-The backend SDK provides AsyncLocalStorage-based trace context management. Trace context automatically propagates through async operations, allowing you to link exceptions, spans, and attributes to the current trace.
+OpenTelemetry auto-instrumentation handles most tracing automatically. This page covers manual span creation and exception recording for cases where you need more control.
-## withTraceContext
+## How Spans Map to Traceway
-Run a function within a new trace context:
+| OTel Span | Traceway Concept |
+|-----------|-----------------|
+| Root SERVER span with HTTP attributes | **Endpoint** (e.g., `GET /api/users`) |
+| Root span (other kinds) | **Task** |
+| Child span | **Span** |
+| Exception event on any span | **Issue** |
-```typescript
-import { withTraceContext, captureCurrentTrace } from "@tracewayapp/backend";
-
-await withTraceContext(
- {
- endpoint: "GET /api/users",
- clientIP: req.ip,
- },
- async () => {
- // All async operations here share the same trace context
- const users = await db.query("SELECT * FROM users");
- res.json(users);
-
- // Capture the trace when done
- captureCurrentTrace();
- }
-);
-```
-
-### TraceContextOptions
+See [OTel Trace Mapping](/client/otel/traces) for full details on attributes and conventions.
-| Option | Type | Required | Description |
-|--------|------|----------|-------------|
-| `endpoint` | `string` | No | Endpoint name (e.g., "GET /api/users") |
-| `traceId` | `string` | No | Custom trace ID (auto-generated if not provided) |
-| `isTask` | `boolean` | No | Mark as background task instead of HTTP trace |
-| `attributes` | `Record<string, string>` | No | Initial trace attributes |
-| `clientIP` | `string` | No | Client IP address for HTTP traces |
-| `distributedTraceId` | `string` | No | Distributed trace ID from an incoming `traceway-trace-id` header (for frontend ↔ backend correlation) |
+## Manual Span Creation
-## Reading Trace Context
-
-### getTraceContext
-
-Get the full trace context object:
+Use `@opentelemetry/api` to create custom spans for operations that aren't auto-instrumented:
```typescript
-import { getTraceContext } from "@tracewayapp/backend";
-
-const ctx = getTraceContext();
-if (ctx) {
- console.log("Trace ID:", ctx.traceId);
- console.log("Endpoint:", ctx.endpoint);
- console.log("Spans:", ctx.spans.length);
+import { trace, SpanStatusCode } from "@opentelemetry/api";
+
+const tracer = trace.getTracer("my-service");
+
+async function processOrder(orderId: string) {
+ return tracer.startActiveSpan("process-order", async (span) => {
+ try {
+ span.setAttribute("order.id", orderId);
+
+ await validateOrder(orderId);
+ await chargePayment(orderId);
+ await sendConfirmation(orderId);
+
+ span.setStatus({ code: SpanStatusCode.OK });
+ } catch (error) {
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
+ span.recordException(error);
+ throw error;
+ } finally {
+ span.end();
+ }
+ });
}
```
-### getTraceId
+## Nested Spans
-Get just the current trace ID:
+Spans created inside an active span are automatically linked as children:
```typescript
-import { getTraceId } from "@tracewayapp/backend";
-
-const traceId = getTraceId();
-// Returns undefined if not in a trace context
-```
-
-### hasTraceContext
-
-Check if currently within a trace context:
-
-```typescript
-import { hasTraceContext } from "@tracewayapp/backend";
-
-if (hasTraceContext()) {
- // Safe to use trace-related functions
+async function chargePayment(orderId: string) {
+ return tracer.startActiveSpan("charge-payment", async (span) => {
+ try {
+ const result = await paymentGateway.charge(orderId);
+ span.setAttribute("payment.status", result.status);
+ return result;
+ } finally {
+ span.end();
+ }
+ });
}
```
-## Setting Attributes
-
-### setTraceAttribute
-
-Set a single attribute on the current trace:
-
-```typescript
-import { setTraceAttribute } from "@tracewayapp/backend";
-
-setTraceAttribute("userId", currentUser.id);
-setTraceAttribute("tenantId", tenant.id);
-```
-
-### setTraceAttributes
-
-Set multiple attributes at once:
-
-```typescript
-import { setTraceAttributes } from "@tracewayapp/backend";
-
-setTraceAttributes({
- userId: currentUser.id,
- tenantId: tenant.id,
- plan: subscription.plan,
-});
-```
-
-Attributes are no-op when called outside a trace context.
+## Recording Exceptions
-## HTTP Response Info
-
-### setTraceResponseInfo
-
-Set HTTP response information for the trace:
+Exceptions recorded as span events appear as **Issues** in Traceway:
```typescript
-import { setTraceResponseInfo, withTraceContext, captureCurrentTrace } from "@tracewayapp/backend";
-
-await withTraceContext({ endpoint: "GET /api/users" }, async () => {
- // ... handle request ...
+import { trace, SpanStatusCode } from "@opentelemetry/api";
- // Set response info before capturing
- setTraceResponseInfo(200, responseBody.length);
- captureCurrentTrace();
-});
-```
-
-## Capturing Traces
-
-### captureCurrentTrace
-
-Capture the current trace context as a trace record:
-
-```typescript
-import { captureCurrentTrace, withTraceContext, setTraceResponseInfo } from "@tracewayapp/backend";
-
-await withTraceContext({ endpoint: "POST /api/orders" }, async () => {
- const result = await createOrder(data);
-
- setTraceResponseInfo(201, JSON.stringify(result).length);
- captureCurrentTrace(); // Records the trace with all spans and attributes
-});
-```
+function riskyOperation() {
+ const span = trace.getActiveSpan();
-### captureTrace (Manual)
-
-Capture a trace with explicit parameters:
-
-```typescript
-import { captureTrace } from "@tracewayapp/backend";
-
-captureTrace(
- traceId, // string
- "GET /api/users", // endpoint
- 45.2, // duration in ms
- new Date(), // start time
- 200, // status code
- 1024, // body size
- "192.168.1.1", // client IP
- { userId: "123" }, // attributes (optional)
- spans, // spans array (optional)
-);
+ try {
+ doSomethingDangerous();
+ } catch (error) {
+ if (span) {
+ span.recordException(error);
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
+ }
+ throw error;
+ }
+}
```
-## Forking Trace Context
+The `recordException` call adds an event with `exception.type`, `exception.message`, and `exception.stacktrace` attributes. Traceway normalizes and hashes the stack trace to group identical errors into a single Issue.
-### forkTraceContext
+## Span Attributes
-Fork the current context for parallel operations with isolated spans:
+Add attributes to enrich your spans with context:
```typescript
-import { forkTraceContext, withTraceContext, startSpan, endSpan } from "@tracewayapp/backend";
-
-await withTraceContext({ endpoint: "GET /api/dashboard" }, async () => {
- // Run multiple operations in parallel, each with isolated spans
- await Promise.all([
- forkTraceContext(async () => {
- const span = startSpan("fetch-users");
- await fetchUsers();
- endSpan(span);
- }),
- forkTraceContext(async () => {
- const span = startSpan("fetch-metrics");
- await fetchMetrics();
- endSpan(span);
- }),
- ]);
-
- // All spans are merged back to the parent context
- captureCurrentTrace();
+span.setAttribute("user.id", userId);
+span.setAttribute("db.statement", "SELECT * FROM users");
+span.setAttributes({
+ "order.id": orderId,
+ "order.total": 99.99,
+ "order.items": 3,
});
```
-Forked contexts:
-- Share the same trace ID as the parent
-- Get their own isolated span list
-- Inherit parent attributes
-- Merge spans back to parent when complete
+## Context Propagation
-## Trace Duration
-
-### getTraceDuration
-
-Get elapsed time since trace started:
+OTel automatically propagates trace context across async operations. For manual propagation across service boundaries, use the `W3C Trace Context` headers:
```typescript
-import { getTraceDuration } from "@tracewayapp/backend";
+import { propagation, context } from "@opentelemetry/api";
-const elapsedMs = getTraceDuration();
-// Returns 0 if not in a trace context
-```
+// Inject trace context into outgoing request headers
+const headers = {};
+propagation.inject(context.active(), headers);
-## Distributed Tracing
-
-### getDistributedTraceId
-
-Get the distributed trace ID from the current trace context:
-
-```typescript
-import { getDistributedTraceId } from "@tracewayapp/backend";
-
-const distributedId = getDistributedTraceId();
-// Returns undefined if no distributed trace ID is set
+// The headers now contain `traceparent` and optionally `tracestate`
+await fetch("https://other-service.com/api", { headers });
```
-### Express Middleware with Distributed Tracing
-
-When building a custom Express middleware, read the `traceway-trace-id` header and pass it into the trace context to enable frontend ↔ backend correlation:
-
-```typescript
-import {
- withTraceContext,
- setTraceAttribute,
- setTraceResponseInfo,
- captureCurrentTrace,
- captureException,
-} from "@tracewayapp/backend";
-
-function tracingMiddleware(req, res, next) {
- const distributedTraceId = req.headers["traceway-trace-id"];
-
- if (distributedTraceId) {
- res.setHeader("traceway-trace-id", distributedTraceId);
- }
-
- withTraceContext(
- {
- endpoint: `${req.method} ${req.path}`,
- clientIP: req.ip,
- distributedTraceId,
- },
- async () => {
- if (req.user) {
- setTraceAttribute("userId", req.user.id);
- }
-
- res.on("finish", () => {
- setTraceResponseInfo(res.statusCode, res.get("content-length") || 0);
- captureCurrentTrace();
- });
-
- try {
- await next();
- } catch (error) {
- captureException(error);
- throw error;
- }
- }
- );
-}
-```
-
-See the [JS SDK Distributed Tracing](/client/js-sdk/distributed-tracing) guide for frontend setup details.
-
-## Express Middleware Example (Basic)
-
-```typescript
-import {
- withTraceContext,
- setTraceAttribute,
- setTraceResponseInfo,
- captureCurrentTrace,
- captureException,
-} from "@tracewayapp/backend";
-
-function tracingMiddleware(req, res, next) {
- withTraceContext(
- {
- endpoint: `${req.method} ${req.path}`,
- clientIP: req.ip,
- },
- async () => {
- if (req.user) {
- setTraceAttribute("userId", req.user.id);
- }
-
- res.on("finish", () => {
- setTraceResponseInfo(res.statusCode, res.get("content-length") || 0);
- captureCurrentTrace();
- });
-
- try {
- await next();
- } catch (error) {
- captureException(error);
- throw error;
- }
- }
- );
-}
-```
-
-## Background Tasks
-
-For background tasks, set `isTask: true`:
-
-```typescript
-await withTraceContext(
- {
- isTask: true,
- endpoint: "process-emails",
- },
- async () => {
- await processEmails();
- captureCurrentTrace();
- }
-);
-```
+## Next Steps
-Tasks appear separately from HTTP traces in the dashboard.
+- [Metrics](/client/node-sdk/metrics) — custom counters, histograms, and gauges
+- [Quick Start](/client/node-sdk) — setup and installation
diff --git a/docs/pages/client/otel/index.mdx b/docs/pages/client/otel/index.mdx
index 6e240b32..a9f5b873 100644
--- a/docs/pages/client/otel/index.mdx
+++ b/docs/pages/client/otel/index.mdx
@@ -20,7 +20,7 @@ Any language with an OTel SDK can export to Traceway. Here are the most common o
| Python | [opentelemetry-python](https://github.com/open-telemetry/opentelemetry-python) | `pip install opentelemetry-sdk` |
| C# / .NET | [opentelemetry-dotnet](https://github.com/open-telemetry/opentelemetry-dotnet) | `dotnet add package OpenTelemetry` |
| Go | [opentelemetry-go](https://github.com/open-telemetry/opentelemetry-go) | `go get go.opentelemetry.io/otel` |
-| Node.js | [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js) | `npm install @opentelemetry/sdk-node` |
+| Node.js | [opentelemetry-js](https://github.com/open-telemetry/opentelemetry-js) | `npm install @opentelemetry/sdk-node` — see [Node.js guide](/client/node-sdk), [NestJS guide](/client/nestjs), [Hono guide](/client/hono) |
| PHP / Symfony | [opentelemetry-php](https://github.com/open-telemetry/opentelemetry-php) | `composer require open-telemetry/sdk` — see [Symfony guide](/client/symfony) |
| Cloudflare Workers | [workers-sdk](https://developers.cloudflare.com/workers/observability/otel/) | Built-in — see [Cloudflare guide](/client/otel-cloudflare) |
diff --git a/docs/public/hono.png b/docs/public/hono.png
new file mode 100644
index 00000000..efdc9fd0
Binary files /dev/null and b/docs/public/hono.png differ
diff --git a/frontend/src/lib/components/framework-combobox.svelte b/frontend/src/lib/components/framework-combobox.svelte
index 94fbf1c9..74d340c5 100644
--- a/frontend/src/lib/components/framework-combobox.svelte
+++ b/frontend/src/lib/components/framework-combobox.svelte
@@ -30,12 +30,9 @@
{ value: 'react', label: 'React', description: 'Frontend UI library', group: 'JavaScript' },
{ value: 'svelte', label: 'Svelte', description: 'Frontend compiler framework', group: 'JavaScript' },
{ value: 'vuejs', label: 'Vue.js', description: 'Progressive frontend framework', group: 'JavaScript' },
- { value: 'nextjs', label: 'Next.js', description: 'React full-stack framework', group: 'JavaScript' },
- { value: 'nestjs', label: 'NestJS', description: 'Node.js server framework', group: 'JavaScript' },
- { value: 'express', label: 'Express', description: 'Minimal Node.js framework', group: 'JavaScript' },
- { value: 'remix', label: 'Remix', description: 'React full-stack framework', group: 'JavaScript' },
{ value: 'jquery', label: 'jQuery', description: 'Legacy-friendly AJAX and DOM library', group: 'JavaScript' },
{ value: 'symfony', label: 'Symfony', description: 'PHP full-stack framework (OTLP)', group: 'PHP' },
+ { value: 'hono', label: 'Hono', description: 'Lightweight multi-runtime framework (OTLP)', group: 'Backend' },
{ value: 'cloudflare', label: 'Cloudflare', description: 'Cloudflare Workers (OTLP Traces)', group: 'Backend' },
{ value: 'opentelemetry', label: 'OpenTelemetry', description: 'Vendor-neutral observability', group: 'Backend' },
] as const;
diff --git a/frontend/src/lib/components/framework-icon.svelte b/frontend/src/lib/components/framework-icon.svelte
index 57c5dd46..ba687d3b 100644
--- a/frontend/src/lib/components/framework-icon.svelte
+++ b/frontend/src/lib/components/framework-icon.svelte
@@ -48,6 +48,8 @@
<img src="/remix.png" alt="Remix" class={className} />
{:else if framework === 'jquery'}
<img src="/jquery.png" alt="jQuery" class={className} />
+{:else if framework === 'hono'}
+ <img src="/hono.png" alt="Hono" class={className} />
{:else if framework === 'cloudflare'}
<img src="/cloudflare.png" alt="Cloudflare" class={className} />
{:else if framework === 'opentelemetry'}
diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.ts
index b12bbf5e..2dd8e283 100644
--- a/frontend/src/lib/state/projects.svelte.ts
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -1,7 +1,7 @@
import { api } from '$lib/api';
import { authState } from './auth.svelte';
-export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'cloudflare' | 'opentelemetry' | 'symfony';
+export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom' | 'react' | 'svelte' | 'vuejs' | 'nextjs' | 'nestjs' | 'express' | 'remix' | 'jquery' | 'hono' | 'cloudflare' | 'opentelemetry' | 'symfony';
export const FRONTEND_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'jquery'];
export const JS_FRAMEWORKS: Framework[] = ['react', 'svelte', 'vuejs', 'nextjs', 'nestjs', 'express', 'remix', 'jquery'];
@@ -21,6 +21,7 @@ export const FRAMEWORK_LABELS: Record<Framework, string> = {
express: 'Express',
remix: 'Remix',
jquery: 'jQuery',
+ hono: 'Hono',
cloudflare: 'Cloudflare',
opentelemetry: 'OpenTelemetry',
symfony: 'Symfony',
@@ -39,7 +40,7 @@ export function isJsFramework(fw: Framework): boolean {
}
export function isOtelFramework(fw: Framework): boolean {
- return fw === 'opentelemetry';
+ return fw === 'opentelemetry' || fw === 'hono';
}
export function isCloudflareFramework(fw: Framework): boolean {
diff --git a/frontend/src/lib/utils/framework-code.ts b/frontend/src/lib/utils/framework-code.ts
index 8fd5452d..2341f93d 100644
--- a/frontend/src/lib/utils/framework-code.ts
+++ b/frontend/src/lib/utils/framework-code.ts
@@ -30,6 +30,8 @@ export function getInstallCommand(framework: Framework): string {
return 'npm install @tracewayapp/remix';
case 'jquery':
return 'npm install @tracewayapp/jquery';
+ case 'hono':
+ return '';
case 'symfony':
return 'composer require traceway/opentelemetry-symfony open-telemetry/exporter-otlp php-http/guzzle7-adapter';
case 'cloudflare':
@@ -273,6 +275,9 @@ $response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);`;
+ case 'hono':
+ return '';
+
case 'cloudflare':
return '';
@@ -391,6 +396,7 @@ export function getFrameworkLabel(framework: Framework): string {
express: 'Express',
remix: 'Remix',
jquery: 'jQuery',
+ hono: 'Hono',
cloudflare: 'Cloudflare',
opentelemetry: 'OpenTelemetry',
symfony: 'Symfony',
@@ -401,6 +407,7 @@ export function getFrameworkLabel(framework: Framework): string {
export function getCodeLanguage(framework: Framework): 'go' | 'javascript' | 'bash' | 'php' {
if (framework === 'symfony') return 'php';
if (framework === 'opentelemetry') return 'go';
+ if (framework === 'hono') return 'javascript';
if (framework === 'cloudflare') return 'javascript';
return isJsFramework(framework) ? 'javascript' : 'go';
}
diff --git a/frontend/static/hono.png b/frontend/static/hono.png
new file mode 100644
index 00000000..efdc9fd0
Binary files /dev/null and b/frontend/static/hono.png differ