Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
7e7f416
Initial Vite plugin docs
jamesopstad Mar 3, 2025
3d72d85
Update src/content/docs/workers/vite-plugin/api.mdx
jamesopstad Mar 3, 2025
faa371a
Update src/content/docs/workers/vite-plugin/api.mdx
jamesopstad Mar 3, 2025
73499b9
adds a directory structure for local development docs, and adds a Vi…
korinne Mar 6, 2025
c8d8ead
Update src/content/docs/workers/local-development/vite.mdx
korinne Mar 7, 2025
c2d590d
Update src/content/docs/workers/local-development/wrangler.mdx
korinne Mar 7, 2025
87e01b5
fix some broken links
korinne Mar 7, 2025
086a3cc
Merge branch 'korinne-vite-plugin-docs' of github.com:cloudflare/clou…
korinne Mar 7, 2025
f6cf8a0
consolidates current local dev docs under new directory, and includes
korinne Mar 11, 2025
22dd07e
Uses new PackageManager component in local-development/wrangler.mdx
korinne Mar 11, 2025
66508f7
adds bindings_per_env.mdx under src/content/partials/workers
korinne Mar 11, 2025
0c9b53d
Adds guidance for when to use Wrangler vs Vite, adds Vite to the bind…
korinne Mar 17, 2025
547e15b
updates Wrangler local development guide, and partial for local vs re…
korinne Mar 17, 2025
69b09ff
updates overview page to make more concise
korinne Mar 17, 2025
b09d283
merge production
korinne Mar 18, 2025
4caed42
Merge branch 'production' of github.com:cloudflare/cloudflare-docs in…
korinne Mar 18, 2025
1556028
fixes broken links
korinne Mar 18, 2025
ac90adc
Update src/content/docs/workers/local-development/vite.mdx
korinne Mar 19, 2025
2dfae73
Update src/content/docs/workers/local-development/vite.mdx
korinne Mar 19, 2025
df19876
Update src/content/docs/workers/local-development/vite.mdx
korinne Mar 19, 2025
9d5202c
Update src/content/docs/workers/local-development/index.mdx
korinne Mar 19, 2025
64875a9
moves local development section nearer to testing section
korinne Mar 28, 2025
57de775
cleans up text in choosing between wrangler and vite
korinne Apr 2, 2025
9aaeb9c
updates overview page for local development
korinne Apr 2, 2025
7b3f858
update overview page, add working with data page
korinne Apr 4, 2025
7255613
updates local development docs
korinne Apr 5, 2025
f888bee
Merge branch 'production' of github.com:cloudflare/cloudflare-docs in…
korinne Apr 5, 2025
9af5af8
Update src/content/docs/workers/local-development/local-data.mdx
korinne Apr 7, 2025
b2766b8
Update src/content/docs/workers/local-development/local-data.mdx
korinne Apr 7, 2025
54bbee8
Update src/content/docs/workers/local-development/wrangler-vs-vite.mdx
korinne Apr 7, 2025
3a6d19a
Update src/content/docs/workers/local-development/remote-data.mdx
korinne Apr 7, 2025
32273fb
Update src/content/docs/workers/local-development/local-data.mdx
korinne Apr 7, 2025
a64d2ca
Update src/content/docs/workers/local-development/local-data.mdx
korinne Apr 7, 2025
d325a33
Update src/content/docs/workers/local-development/local-data.mdx
korinne Apr 7, 2025
9e0b348
Update src/content/docs/workers/local-development/index.mdx
korinne Apr 7, 2025
f302af4
adds updates to remove separate vite vs wrangler docs, small changes
korinne Apr 7, 2025
d2ae2db
updates local-data.mdx
korinne Apr 7, 2025
18f294b
Update src/content/docs/workers/local-development/remote-data.mdx
kodster28 Apr 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/content/docs/workers/local-development/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
pcx_content_type: navigation
title: Local development
sidebar:
order: 5
head: []
description: Develop your Workers locally.
---

Cloudflare Workers provides two primary ways to develop and test your code locally. Local development ensures a fast feedback loop, keeps iteration times low, and lets you experiment before deploying to production.

Developers can locally test their changes to a Workers project using the following:

