Back to docs

SDK

Start with the getting-started guide for framework wiring. This page explains the SDK behavior behind those adapters.

Runtime env

Set these on the server runtime that executes traced code and exposes the agent route. The SDK ships with production ingest failover URLs, so normal apps do not set an ingest URL.

.env
FLUX_PROJECT_TOKEN=fbproj_...
FLUX_PUBLIC_KEY=base64-public-key
FLUX_PRIVATE_KEY=base64-private-key

# Optional: dry-run for CI / local testing
FLUX_DRY_RUN=1
# Optional: capture host-side console.log in dashboard
FLUX_CAPTURE_HOST_CONSOLE=1

Use FLUX_INGEST_URL or FLUX_INGEST_URLS only for private or self-hosted ingest overrides.

For local smoke tests, setting FLUX_INGEST_URL=/api/flux-ingest posts batches to /api/flux-ingest/v1/executions.

Set FLUX_DRY_RUN=1 to skip ingest and log capture JSON to stdout instead — useful for CI and local verification.

Startup health check

Call fluxCheck() at startup to verify project token, public key, and ingest connectivity before the first route is hit. Returns structured FluxCheckResult with .ok, .warnings, and .ingestReachable.

typescript
import { fluxCheck } from 'fluxrun';

// Add at app startup to verify SDK connectivity.
// Logs health summary; returns structured result.
const health = await fluxCheck();
if (!health.ok) console.warn('FluxRun SDK is not fully configured.');

Adapters first

Use a framework adapter when one exists. Adapters normalize request data into flux.request, capture the execution, and return the response shape your framework expects. They also auto-extract flux.requestId and flux.traceId from incoming headers for cross-service tracing. For webhooks that need the original request body (HMAC verification), pass rawBody: true. Use passRequest: true with native mode to access the raw Request object via flux.request.raw.

  • fluxrun

    Core SDK: fluxFunc, fluxTrack, fluxHost, fluxHost.auto, fluxFetch, fluxInline, fluxENV, fluxAgent, withFluxNextServerAction.

  • fluxrun/build

    Next.js and bundler plugins for host-module transforms.

  • fluxrun/adapters/next

    Next.js App Router route handlers.

  • fluxrun/adapters/next-server-action

    Next.js server action wrapper.

  • fluxrun/adapters/express

    Express middleware.

  • fluxrun/adapters/fastify

    Fastify route handlers.

  • fluxrun/adapters/hono

    Hono handlers.

  • fluxrun/adapters/koa

    Koa middleware.

  • fluxrun/adapters/web

    Standard Request and Response runtimes.

  • fluxrun/adapters/aws

    AWS Lambda API Gateway v2 style handlers.

Server actions

Use withFluxNextServerAction from fluxrun/adapters/next-server-action to record Next.js server actions. Runs in native mode so redirect(), revalidatePath(), and cookies() work normally. Supports both plain form actions and useActionState.

typescript
import { withFluxNextServerAction } from 'fluxrun/adapters/next-server-action';

// Server action — records vm.boot/vm.return, captures fluxHost calls.
export const createOrder = withFluxNextServerAction(
  'orders.create',
  async (formData: FormData) => {
    const amount = formData.get('amount');
    await db.createOrder({ amount: Number(amount), currency: 'usd' });
    redirect('/orders');
  },
  { host: { db } },
);

// useActionState pattern:
export const updateProfile = withFluxNextServerAction(
  'profile.update',
  async (prevState: { error?: string }, formData: FormData) => {
    const name = formData.get('name');
    if (!name) return { error: 'Name is required' };
    await db.updateProfile({ name });
    return { error: '' };
  },
);

Manual wrapping

Use fluxFunc directly for custom servers, cron jobs, queue workers, or frameworks without an adapter. Put live clients and class instances behind fluxHost so replay can call them through an explicit boundary.

typescript
import { fluxFunc, fluxHost } from 'fluxrun';

type OrderInput = { amount: number; currency: string };

const db = fluxHost('db', {
  createOrder: async (input: OrderInput) => prisma.order.create({ data: input }),
});

export const createOrder = fluxFunc(
  async (input: OrderInput) => {
    const order = await db.createOrder(input);
    return { id: order.id };
  },
  'orders.create',
  { host: { db } },
);

Auto-registering store methods

Use fluxHost.auto to discover every function property on a store object — no manual fluxHost call per method.

typescript
import { fluxHost } from 'fluxrun';

// Register all 54 store methods in one call
const db = fluxHost.auto('db', prisma);

Native recording (fluxTrack)

Use fluxTrack or { mode: 'native' } when you need framework APIs like redirect(), cookies(), or any Node.js API unavailable in the QuickJS VM. Lifecycle events and fluxHost RPC calls are still recorded — only the sandbox is skipped.

typescript
import { fluxTrack } from 'fluxrun';

// Native execution — redirect(), cookies(), revalidatePath() work.
export const charge = fluxTrack(async (amount: number) => {
  const res = await fluxFetch('https://api.stripe.com/v1/charges', {
    method: 'POST',
    headers: { Authorization: `Bearer ${fluxENV.STRIPE_KEY}` },
    body: JSON.stringify({ amount, currency: 'usd' }),
  });
  return res.json();
}, 'billing.charge');

Outbound fetch with tracing

Use fluxFetch for host-side HTTP calls inside traced handlers. It auto-injects x-request-id and traceparent headers from the execution context, and records the call as a boundary event in the dashboard.

typescript
import { fluxFetch } from 'fluxrun';

// Auto-injects x-request-id and W3C traceparent headers
const res = await fluxFetch('https://api.stripe.com/v1/charges', {
  method: 'POST',
  headers: { Authorization: `Bearer ${fluxENV.STRIPE_KEY}` },
  body: JSON.stringify({ amount: 2000, currency: 'usd' }),
});

Agent route

The dashboard calls your agent route with a short-lived token. Forward the Authorization header to fluxAgent; the SDK verifies it with FluxRun using your project token, then handles decrypt and replay.

typescript
import { fluxAgent } from 'fluxrun';

export async function POST(req: Request) {
  return Response.json(
    await fluxAgent(await req.json(), {
      authorization: req.headers.get('authorization'),
    }),
  );
}

Capture behavior

Capture records request, return, errors, console events, timing, host-module boundaries, and outbound fetch calls for the project shown in the dashboard. Payload handling follows the SDK encryption and redaction policy for the installed fluxrun version.