stnd.buildSTANDARD MANUAL2026-07-15

2.2 Edge Database & Authentication

Structural implementation of Kysely, D1, and Better-Auth within Cloudflare Workers.

2.2 Edge Database & Authentication

“Global state in serverless environments is a structural defect.” — Standard Technical Directives, 2026

The @stnd/account package implements authentication and database connectivity. The architecture strictly mandates dynamic, request-bound instantiations to prevent severe systemic failures inherent to Cloudflare Workers.

1. The Singleton Anti-Pattern

In traditional Node.js environments, it is standard practice to export a globally initialized database or authentication client. This pattern is explicitly forbidden in the Standard Framework.

Cloudflare Workers execute multiple concurrent requests across the same V8 isolate. Variables bound to specific requests (such as Cloudflare D1 database bindings provided via env) cannot be safely stored in global scope. Attempting to do so triggers the fatal Cannot perform I/O on behalf of a different request exception.

2. Dynamic Initialization (initAuth)

To ensure absolute operational safety, the auth.js instance is constructed dynamically during the execution of Astro’s middleware.

Implementation Protocol

  1. The middleware.js intercepts the request.
  2. It extracts the contextual environment bindings (context.locals.runtime.env).
  3. It passes these bindings to the initAuth(env) factory function.
  4. initAuth initializes a transient instance of better-auth combined with the kysely-adapter, actively binding the correct D1 instance (env.ADE_DB or env.DB).
  5. The instance is immediately utilized to validate the session (auth.api.getSession) and is safely garbage-collected post-response.

3. Cryptographic Verification

Password-based authentication introduces unnecessary friction and insecure user behavior. It is deprecated.

The Standard Framework enforces cryptographic verification via @better-auth/passkey (WebAuthn) and magicLink (Email OTP). All secrets must be securely provided via Cloudflare environment variables (BETTER_AUTH_SECRETRESEND_API_KEY). Hardcoding cryptographic parameters in source control constitutes a critical violation of system integrity.