Hope someone finds this well: # Fixing D1 Local Persistence with Wrangler Pages Dev ## Issue Local D1 persistence with `wrangler pages dev` may not work as expected, even when `preview_database_id` is set in `wrangler.toml` and `--persist-to` is used in the `dev` script. Runtime operations (e.g., API calls creating new data) might connect to a new, blank D1 instance instead of the schema-initialized, persisted one. This leads to "no such table" errors and data loss between development server restarts. While `wrangler d1 execute --local ...` correctly applies the schema to the persisted file, Pages Functions at runtime might fail to use this persisted database. ## Solution The fix involves making the D1 binding in the `wrangler pages dev` command more explicit by specifying both the binding name and the `database_name` from your `wrangler.toml`. ### 1. `wrangler.toml` Configuration Ensure your D1 database configuration includes `preview_database_id`: ```toml [[d1_databases]] binding = "DB" # Binding used in Functions (e.g., context.env.DB) database_name = "your-actual-db-name" # The name of your D1 on Cloudflare database_id = "your-remote-database-id" # ID of your remote D1 preview_database_id = "your-db-preview" # ID for the local persistent file ``` ### 2. `package.json` `dev` script Modify your `dev` script to use the `BINDING_NAME:DATABASE_NAME_FROM_TOML` format for the `--d1` flag. **Original (potentially problematic for some setups):** ```json { "scripts": { "dev": "wrangler pages dev --d1=DB --persist-to=.wrangler/state" } } ``` **Fixed (more explicit and reliable):** ```json { "scripts": { "dev": "wrangler pages dev --d1=DB:your-actual-db-name --persist-to=.wrangler/state" } } ``` *(Replace `DB` with your specific binding name and `your-actual-db-name` with the `database_name` from your `wrangler.toml`.)* This explicit linking helps ensure `wrangler pages dev` correctly uses the D1 configuration associated with the `preview_database_id` for runtime operations, enabling local persistence to function as intended. This has been observed as a fix with Wrangler v4.14.4 and v4.15.2.