Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit d99b0d3

Browse files
committed
Add docs for new v2 features
1 parent c28c916 commit d99b0d3

File tree

14 files changed

+395
-16
lines changed

14 files changed

+395
-16
lines changed

docs/.vitepress/config.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ module.exports = {
4848
{ text: "🗺 Source Maps", link: "/source-maps.html" },
4949
{ text: "🕸 Web Standards", link: "/standards.html" },
5050
{ text: "📄 HTMLRewriter", link: "/html-rewriter.html" },
51+
{ text: "⚡️ Live Reload", link: "/live-reload.html" },
52+
{ text: "📅 Compatibility Dates", link: "/compatibility.html" },
5153
{ text: "🤹 Jest Environment", link: "/jest.html" },
5254
],
5355
},

docs/api.md

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,46 @@ const mf = new Miniflare({ ... });
9898
await mf.reload();
9999
```
100100

101+
Miniflare will emit a `reload` event whenever it reloads too:
102+
103+
```js
104+
const mf = new Miniflare({ ... });
105+
mf.addEventListener("reload", (event) => {
106+
console.log("Worker reloaded!");
107+
});
108+
```
109+
110+
### Updating Options and the Global Scope
111+
112+
You can use the `setOptions` method to update the options of an existing
113+
`Miniflare` instance. This accepts the same options object as the
114+
`new Miniflare` constructor, applies those options, then reloads the worker.
115+
116+
```js
117+
const mf = new Miniflare({
118+
script: "...",
119+
kvNamespaces: ["TEST_NAMESPACE"],
120+
bindings: { KEY: "value1" },
121+
});
122+
123+
// Only updates `bindings`, leaves `script` and `kvNamespaces` alone
124+
await mf.setOptions({
125+
bindings: { KEY: "value2" },
126+
});
127+
```
128+
129+
You can also access the global scope of the sandbox directly using the
130+
`getGlobalScope` method. Ideally, use should use the `setOptions` method when
131+
updating the environment dynamically though:
132+
133+
```js
134+
const mf = new Miniflare({
135+
globals: { KEY: "value1" },
136+
});
137+
const globalScope = await mf.getGlobalScope();
138+
globalScope.KEY = "value2";
139+
```
140+
101141
### Dispatching Events
102142

103143
`dispatchFetch` and `dispatchScheduled` dispatch `fetch` and `scheduled` events
@@ -138,7 +178,7 @@ returns a
138178
[Node.js `http.Server`](https://nodejs.org/api/http.html#http_class_http_server)
139179
instance:
140180

141-
```js{10}
181+
```js{11}
142182
import { Miniflare } from "miniflare";
143183
144184
const mf = new Miniflare({
@@ -153,6 +193,52 @@ const server = await mf.startServer();
153193
console.log("Listening on :5000");
154194
```
155195

196+
You can also just create the server with `createServer` and start it yourself.
197+
Note that you're then responsible for setting the correct host and port:
198+
199+
```js
200+
const mf = new Miniflare({
201+
script: "...",
202+
port: 5000,
203+
});
204+
const server = await mf.createServer();
205+
const { HTTPPlugin } = await mf.getPlugins();
206+
server.listen(HTTPPlugin.port, () => {
207+
console.log(`Listening on :${HTTPPlugin.port}`);
208+
});
209+
```
210+
211+
#### `Request#cf` Object
212+
213+
By default, Miniflare will fetch the `Request#cf` object from a trusted
214+
Cloudflare endpoint. You can disable this behaviour, using the `cfFetch` option:
215+
216+
```js
217+
const mf = new Miniflare({
218+
cfFetch: false,
219+
});
220+
```
221+
222+
You can also provide a custom request metadata provider, which takes the
223+
incoming Node request and may look-up information in a geo-IP database:
224+
225+
```js
226+
const mf = new Miniflare({
227+
async metaProvider(req) {
228+
return {
229+
forwardedProto: req.headers["X-Forwarded-Proto"],
230+
realIp: req.headers["X-Forwarded-For"],
231+
cf: {
232+
// Could get these from a geo-IP database
233+
colo: "SFO",
234+
country: "US",
235+
// ...
236+
},
237+
};
238+
},
239+
});
240+
```
241+
156242
### HTTPS Server
157243

