Guides / Platforms & Tools

How to Log Events from Cloudflare Workers

3 min readยทPlatforms & Tools

Why the REST API

Cloudflare Workers don't support Node.js APIs. Use LogIt's HTTP REST API directly with fetch โ€” no SDK needed.

Minimal helper

ts
// lib/logit.ts (Cloudflare Workers compatible)
interface LogitPayload {
  channel: string;
  event: string;
  description?: string;
  icon?: string;
  notify?: boolean;
  tags?: Record<string, string>;
  metadata?: Record<string, string | number | boolean>;
}

async function logit(payload: LogitPayload, apiKey: string): Promise<void> {
  await fetch("https://logit.now/api/v1/events", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify(payload),
  });
}

Full Worker example

ts
// worker.ts
export interface Env {
  LOGIT_API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    // Track API requests
    if (url.pathname === "/api/checkout") {
      const start = Date.now();
      try {
        // ... handle checkout
        await logit({
          channel: "payments",
          event: "Checkout processed",
          description: `${request.method} ${url.pathname}`,
          icon: "๐Ÿ’ฐ",
          notify: true,
          metadata: { durationMs: Date.now() - start, cf_country: request.cf?.country as string },
        }, env.LOGIT_API_KEY);

        return Response.json({ ok: true });
      } catch (error) {
        await logit({
          channel: "errors",
          event: "Worker error",
          description: error instanceof Error ? error.message : "Unknown error",
          icon: "โŒ",
          notify: true,
          metadata: { path: url.pathname },
        }, env.LOGIT_API_KEY);
        return Response.json({ error: "Internal error" }, { status: 500 });
      }
    }

    return new Response("Not found", { status: 404 });
  },
};

Using waitUntil for non-blocking logging

ts
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const response = await handleRequest(request, env);

    // Log without blocking the response
    ctx.waitUntil(
      logit({ channel: "requests", event: "API request", icon: "๐Ÿ“ก", notify: false }, env.LOGIT_API_KEY)
    );

    return response;
  },
};

Note: Always use ctx.waitUntil for logging so the Worker response isn't delayed. The log happens after the response is sent.

Set secrets

bash
wrangler secret put LOGIT_API_KEY

Try LogIt free

7-day trial. No credit card required.

Start free