> ## Documentation Index
> Fetch the complete documentation index at: https://docs.credprotocol.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Express Middleware

> Trust-gating middleware for Express.js APIs

## Installation

```bash theme={null}
npm install @cred-protocol/express @cred-protocol/sdk
```

## Quick Start

```typescript theme={null}
import express from 'express'
import { credGates } from '@cred-protocol/express'

const app = express()

app.use('/api', credGates({
  apiKey: process.env.CRED_API_KEY,
  policy: 'standard',
}))

app.get('/api/resource', (req, res) => {
  const trust = req.credTrust!
  res.json({ data: '...', tier: trust.trustTier })
})

app.listen(3000)
```

## Configuration

```typescript theme={null}
credGates({
  // Required
  apiKey: process.env.CRED_API_KEY,

  // Policy (pick one)
  policy: 'standard',              // Named template
  // gates: ['human', 'verified'], // Or custom gates
  // operator: 'AND',

  // Dynamic pricing
  pricing: {
    enabled: true,
    curve: 'step',
    basePriceUsdc: 0.01,
  },

  // Failure handling
  on402: 'challenge',              // 'challenge' (402), 'deny' (403), 'pass'

  // Response headers
  headers: true,                   // X-Cred-Trust-Score, X-Cred-Trust-Tier

  // Custom wallet extraction
  extractWallet: (req) => req.headers['x-agent-wallet'] as string,
})
```

## Wallet Address Extraction

By default the middleware checks:

1. `X-Wallet-Address` request header
2. `?wallet=` query parameter

Override with `extractWallet`:

```typescript theme={null}
credGates({
  apiKey: process.env.CRED_API_KEY,
  policy: 'standard',
  extractWallet: (req) => {
    // From a JWT, session, or custom header
    return req.headers['x-agent-wallet'] as string || null
  },
})
```

## Accessing Trust Data

The middleware attaches the result to `req.credTrust`:

```typescript theme={null}
app.get('/api/profile', (req, res) => {
  const trust = req.credTrust!

  res.json({
    wallet: trust.walletAddress,
    score: trust.trustScore,
    tier: trust.trustTier,
    confidence: trust.confidence,
    gates: trust.gateResults,
  })
})
```

## Response Headers

When `headers: true` (default), every response includes:

| Header                    | Example        | Description                           |
| ------------------------- | -------------- | ------------------------------------- |
| `X-Cred-Trust-Score`      | `75`           | 0–100 composite score                 |
| `X-Cred-Trust-Tier`       | `verified`     | Trust tier classification             |
| `X-Cred-Request-Id`       | `a1b2c3d4-...` | Request ID for debugging              |
| `X-Cred-Price-Multiplier` | `0.25`         | Price multiplier (if pricing enabled) |

## Error Handling

The middleware catches errors and passes them to Express error handling:

```typescript theme={null}
// Errors from the Cred API are forwarded via next(err)
app.use((err, req, res, next) => {
  console.error('Trust evaluation error:', err)
  res.status(500).json({ error: 'Internal server error' })
})
```

| Response | When                                                         |
| -------- | ------------------------------------------------------------ |
| `400`    | No wallet address found on the request                       |
| `402`    | Gates failed, `on402: 'challenge'` — includes challenge body |
| `403`    | Gates failed with `on402: 'deny'`, or wallet is `blocked`    |
| `429`    | Cred API rate limit exceeded                                 |
| `502`    | Upstream gate provider error                                 |
