npm package: @smart-dev-agency/smart-grow-logs-cloudflare
Description: Smart Grow Logs adapter for Cloudflare Workers and Hono applications.
Author: Smart Dev Agency S.A.S
Latest version: 2.0.0

# Smart Grow Logs - Cloudflare Workers + Hono SDK

Official adapter for Cloudflare Workers with first-class Hono middleware support.

## 1. Requirements

Before installing:

1. Create a Smart Grow Logs project.
2. Get your API key (`sgl_...`) from the dashboard.
3. Define the `baseUrl` for your logs API.

SaaS example:

- `https://logs-api.smart-grow.app/`

Self-hosted example:

- `https://your-logs-domain.com/`

## 2. Installation

### npm (Workers only)

```bash
npm install @smart-dev-agency/smart-grow-logs-cloudflare
```

### npm (if you use Hono)

```bash
npm install @smart-dev-agency/smart-grow-logs-cloudflare hono
```

### pnpm (if you use Hono)

```bash
pnpm add @smart-dev-agency/smart-grow-logs-cloudflare hono
```

### yarn (if you use Hono)

```bash
yarn add @smart-dev-agency/smart-grow-logs-cloudflare hono
```

## 3. Cloudflare environment variables

Recommended setup:

- `SMART_GROW_API_KEY`: as a secret.
- `SMART_GROW_BASE_URL`: as a regular variable.
- `SMART_GROW_SERVICE`: service name.
- `SMART_GROW_ENVIRONMENT`: `local`, `staging`, `production`, etc.

### Option A: `wrangler.toml` (non-sensitive variables)

```toml
name = "my-worker"
main = "src/index.ts"
compatibility_date = "2026-02-20"

[vars]
SMART_GROW_BASE_URL = "https://logs-api.smart-grow.app/"
SMART_GROW_SERVICE = "edge-api"
SMART_GROW_ENVIRONMENT = "development"

[env.production.vars]
SMART_GROW_BASE_URL = "https://logs-api.smart-grow.app/"
SMART_GROW_SERVICE = "edge-api"
SMART_GROW_ENVIRONMENT = "production"
```

### Option B: secrets (API key)

```bash
wrangler secret put SMART_GROW_API_KEY
wrangler secret put SMART_GROW_API_KEY --env production
```

### Local development with `.dev.vars`

```bash
SMART_GROW_API_KEY=sgl_xxxxxxxxxxxxxxxxx
SMART_GROW_BASE_URL=https://logs-api.smart-grow.app/
SMART_GROW_SERVICE=edge-local
SMART_GROW_ENVIRONMENT=local
```

Wrangler automatically loads `.dev.vars` when running `wrangler dev`.

## 4. Use Case 1: Plain Worker (no Hono)

```ts
import { SmartGrowLogsCloudflare } from '@smart-dev-agency/smart-grow-logs-cloudflare';

type Env = {
  SMART_GROW_API_KEY: string;
  SMART_GROW_BASE_URL: string;
  SMART_GROW_SERVICE?: string;
  SMART_GROW_ENVIRONMENT?: string;
};

let loggerInit: Promise<void> | null = null;

function ensureLogger(env: Env): Promise<void> {
  if (!loggerInit) {
    loggerInit = SmartGrowLogsCloudflare.initialize({
      apiKey: env.SMART_GROW_API_KEY,
      baseUrl: env.SMART_GROW_BASE_URL,
      service: env.SMART_GROW_SERVICE ?? 'worker-api',
      environment: env.SMART_GROW_ENVIRONMENT ?? 'unknown',
    });
  }
  return loggerInit;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    await ensureLogger(env);

    ctx.waitUntil(
      SmartGrowLogsCloudflare.info('Incoming request', {
        metadata: {
          path: new URL(request.url).pathname,
        },
        context: { request },
      })
    );

    return new Response('ok');
  },
};
```

## 5. Use Case 2: Basic Hono setup (5xx + unhandled exceptions only)

This is the middleware default behavior.

