---
title: "Node.js"
description: "A batching sender for Node.js 18+ with no dependencies."
canonical_url: "https://docs.logstrace.dev/guides/integrations/nodejs"
---
# Node.js

> A batching sender for Node.js 18+ with no dependencies.

```ts [logstrace.ts]
type Level = 'debug' | 'info' | 'warn' | 'error' | 'fatal'
type LogEvent = { text: string, channel?: string, level?: Level, data?: Record<string, unknown>, traceId?: string, ts?: number }

const URL = 'https://logstrace.dev/api/ingest'
const KEY = process.env.LOGSTRACE_KEY!
let queue: LogEvent[] = []
let timer: NodeJS.Timeout | undefined

async function flush() {
  clearTimeout(timer)
  timer = undefined
  const events = queue.splice(0, 500)
  if (!events.length) return
  try {
    const res = await fetch(URL, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${KEY}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ events }),
      signal: AbortSignal.timeout(5000)
    })
    if (res.status === 429 || res.status >= 500) queue.unshift(...events) // retry next flush
  }
  catch {
    queue.unshift(...events)
  }
  if (queue.length > 10_000) queue = queue.slice(-10_000) // never grow without bound
  if (queue.length) schedule()
}

function schedule() {
  timer ??= setTimeout(flush, 1000)
}

export function log(channel: string, level: Level, text: string, extra: Omit<LogEvent, 'text' | 'channel' | 'level'> = {}) {
  queue.push({ channel, level, text, ts: Date.now(), ...extra })
  if (queue.length >= 200) void flush()
  else schedule()
}

process.on('beforeExit', () => void flush())
```

```ts
import { log } from './logstrace'

log('orders', 'info', `Order ${order.id} paid ${order.total} ${order.currency} by ${order.method}`)
log('payments', 'error', `Payment ${p.id} failed`, { data: { reason: err.message }, traceId: req.id })
```

## Using pino or winston

LogsTrace accepts their field names (`msg`, `message`, `time`, `timestamp`, numeric or named `level`), so you can forward their JSON records unchanged: push each parsed record into the queue above instead of building a new event.


## Sitemap

See the full [sitemap](https://docs.logstrace.dev/sitemap.md) for all pages.
