---
title: "Express"
description: "One `app.use(evlog())` puts a request logger on `req.log`, emits the wide event when the response finishes, and feeds your error handler."
canonical_url: "https://www.evlog.dev/integrate/frameworks/express"
---
# Express

> One `app.use(evlog())` puts a request logger on `req.log`, emits the wide event when the response finishes, and feeds your error handler.

The `evlog/express` middleware auto-creates a request-scoped logger on `req.log` and emits a wide event when the response finishes.

<prompt :actions="["copy","cursor","claude"]" description="Set up evlog in my Express app" icon="i-simple-icons-express">

Set up evlog in my Express app.

- Install evlog: pnpm add evlog
- Create evlog.config.ts with export default defineEvlog({ service: 'my-api' })
- Call initLogger(toLoggerConfig(config)) at startup, importing config from evlog.config.ts
- Import evlog middleware from 'evlog/express' and add app.use(evlog(toMiddlewareOptions(config)))
- Access the logger via req.log in routes or useLogger() anywhere in the call stack
- Use log.set() to accumulate context, throw createError() for structured errors
- Put drain, enrich, include and keep in evlog.config.ts; toMiddlewareOptions(config) passes them to evlog()

Docs: [https://www.evlog.dev/integrate/frameworks/express](https://www.evlog.dev/integrate/frameworks/express)
Adapters: [https://www.evlog.dev/integrate/adapters/overview](https://www.evlog.dev/integrate/adapters/overview)

</prompt>

## Quick Start

### 1. Install

<code-group>

```bash [pnpm]
pnpm add evlog express
```

```bash [bun]
bun add evlog express
```

```bash [yarn]
yarn add evlog express
```

```bash [npm]
npm install evlog express
```

</code-group>

### 2. Create evlog.config.ts

```typescript [evlog.config.ts]
import { defineEvlog } from 'evlog'

export default defineEvlog({
  service: 'my-api',
})
```

Every option lives in this file: sampling, drain, `enrich`, route filters. `npx evlog init` writes it, and the wiring below, for you. See [Configuration](https://www.evlog.dev/reference/configuration).

### 3. Initialize and register the middleware

```typescript [src/index.ts]
import express from 'express'
import { initLogger, toLoggerConfig, toMiddlewareOptions } from 'evlog'
import { evlog } from 'evlog/express'
import config from '../evlog.config'

initLogger(toLoggerConfig(config))

const app = express()

app.use(evlog(toMiddlewareOptions(config)))

app.get('/health', (req, res) => {
  req.log.set({ route: 'health' })
  res.json({ ok: true })
})

app.listen(3000)
```

<callout color="info" icon="i-custom-vite">

**Using Vite?** The [`evlog/vite` plugin](https://www.evlog.dev/reference/vite-plugin) strips `log.debug()` from production builds and injects source locations. It reads `evlog.config.ts` too, so the service and the other serializable settings come from the file. It cannot carry the drain, so keep the `initLogger(toLoggerConfig(config))` call: it runs after the plugin's auto-init and replaces it.

</callout>

The logger is available on `req.log` with full TypeScript support via module augmentation, so no extra type annotations are needed.

## Wide Events

Build up context progressively through your handler. One request = one wide event:

```typescript [src/index.ts]
app.get('/users/:id', async (req, res) => {
  const userId = req.params.id

  req.log.set({ user: { id: userId } })

  const user = await db.findUser(userId)
  req.log.set({ user: { name: user.name, plan: user.plan } })

  const orders = await db.findOrders(userId)
  req.log.set({ orders: { count: orders.length, totalRevenue: sum(orders) } })

  res.json({ user, orders })
})
```

All fields are merged into a single wide event emitted when the response finishes:

```bash [Terminal output]
14:58:15 INFO [my-api] GET /users/usr_123 200 in 12ms
  ├─ orders: count=2 totalRevenue=6298
  ├─ user: id=usr_123 name=Alice plan=pro
  └─ requestId: 4a8ff3a8-...
```

## useLogger()

Use `useLogger()` to access the request-scoped logger from anywhere in the call stack without passing `req` through your service layer:

```typescript [src/services/user.ts]
import { useLogger } from 'evlog/express'

export async function findUser(id: string) {
  const log = useLogger()
  log.set({ user: { id } })

  const user = await db.findUser(id)
  log.set({ user: { name: user.name, plan: user.plan } })

  return user
}
```

```typescript [src/index.ts]
import { findUser } from './services/user'

app.get('/users/:id', async (req, res) => {
  const user = await findUser(req.params.id)
  res.json(user)
})
```

Both `req.log` and `useLogger()` return the same logger instance. `useLogger()` uses `AsyncLocalStorage` to propagate the logger across async boundaries.

## Background work (`log.fork`)

Fire-and-forget async work that finishes **after** the response can no longer update the request wide event (the logger is sealed after emit). Use **req.log.fork(label, fn)** so `useLogger()` inside `fn` targets the forked logger, which emits its own event with `operation` and `_parentRequestId`. See [After emit](https://www.evlog.dev/learn/wide-events#after-emit-sealing-and-background-work) in Wide events.

```typescript [src/index.ts]
import { evlog, useLogger } from 'evlog/express'

app.use(evlog())

app.post('/orders', (req, res) => {
  req.log.set({ orderId: 'ord_1' })
  req.log.fork!('fulfill_order', async () => {
    const log = useLogger()
    log.set({ step: 'inventory_ok' })
  })
  res.json({ ok: true })
})
```

## Error Handling

Use `createError` for structured errors with `why`, `fix`, and `link` fields. Express uses a 4-argument error handler middleware:

```typescript [src/index.ts]
import { createError, parseError } from 'evlog'

app.get('/checkout', () => {
  throw createError({
    message: 'Payment failed',
    status: 402,
    why: 'Card declined by issuer',
    fix: 'Try a different payment method',
    link: 'https://docs.example.com/payments/declined',
  })
})

app.use((err, req, res, next) => {
  req.log.error(err)
  const parsed = parseError(err)

  res.status(parsed.status).json({
    message: parsed.message,
    why: parsed.why,
    fix: parsed.fix,
    link: parsed.link,
  })
})
```

The error is captured and logged with both the custom context and structured error fields:

```bash [Terminal output]
14:58:20 ERROR [my-api] GET /checkout 402 in 3ms
  ├─ error: name=EvlogError message=Payment failed status=402
  └─ requestId: 880a50ac-...
```

## Configuration

Every option goes in `evlog.config.ts`. See the [Configuration reference](https://www.evlog.dev/reference/configuration) for the full list.

## Drain & Enrichers

Set `drain` and `enrich` in `evlog.config.ts` so they reach the app through `toMiddlewareOptions(config)`. You can also pass them inline in the middleware options; an inline key replaces the one from the file instead of merging with it:

```typescript [src/index.ts]
import { createAxiomDrain } from 'evlog/axiom'
import { createUserAgentEnricher } from 'evlog/enrichers'

const userAgent = createUserAgentEnricher()

app.use(evlog({
  drain: createAxiomDrain(),
  enrich: (ctx) => {
    userAgent(ctx)
    ctx.event.region = process.env.FLY_REGION
  },
}))
```

### Pipeline (Batching & Retry)

For production, wrap your adapter with `createDrainPipeline` to batch events and retry on failure:

```typescript [src/index.ts]
import type { DrainContext } from 'evlog'
import { createAxiomDrain } from 'evlog/axiom'
import { createDrainPipeline } from 'evlog/pipeline'

const pipeline = createDrainPipeline<DrainContext>({
  batch: { size: 50, intervalMs: 5000 },
  retry: { maxAttempts: 3 },
})
const drain = pipeline(createAxiomDrain())

app.use(evlog({ drain }))
```

<callout color="info" icon="i-lucide-info">

Call `drain.flush()` on server shutdown to ensure all buffered events are sent. See the [Pipeline docs](https://www.evlog.dev/extend/drain-pipeline) for all options.

</callout>

## Tail Sampling

Use `keep` to force-retain specific events regardless of head sampling:

```typescript [src/index.ts]
app.use(evlog({
  drain: createAxiomDrain(),
  keep: (ctx) => {
    if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
  },
}))
```

## Route Filtering

Control which routes are logged with `include` and `exclude` patterns:

```typescript [src/index.ts]
app.use(evlog({
  include: ['/api/**'],
  exclude: ['/_internal/**', '/health'],
  routes: {
    '/api/auth/**': { service: 'auth-service' },
    '/api/payment/**': { service: 'payment-service' },
  },
}))
```

## Client-Side Logging

Use `evlog/http` to send structured logs from any frontend to your Express server. This works with any client framework (React, Vue, Svelte, vanilla JS).

### Browser setup

```typescript [client.ts]
import { initLogger, log } from 'evlog'
import { createHttpLogDrain } from 'evlog/http'

const drain = createHttpLogDrain({
  drain: { endpoint: '/v1/ingest' },
})
initLogger({ drain })

log.info({ action: 'page_view', path: location.pathname })
```

### Ingest endpoint

Add a POST route to receive batched `DrainContext[]` from the browser:

```typescript [src/index.ts]
import type { DrainContext } from 'evlog'

app.post('/v1/ingest', express.json(), (req, res) => {
  const batch = req.body as DrainContext[]
  for (const ctx of batch) {
    console.log('[BROWSER]', JSON.stringify(ctx.event))
  }
  res.sendStatus(204)
})
```

<callout color="neutral" icon="i-lucide-globe">

See the full [HTTP drain](https://www.evlog.dev/extend/drain-pipeline#http-drain-browser-to-server) adapter docs for batching, retry, sendBeacon fallback, and authentication options.

</callout>

## Run Locally

```bash [Terminal]
git clone https://github.com/evloghq/evlog.git
cd evlog
pnpm install
pnpm example express
```

Open [http://localhost:3000](http://localhost:3000) to explore the interactive test UI.

<card-group>
<card icon="i-simple-icons-github" title="Source Code" to="https://github.com/evloghq/evlog/tree/main/examples/express">

Browse the complete Express example source on GitHub.

</card>
</card-group>

## Next Steps

Deepen your **Express** integration:

- [Wide Events](https://www.evlog.dev/learn/wide-events): Design comprehensive events with context layering
- [Adapters](https://www.evlog.dev/integrate/adapters/overview): Send logs to Axiom, Sentry, PostHog, and more
- [Sampling](https://www.evlog.dev/learn/sampling): Control log volume with head and tail sampling
- [Structured Errors](https://www.evlog.dev/learn/structured-errors): Throw errors with `why`, `fix`, and `link` fields

---

- [Source Code](https://github.com/evloghq/evlog/tree/main/examples/express)


## Sitemap

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