[bug] Better Auth addon generates legacy D1 binding access with SvelteKit 3 and Cloudflare adapter 8

Abierto Apto para principiantes
#1,450 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 4 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
82/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
typescript
Área
backend, cli

Línea de trabajo

Encuentra la plantilla del complemento Better Auth que genera src/hooks.server.ts para Cloudflare Workers y Drizzle D1. Empieza buscando event.platform.env.DB en las plantillas de la CLI y comprueba cómo acceden a los bindings otras plantillas de Cloudflare. Actualiza el hook generado para que use la API de bindings compatible y, después, verifica que un proyecto generado se inicie y que sus rutas devuelvan HTTP 200.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug pkg:add

Describe the bug

When creating a new SvelteKit project using sv create with the Cloudflare Workers adapter, Drizzle (Cloudflare D1), and Better Auth (Email & Password) addons, the generated src/hooks.server.ts uses the legacy event.platform.env.DB API to access the D1 database binding.

With SvelteKit 3 and @sveltejs/adapter-cloudflare 8, Cloudflare-specific bindings are no longer exposed through event.platform.

As a result, the generated application fails with HTTP 500 errors during local development, even when the D1 binding is correctly configured.

Replacing event.platform.env.DB with env.DB imported from cloudflare:workers resolves the issue.

Steps to reproduce

  1. Run:

    npx [email protected] create
    
  2. Select the following options:

    • Template: SvelteKit minimal
    • TypeScript: Yes
    • Adapter: Cloudflare → Workers
    • Drizzle: Cloudflare D1
    • Better Auth: Email & Password
  3. Configure the Cloudflare D1 binding and environment variables as instructed by the CLI.

  4. Start the development server:

    npm run dev
    
  5. Navigate to http://localhost:5173/.

Actual behavior

The generated src/hooks.server.ts contains:

const handleBetterAuth: Handle = async ({ event, resolve }) => {
    if (!event.platform?.env?.DB)
        throw new Error('D1 binding "DB" not found - are you running with wrangler?');

    event.locals.auth = createAuth(event.platform.env.DB);

    // ...
};

The application throws the following runtime error:

Error: D1 binding "DB" not found - are you running with wrangler?
    at handleBetterAuth (src/hooks.server.ts:23:9)

500 GET /
500 GET /favicon.ico

Expected behavior

The generated Better Auth integration should use the supported Cloudflare binding access API for SvelteKit 3 and @sveltejs/adapter-cloudflare 8.

A correctly configured project should start successfully without requiring manual modifications to the generated authentication hook.

Suggested fix

Import env directly from cloudflare:workers instead of accessing bindings through event.platform.env.

+ import { env } from 'cloudflare:workers';

const handleBetterAuth: Handle = async ({ event, resolve }) => {
-   if (!event.platform?.env?.DB)
+   if (!env?.DB)
        throw new Error('D1 binding "DB" not found - are you running with wrangler?');

-   event.locals.auth = createAuth(event.platform.env.DB);
+   event.locals.auth = createAuth(env.DB);

    // Remaining handler unchanged
};

After applying this change, the application successfully started, and the previously failing routes returned HTTP 200 instead of HTTP 500.

Environment

Package Version
sv 1.2.0
@sveltejs/kit 3.1.1
@sveltejs/adapter-cloudflare 8.0.2
better-auth 1.7.16
Database Cloudflare D1
ORM Drizzle
Package manager npm
OS Windows (PowerShell)

Additional context

The SvelteKit 3 migration guide documents the removal of Cloudflare-specific APIs from event.platform and recommends using imports from cloudflare:workers instead.

This appears to be a compatibility issue in the Svelte CLI Better Auth addon template when generating projects targeting SvelteKit 3 and Cloudflare Workers.

The addon template should be updated to generate the appropriate Cloudflare binding access code.

Note: The initial setup also reported a separate Drizzle schema mismatch involving missing Better Auth tables (user, session, account, and verification). This report specifically concerns the D1 binding access issue, which was resolved by the change described above.

Lenguaje dominante
TypeScript
Estrellas
513
Forks
110
Merge medio
5 d 1 h
PR fusionados (30 d)
24

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de sveltejs/cli

Todos los issues de sveltejs/cli

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.