On this page

Guides

Cloudflare Guide

Configure Entro Auth for Cloudflare.

This guide covers what Entro Auth needs on Cloudflare. Set up Entro Auth with the installation guide first.

@entro314labs/entro-auth-cloudflare holds the two pieces a Worker needs code for: the client address and one auth instance per request.

npm install @entro314labs/entro-auth-cloudflare

Node.js Compatibility

Entro Auth uses Node.js APIs such as node:crypto and AsyncLocalStorage. Cloudflare Workers enable Node.js compatibility by default from compatibility date 2026-08-04. For an earlier date, add the nodejs_compat flag to your Wrangler configuration:

wrangler.jsonc
{
  "compatibility_flags": ["nodejs_compat"]
}

Environment Variables

Entro Auth reads environment variables from process.env. With Node.js compatibility, Workers add variables and secrets to process.env from compatibility date 2025-04-01. Set the secret with Wrangler, and put local values in .dev.vars or .env:

npx wrangler secret put ENTRO_AUTH_SECRET

For an earlier date, pass the values from env instead:

auth.ts
import { env } from "cloudflare:workers";
import { entroAuth } from "@entro314labs/entro-auth";

export const auth = entroAuth({
  secret: env.ENTRO_AUTH_SECRET,
});

With the Vite plugin's cloudflare.config.ts

Version 2 of @cloudflare/vite-plugin reads a cloudflare.config.ts and no Wrangler file, and deploys go through the cf CLI. There a value reaches process.env only when the Worker's configuration declares it. This was checked with @cloudflare/vite-plugin 2.0.0-rc.6 and cf 1.0.0-rc.6; both are release candidates, so read their own documentation if yours are newer.

cloudflare.config.ts
import { bindings, defineConfig } from "cf/config";

export default defineConfig({
  worker: {
    name: "my-app",
    compatibilityDate: "2026-08-01",
    compatibilityFlags: ["nodejs_compat"],
    env: {
      ENTRO_AUTH_SECRET: bindings.secret(),
      ENTRO_AUTH_URL: bindings.secret(),
      DATABASE_URL: bindings.secret(),
    },
  },
});
  • In development the values come from .env.local beside the configuration. One that is in the file and not declared under env is absent from process.env, with no warning: the instance starts without its secret or its database address.
  • A deploy fails while a declared secret has no value on the Worker. Set the values first.
  • Setting a secret on a deployed Worker creates a new version and deploys it. Set several in one call rather than one at a time, so that no version runs with half of them.

Declare every setting your auth.ts reads, the ones for plugins included (a captcha secret, a mail key, a provider's client secret).

Client IP

Requests to a Worker don't carry the client address in X-Forwarded-For, which Entro Auth reads by default. Without an address, rate limiting cannot tell visitors apart: it counts everybody in one bucket per path, so three wrong passwords by one person refuse sign in to everyone until the window has passed. Cloudflare puts the address in CF-Connecting-IP and replaces whatever a client sent there. The cloudflare plugin reads it:

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { cloudflare } from "@entro314labs/entro-auth-cloudflare";

export const auth = entroAuth({
  plugins: [cloudflare()],
});

It sets advanced.ipAddress.ipAddressHeaders to ["cf-connecting-ip"], and leaves the option alone when you set it yourself. Use it only where Cloudflare is in front of the server: anywhere else a client can send the header and choose the address it is counted under.

Background Tasks

To run non-critical work after the response is sent, pass waitUntil from cloudflare:workers as advanced.backgroundTasks.handler.

Database Connections

Workers don't allow I/O across requests: a socket that one request opened cannot be used by another. An auth instance at module scope, on a client that keeps a connection open (postgres, a pg or mysql2 pool, also through Hyperdrive), answers the first request and fails as soon as two overlap. There are two ways out.

A driver that queries over HTTP holds no socket, so one instance at module scope works.

One instance per request. perRequest opens a connection, builds the auth instance on it, runs the work and closes the connection:

auth.ts
import { createDb } from "@capydb/drizzle";
import { entroAuth } from "@entro314labs/entro-auth/minimal";
import type { CapydbDatabase } from "@entro314labs/entro-auth-capydb";
import { capydbAdapter } from "@entro314labs/entro-auth-capydb";
import { cloudflare, perRequest } from "@entro314labs/entro-auth-cloudflare";
import * as schema from "./auth-schema";

export const build = (db: CapydbDatabase) =>
  entroAuth({
    database: capydbAdapter(db, { schema }),
    plugins: [cloudflare()],
  });

export const withAuth = perRequest({ 
  open: () => createDb({ relations: schema.authRelations }),
  build,
  close: (db) => db.$client.end({ timeout: 5 }),
});
const response = await withAuth((auth) => auth.handler(request));

Any driver works the same way: open returns the client, close ends it. With Hyperdrive, open connects to env.HYPERDRIVE.connectionString, and the connection is cheap because Hyperdrive keeps the ones to your database open.

What a request costs

A client such as postgres connects on its first query, so a request that needs no query opens nothing. A request that does pays for the connection first: a TCP and a TLS handshake and the database login, about seven round trips to your database before the first query, on every such request. Keep the requests every page makes away from the database:

  • /get-session. Turn on session.cookieCache, so the session is read from a signed cookie for a few minutes at a time.
  • The JWT plugin. By default it adds a set-auth-jwt header to every /get-session answer, signed with a key it reads from the database, so the cookie cache alone saves nothing. Set disableSettingJwtHeader: true unless you read that header.
  • The rate limit. A Worker keeps no memory between requests, so use rateLimit.storage: "database" (or a secondary storage). Every counted request then reads and writes the counter. Leave the cheap, frequent paths out with customRules: { "/get-session": false }.
auth.ts
entroAuth({
  session: { cookieCache: { enabled: true, maxAge: 300 } },
  rateLimit: {
    enabled: true,
    storage: "database",
    customRules: { "/get-session": false, "/token": false },
  },
  plugins: [jwt({ disableSettingJwtHeader: true }), cloudflare()],
});

The rate limit is on in production only unless enabled is set. With database storage, set it, or a missing rateLimit table shows up after the deploy.

The schema generator

The CLI reads an exported auth instance, which a per-request setup does not have. Give it a file of its own that builds the same configuration on a client that never connects, and point --config at it:

auth.cli.ts
import { createDb } from "@capydb/drizzle";
import { build } from "./auth";

export const auth = build(
  createDb({ connectionString: "postgres://localhost:6432/unused" }),
);

Cloudflare Workers KV

Cloudflare Workers KV is eventually consistent, cannot expire a key sooner than 60 seconds, and has no atomic operations, so it cannot meet the secondaryStorage contract. Use a store that can, such as Redis.