158244
To start an HTTPS server instead, set the `https` option. To use an
@@ -197,6 +283,21 @@ const mf = new Miniflare({
197283
If both a string and path are specified for an option (e.g. `httpsKey` and
198284
`httpsKeyPath`), the string will be preferred.
199285

286+
### CRON Scheduler
287+
288+
To start a CRON scheduler like the CLI's, use the `startScheduler` method. This
289+
will dispatch `scheduled` events according to the specified CRON expressions:
290+
291+
```js
292+
const mf = new Miniflare({
293+
crons: ["30 * * * *"],
294+
});
295+
const scheduler = await mf.startScheduler();
296+
// ...
297+
// Stop dispatching events
298+
await scheduler.dispose();
299+
```
300+
200301
### Logging
201302

202303
By default, `[mf:*]` logs as seen in the CLI are disabled when using the API. To

docs/builds.md

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ Custom builds can be enabled by specifying a build command. You can also specify
88
a path to run the build in, and a path to watch:
99

1010
```shell
11-
$ miniflare --build-command "npm run build"
11+
$ miniflare --build-command "npm run build" # or -B
1212
$ miniflare --build-command "npm run build" --build-base-path "build"
13-
$ miniflare --build-command "npm run build" --build-watch-path "source"
13+
$ miniflare --build-command "npm run build" --build-watch-path "source1" --build-watch-path "source2"
1414
```
1515

1616
```toml
@@ -27,7 +27,7 @@ const mf = new Miniflare({
2727
buildCommand: "npm run build",
2828
// Below options are optional
2929
buildBasePath: "build",
30-
buildWatchPath: "source", // Defaults to "src" if command set
30+
buildWatchPaths: ["source1", "source2"], // Defaults to "src" if command set
3131
});
3232
```
3333

@@ -49,6 +49,14 @@ assumed.
4949
:::
5050
<!--prettier-ignore-end-->
5151

52+
<!--prettier-ignore-start-->
53+
::: tip
54+
When running your custom build script, Miniflare will set the environment
55+
variable `MINIFLARE=1`. You can use this to customise build behaviour during
56+
local development.
57+
:::
58+
<!--prettier-ignore-end-->
59+
5260
## Wrangler Builds
5361

5462
Miniflare supports building `webpack` and `rust` type Wrangler projects too.

docs/cache.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,19 @@ When using Redis, each key will be prefixed with the namespace. If you're using
5858
this with the API, make sure you call `dispose` on your `Miniflare` instance to
5959
close database connections.
6060

61+
<!--prettier-ignore-start-->
62+
::: warning
63+
Redis support is not included by default. You must install an optional peer dependency:
64+
```
65+
$ npm install -D @miniflare/storage-redis
66+
```
67+
:::
68+
<!--prettier-ignore-end-->
69+
6170
## Manipulating Outside Workers
6271

6372
For testing, it can be useful to put/match data from cache outside a worker. You
64-
can do this with the `getCache` method:
73+
can do this with the `getCaches` method:
6574

6675
```js{23-33}
6776
import { Miniflare, Response } from "miniflare";

docs/cli.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,16 @@ You can also install and invoke the CLI using `npx`:
1818
$ npx miniflare
1919
```
2020

21+
<!--prettier-ignore-start-->
22+
::: warning
23+
Miniflare requires at least **Node.js 16.7.0**, as it makes extensive use of
24+
recently added web standards. You should use the latest Node.js version if
25+
possible, as Cloudflare Workers use a very up-to-date version of V8. Consider
26+
using a Node.js version manager such as https://volta.sh/ or
27+
https://github.com/nvm-sh/nvm.
28+
:::
29+
<!--prettier-ignore-end-->
30+
2131
## Usage
2232

2333
If `worker.js` contains the following worker script:
@@ -123,6 +133,18 @@ main = "./worker.js"
123133
}
124134
```
125135

136+
### `Request#cf` Object
137+
138+
For a more accurate development experience, Miniflare automatically fetches the
139+
`cf` object for incoming requests (containing IP and location data) from a
140+
trusted Cloudflare endpoint, caching it for 30 days. You can disable this
141+
behaviour, falling back to a default `cf` object, using the `--no-cf-fetch`
142+
flag:
143+
144+
```shell
145+
$ miniflare worker.js --no-cf-fetch
146+
```
147+
126148
### HTTPS Server
127149

128150
By default, Miniflare starts an HTTP server. To start an HTTPS server instead,

docs/compatibility.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# 📅 Compatibility Dates
2+
3+
- [Compatibility Dates Reference](https://developers.cloudflare.com/workers/platform/compatibility-dates)
4+
5+
## Compatibility Dates
6+
7+
Like the Workers runtime, Miniflare uses compatibility dates to opt-into
8+
backwards-incompatible changes from a specific date. If one isn't set, it will
9+
default to some time far in the past.
10+
11+
```shell
12+
$ miniflare --compat-date 2021-11-12
13+
```
14+
15+
```toml
16+
# wrangler.toml
17+
compatibility_date = "2021-11-12"
18+
```
19+
20+
```js
21+
const mf = new Miniflare({
22+
compatibilityDate: "2021-11-12",
23+
});
24+
```
25+
26+
## Compatibility Flags
27+
28+
Miniflare also lets you opt-in/out of specific changes using compatibility
29+
flags:
30+
31+
```shell
32+
$ miniflare --compat-flag formdata_parser_supports_files --compat-flag durable_object_fetch_allows_relative_url
33+
```
34+
35+
```toml
36+
# wrangler.toml
37+
compatibility_flags = [
38+
"formdata_parser_supports_files",
39+
"durable_object_fetch_allows_relative_url"
40+
]
41+
```
42+
43+
```js
44+
const mf = new Miniflare({
45+
compatibilityFlags: [
46+
"formdata_parser_supports_files",
47+
"durable_object_fetch_allows_relative_url",
48+
],
49+
});
50+
```
51+
52+
Specifically Miniflare supports the following flags:
53+
54+
- [`durable_object_fetch_requires_full_url`/`durable_object_fetch_allows_relative_url`](https://developers.cloudflare.com/workers/platform/compatibility-dates#durable-object-stubfetch-requires-a-full-url)
55+
- [`fetch_refuses_unknown_protocols`/`fetch_treats_unknown_protocols_as_http`](https://developers.cloudflare.com/workers/platform/compatibility-dates#fetch-improperly-interprets-unknown-protocols-as-http)
56+
- [`formdata_parser_supports_files`/`formdata_parser_converts_files_to_strings`](https://developers.cloudflare.com/workers/platform/compatibility-dates#formdata-parsing-supports-file)

docs/durable-objects.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,35 @@ When using Redis, each key will be prefixed with the object name and instance.
7979
If you're using this with the API, make sure you call `dispose` on your
8080
`Miniflare` instance to close database connections.
8181

82+
<!--prettier-ignore-start-->
83+
::: warning
84+
Redis support is not included by default. You must install an optional peer dependency:
85+
```
86+
$ npm install -D @miniflare/storage-redis
87+
```
88+
:::
89+
<!--prettier-ignore-end-->
90+
91+
## Validation
92+
93+
Like the real Workers runtime, Miniflare will throw errors when:
94+
95+
- The string passed to `DurableObjectNamespace#idFromString(hexId)` is not 64
96+
hex digits
97+
- The hex-ID passed to `DurableObjectNamespace#idFromString(hexId)` is for a
98+
different Durable Object
99+
- The ID passed to `DurableObjectNamespace#get(id)` is for a different Durable
100+
Object
101+
- Keys are greater than `2KiB` or `undefined`
102+
- Values are greater than `32KiB`
103+
- Attempting to `get`, `put` or `delete` more than `128` keys
104+
- Attempting to modify more than `128` keys in a transaction
105+
- Attempting to `put` an `undefined` value
106+
- Attempting to list keys with a negative `limit`
107+
- Attempting to perform an operation in a rolledback transaction or in a
108+
transaction that has already committed
109+
- Attempting to call `deleteAll()` in a transaction
110+
82111
## Manipulating Outside Workers
83112

84113
For testing, it can be useful to put/get data from Durable Object storage

docs/jest.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ $ npm install -D jest-environment-miniflare jest
1313

1414
In the following examples, we'll assume your `package.json` contains
1515
`"type": "module"`, and that you're using a tool to bundle your worker. See
16-
[⚡️ Developing with esbuild](/esbuild.html) for an example.
16+
[⚡️ Developing with esbuild](/recipes/esbuild.html) for an example.
1717

1818
To enable the Miniflare environment, set the
1919
[`testEnvironment` option](https://jestjs.io/docs/configuration#testenvironment-string)

docs/kv.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,31 @@ Metadata will be prefixed with the namespace and `:meta:`. If you're using this
8484
with the API, make sure you call `dispose` on your `Miniflare` instance to close
8585
database connections.
8686

87+
<!--prettier-ignore-start-->
88+
::: warning
89+
Redis support is not included by default. You must install an optional peer dependency:
90+
```
91+
$ npm install -D @miniflare/storage-redis
92+
```
93+
:::
94+
<!--prettier-ignore-end-->
95+
96+
## Validation
97+
98+
Like the real Workers runtime, Miniflare will throw errors when:
99+
100+
- Keys are empty, `.`, `..`, `undefined`, or greater than `512B` when UTF-8
101+
encoded
102+
- Values are greater than `25MiB`
103+
- Metadata is greater than `1KiB`
104+
- The `cacheTtl` option is less than `60s`
105+
- The `expirationTtl` option is non-numeric, less than or equal 0, or less than
106+
`60s`
107+
- The `expiration` option is non-numeric, less than or equal the current time,
108+
or less than `60s` in the future
109+
- The `limit` passed to `KVNamespace#list()` is non-numeric, less than or equal
110+
`0`, or greater than `1000`
111+
87112
## Manipulating Outside Workers
88113

89114
For testing, it can be useful to put/get data from KV outside a worker. You can

0 commit comments

Comments
 (0)