```ts
import { Hono } from 'hono';
import { smartGrowLogsMiddleware } from '@smart-dev-agency/smart-grow-logs-cloudflare';

type Bindings = {
  SMART_GROW_API_KEY: string;
  SMART_GROW_BASE_URL: string;
  SMART_GROW_SERVICE: string;
  SMART_GROW_ENVIRONMENT: string;
};

const app = new Hono<{ Bindings: Bindings }>();

app.use(
  '*',
  smartGrowLogsMiddleware({
    apiKey: (c) => c.env.SMART_GROW_API_KEY,
    baseUrl: (c) => c.env.SMART_GROW_BASE_URL,
    service: (c) => c.env.SMART_GROW_SERVICE,
    environment: (c) => c.env.SMART_GROW_ENVIRONMENT,
  })
);

app.get('/health', (c) => c.json({ ok: true }));

export default app;
```

## 6. Use Case 3: Hono with 4xx and successful response logging

```ts
app.use(
  '*',
  smartGrowLogsMiddleware({
    apiKey: (c) => c.env.SMART_GROW_API_KEY,
    baseUrl: (c) => c.env.SMART_GROW_BASE_URL,
    capture4xxResponses: true,
    captureSuccessfulRequests: true,
    includeRequestHeaders: true,
  })
);
```

## 7. Use Case 4: Attach user, session, and custom metadata

```ts
app.use(
  '*',
  smartGrowLogsMiddleware({
    apiKey: (c) => c.env.SMART_GROW_API_KEY,
    baseUrl: (c) => c.env.SMART_GROW_BASE_URL,
    getUserIdentifier: (c) => c.req.header('x-user-id') ?? undefined,
    getSessionId: (c) => c.req.header('x-session-id') ?? undefined,
    metadata: async (c, meta) => ({
      route: c.req.routePath,
      status: meta.status,
      duration_ms: meta.durationMs,
      tenant: c.req.header('x-tenant-id') ?? 'unknown',
    }),
  })
);
```

## 8. Use Case 5: Strict mode (`failOpen: false`)

By default, middleware does not break requests if logger initialization/logging fails (`failOpen: true`).
If you want requests to fail when logger setup fails:

```ts
app.use(
  '*',
  smartGrowLogsMiddleware({
    apiKey: (c) => c.env.SMART_GROW_API_KEY,
    baseUrl: (c) => c.env.SMART_GROW_BASE_URL,
    failOpen: false,
  })
);
```

## 9. Manual logging inside Hono handlers

```ts
import { SmartGrowLogsCloudflare } from '@smart-dev-agency/smart-grow-logs-cloudflare';

app.get('/orders/:id', async (c) => {
  try {
    // business logic
    return c.json({ ok: true });
  } catch (error) {
    c.executionCtx.waitUntil(
      SmartGrowLogsCloudflare.error('Order processing failed', {
        stackTrace: error instanceof Error ? error.stack : undefined,
        metadata: {
          orderId: c.req.param('id'),
        },
        context: { request: c.req.raw },
      })
    );

    throw error;
  }
});
```

## 10. Middleware options

`smartGrowLogsMiddleware(options)` supports:

- `apiKey`: `string | (c) => string`
- `baseUrl`: `string | (c) => string`
- `debug`: `boolean | (c) => boolean`
- `service`: `string | (c) => string`
- `environment`: `string | (c) => string`
- `tags`: `Record<string, string> | (c) => Record<string, string>`
- `capture4xxResponses`: `boolean` (default `false`)
- `captureSuccessfulRequests`: `boolean` (default `false`)
- `includeRequestHeaders`: `boolean` (default `false`)
- `includeCf`: `boolean` (default `true`)
- `skip`: `(c) => boolean | Promise<boolean>`
- `getUserIdentifier`: `(c) => string | undefined`
- `getSessionId`: `(c) => string | undefined`
- `metadata`: `(c, meta) => Record<string, unknown> | Promise<Record<string, unknown>>`
- `failOpen`: `boolean` (default `true`)

## 11. Direct SDK API

The package exports:

- `SmartGrowLogsCloudflare.initialize(options)`
- `SmartGrowLogsCloudflare.sendLog(options)`
- `SmartGrowLogsCloudflare.debug/info/warn/error/fatal(message, options?)`

It also re-exports `LogLevel` and base types.

## 12. Quick integration checklist

1. Install the package.
2. Configure `SMART_GROW_API_KEY` (secret) and `SMART_GROW_BASE_URL`.
3. Add middleware or manual initialization.
4. Deploy and verify logs in your dashboard.