- **Wrangler’s built-in dev command** [`wrangler dev`](/workers/wrangler/commands/#dev), which uses [`workerd`](https://github.com/cloudflare/workerd) and Miniflare to simulate production behavior and resource bindings locally.

- The **Cloudflare Vite plugin** (`@cloudflare/vite-plugin`), which integrates directly with Vite and runs your code in the same `workerd` runtime, while also offering features like [hot module replacement (HMR)](https://vite.dev/guide/features.html#hot-module-replacement). The Vite plugin is currently considered in **beta**.

Both approaches aim to provide confidence that your local environment will closely match the production runtime, removing the need to [test against remote resources](#develop-using-remote-resources-and-bindings).
308 changes: 308 additions & 0 deletions src/content/docs/workers/local-development/vite.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,308 @@
---
title: Vite
pcx_content_type: concept
sidebar:
order: 7
group:
badge: Beta
head: []
description: Locally develop and test changes with the Cloudflare Vite plugin
---

import {
Badge,
InlineBadge,
PackageManagers,
WranglerConfig,
} from "~/components";

The Cloudflare Vite plugin (`@cloudflare/vite-plugin`) integrates your Worker code directly with [Vite](https://vite.dev/). Like `wrangler dev`, this approach uses `workerd` under the hood as well, and provides:

- Direct access to Workers [runtime APIs](/workers/runtime-apis/) and [bindings](/runtime-apis/bindings/)
- [Hot module replacement (HMR)](https://vite.dev/guide/features.html#hot-module-replacement) for near-instant feedback on code changes.
- A single workflow (`vite dev`, `vite build`, `vite preview`) that handles both your client-side assets and Worker code.
- An “input” Wrangler config file and an automatically generated “output” config file (used for preview and deployment).

If you are building anything that involves a front-end using [Workers static assets](/workers/static-assets/), the Vite approach can be particularly powerful.

## Get started

#### 1. Create your project directory and add a minimal package.json:

```json
{
"name": "cloudflare-vite-quick-start",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
```

:::note
Ensure that you include `"type": "module"` in order to use ES modules by default.
:::

#### 2. Install dependencies

<PackageManagers type="add" pkg="vite @cloudflare/vite-plugin wrangler" dev />

#### 3. Create a Vite config file (`vite.config.ts`) and include the Cloudflare plugin:

```ts
// vite.config.ts

import { defineConfig } from "vite";
import { cloudflare } from "@cloudflare/vite-plugin";

export default defineConfig({
plugins: [cloudflare()],
});
```

#### 4. Create a Worker configuration file (`wrangler.toml` or `wrangler.jsonc`):

<WranglerConfig>

```toml
name = "cloudflare-vite-quick-start"
compatibility_date = "2024-12-30"
main = "./src/index.ts"
```

</WranglerConfig>

#### 5. Create a Worker entry file (`src/index.ts`):

```ts
// src/index.ts

export default {
fetch() {
return new Response(`Running in ${navigator.userAgent}!`);
},
};
```

#### 6. Run local development

```sh
npm run dev
```

This starts a local development server, using the Workers runtime behind the scenes. You can build (`npm run build)`, preview (`npm run preview`), or deploy (`npm exec wrangler deploy`) at any time.

## Cloudflare environments

You can specify multiple [Cloudflare environments](/workers/wrangler/environments/) in your Worker confiuration (for example, `[env.staging]` or `[env.production]`). With the Cloudflare Vite plugin, you can select an environment at `dev` or `build` time by providing the `CLOUDFLARE_ENV` environment variable.

For example, let's say you have the following Wrangler configuration file:

<WranglerConfig>

```toml
name = "my-worker"
compatibility_date = "2024-12-30"
main = "./src/index.ts"

vars = { MY_VAR = "Top-level var" }

[env.staging]
vars = { MY_VAR = "Staging var" }

[env.production]
vars = { MY_VAR = "Production var" }
```

</WranglerConfig>

With the Vite plugin, you can run:

```sh
CLOUDFLARE_ENV=production vite build
```

The output `wrangler.json` file generated by the build will be a flattened configuration for the `'production'` Cloudflare environment. This combines [top-level only](/workers/wrangler/configuration/#top-level-only-keys), [inheritable](/workers/wrangler/configuration/#inheritable-keys), and [non-inheritable](/workers/wrangler/configuration/#non-inheritable-keys) keys.

In this case,

- The value of `MY_VAR` will be `'Production var'`.
- The name of the Worker will be `'my-worker-production'`.

This is because the environment name is automatically appended to the top-level Worker name.

:::note
The default Vite environment name for a Worker is always the top-level Worker name.
This enables you to reference the Worker consistently in your Vite config when using multiple Cloudflare environments.
:::

### Cloudflare Environments during development

You can also specify Cloudflare environments in development. For example, you could run:

```sh
CLOUDFLARE_ENV=development vite dev
```

It is common to use the default top-level environment as the development environment and then add additional environments as necessary.

:::note
Running `vite dev` or `vite build` without providing `CLOUDFLARE_ENV` will use the default top-level Cloudflare environment.
In the above example, the value of `MY_VAR` would be `'Top-level var'`.
Since Cloudflare environments are applied at `dev` and `build` time, specifying `CLOUDFLARE_ENV` when running `vite preview` or `wrangler deploy` will have no effect.
:::

### Combining Cloudflare Environments and Vite Modes

You may want to combine the concepts of [Cloudflare environments](/workers/wrangler/environments/) and [Vite modes](https://vite.dev/guide/env-and-mode.html#modes).

With this approach, the Vite mode can be used to select the Cloudflare environment and a single method can be used to determine environment specific configuration and code.

Let's use the previous example:

<WranglerConfig>

```toml
# wrangler.toml

name = "my-worker"
compatibility_date = "2024-12-30"
main = "./src/index.ts"

vars = { MY_VAR = "Top-level var" }

[env.staging]
vars = { MY_VAR = "Staging var" }

[env.production]
vars = { MY_VAR = "Production var" }
```

</WranglerConfig>

Next, provide `.env.staging` and `.env.production` files:

```sh
# .env.staging

CLOUDFLARE_ENV=staging
```

```sh
# .env.production

CLOUDFLARE_ENV=production
```

By default, `vite build` uses the **'production'** Vite mode, which loads `.env.production` to get the environment variables that are used in the build.

- This sets `CLOUDFLARE_ENV=production`, selecting the production Cloudflare environment.
- `MY_VAR` becomes `'Production var'`.

To build with the **staging mode**, run:

```sh
vite build --mode staging
```

- This loads `.env.staging`.
- The value of `MY_VAR` will be `'Staging var'`.

## Secrets in local development

Secrets can be provided to your Worker in local development using a [`.dev.vars`](/workers/configuration/secrets/#local-development-with-secrets) file. If you are using [Cloudflare Environments](../cloudflare-environments) then the relevant `.dev.vars` file will be selected.

For example,

```sh
CLOUDFLARE_ENV=staging vite dev
```

Will load `.dev.vars.staging` if it exists (falling back to `.dev.vars` if otherwise).

:::note
When you run `vite build`, the relevant `.dev.vars[.env-name]` file is copied to the output directory for use during `vite preview`. It is **not** deployed with your Worker.
:::

## Migrating from `wrangler dev`

Migrating from `wrangler dev` is a simple process and you can follow the instructions in [Get started](../get-started/).

There are a few key differences to highlight:

#### 1. Input and output Worker configuration files

- Your existing Wrangler configuration file is treated as an **input** configuration.
- A separate output configuration is generated at build time, capturing a snapshot of your config and referencing your build artifacts. This is the configuration that is used for **preview** and **deployment**.

#### 2. Redundant fields in the Wrangler configuration file

- Some fields are either ignored or replaced by Vite options, as they are either no longer applicable or are replaced by Vite equivalents.
- If these options are provided, then warnings will be printed to the console with suggestions for how to proceed. For example, you will see console warnings if you use fields like `alias` or `define` that have direct Vite equivalents.

## API

### `cloudflare`

The `cloudflare` plugin should be included in the Vite `plugins` array:

```ts {4, 7}
// vite.config.ts

import { defineConfig } from "vite";
import { cloudflare } from "@cloudflare/vite-plugin";

export default defineConfig({
plugins: [cloudflare()],
});
```

It accepts an optional `PluginConfig` parameter.

### `interface PluginConfig`

- `configPath?: string`

An optional path to your Worker config file.
By default, a `wrangler.toml`, `wrangler.json`, or `wrangler.jsonc` file in the root of your application will be used as the Worker config.

- `viteEnvironment?: { name?: string }`

Optional Vite environment options.
By default, the environment name is the Worker name with `-` characters replaced with `_`.
Setting the name here will override this.

- `persistState?: boolean | { path: string }`

An optional override for state persistence.
By default, state is persisted to `.wrangler/state` in a `v3` subdirectory.
A custom `path` can be provided or, alternatively, persistence can be disabled by setting the value to `false`.

- `auxiliaryWorkers?: Array<AuxiliaryWorkerConfig>`

An optional array of auxiliary Workers.
You can use [service bindings](/workers/runtime-apis/bindings/service-bindings/) to call auxiliary Workers from your main (entry) Worker.
All requests are routed through your entry Worker.
During the build, each Worker is output to a separate subdirectory of `dist`.

:::note
When running `wrangler deploy`, only your main (entry) Worker will be deployed.
If using multiple Workers, each must be deployed individually.
You can inspect the `dist` directory and then run `wrangler deploy -c path-to-worker-output-config` for each.
:::

### `interface AuxiliaryWorkerConfig`

- `configPath: string`

A required path to your Worker config file.

- `viteEnvironment?: { name?: string }`

Optional Vite environment options.
By default, the environment name is the Worker name with `-` characters replaced with `_`.
Setting the name here will override this.
Loading
Loading