Skip to content

Commit 986c904

Browse files
cloudflare: update docs to 0.4 (#57)
Co-authored-by: Victor Berchet <[email protected]>
1 parent 14a58d9 commit 986c904

File tree

11 files changed

+471
-8
lines changed

11 files changed

+471
-8
lines changed

pages/cloudflare/0.3/_meta.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"index": "Overview",
3+
"get-started": "",
4+
"bindings": "",
5+
"caching": "",
6+
"examples": ""
7+
}

pages/cloudflare/0.3/bindings.mdx

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { SITE } from '../../../config';
2+
import { Callout } from 'nextra/components';
3+
4+
### Bindings
5+
6+
[Bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) allow your Worker to interact with resources on the Cloudflare Developer Platform. When you declare a binding on your Worker, you grant it a specific capability, such as being able to read and write files to an [R2](https://developers.cloudflare.com/r2/) bucket.
7+
8+
#### How to configure your Next.js app so it can access bindings
9+
10+
Install [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare), and then add a [wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/) in the root directory of your Next.js app, as described in [Get Started](/cloudflare/get-started#3-create-a-wranglerjson-file).
11+
12+
#### How to access bindings in your Next.js app
13+
14+
You can access [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) from any route of your Next.js app via `getCloudflareContext`:
15+
16+
```js
17+
import { getCloudflareContext } from "@opennextjs/cloudflare";
18+
19+
export async function GET(request) {
20+
let responseText = "Hello World";
21+
22+
const myKv = (await getCloudflareContext()).env.MY_KV_NAMESPACE;
23+
await myKv.put("foo", "bar");
24+
const foo = await myKv.get("foo");
25+
26+
return new Response(foo);
27+
}
28+
```
29+
30+
#### How to add bindings to your Worker
31+
32+
Add bindings to your Worker by adding them to your [wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/).
33+
34+
## TypeScript type declarations for bindings
35+
36+
To ensure that the `env` object from `(await getCloudflareContext()).env` above has accurate TypeScript types, run the following Wrangler command to [generate types that match your Worker's configuration](https://developers.cloudflare.com/workers/languages/typescript/#generate-types-that-match-your-workers-configuration-experimental):
37+
38+
```
39+
npx wrangler types --experimental-include-runtime
40+
```
41+
42+
This will generate a `d.ts` file and (by default) save it to `.wrangler/types/runtime.d.ts`. You will be prompted in the command's output to add that file to your `tsconfig.json`'s `compilerOptions.types` array.
43+
44+
If you would like to commit the file to git, you can provide a custom path. Here, for instance, the `runtime.d.ts` file will be saved to the root of your project:
45+
46+
```bash
47+
npx wrangler types --experimental-include-runtime="./runtime.d.ts"
48+
```
49+
50+
To ensure that your types are always up-to-date, make sure to run `wrangler types --experimental-include-runtime` after any changes to your config file.
51+
52+
## Other Cloudflare APIs (`cf`, `ctx`)
53+
54+
You can access context about the incoming request from the [`cf` object](https://developers.cloudflare.com/workers/runtime-apis/request/#the-cf-property-requestinitcfproperties), as well as lifecycle methods from the [`ctx` object](https://developers.cloudflare.com/workers/runtime-apis/context) from the return value of [`getCloudflareContext()`](https://github.com/opennextjs/opennextjs-cloudflare/blob/main/packages/cloudflare/src/api/get-cloudflare-context.ts):
55+
56+
```js
57+
import { getCloudflareContext } from "@opennextjs/cloudflare";
58+
59+
60+
export async function GET(request) {
61+
const { env, cf, ctx } = await getCloudflareContext();
62+
63+
// ...
64+
}
65+
```

pages/cloudflare/0.3/caching.mdx

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { SITE } from '../../../config';
2+
import { Callout } from 'nextra/components';
3+
4+
## Caching
5+
6+
`@opennextjs/cloudflare` supports [caching](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data).
7+
8+
By default, all `fetch()` subrequests made in your Next.js app are cached. Refer to the [Next.js documentation](https://nextjs.org/docs/app/building-your-application/caching#opting-out-1) for information about how to disable caching for an individual subrequest, or for an entire route.
9+
10+
[The cache persists across deployments](https://nextjs.org/docs/app/building-your-application/caching#data-cache). You are responsible for revalidating/purging this cache.
11+
12+
Note that [Revalidating](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) is not yet supported.
13+
14+
Next.js primes the cache at build time. The build time values are serverd by the [Workers Assets](https://developers.cloudflare.com/workers/static-assets/).
15+
16+
<Callout>
17+
Workers KV is eventually consistent, which means that it can take up to 60 seconds for updates to be reflected globally, when using the default TTL of 60 seconds.
18+
</Callout>
19+
20+
### How to enable caching
21+
22+
`@opennextjs/cloudflare` uses [Workers KV](https://developers.cloudflare.com/kv/) as the cache for your Next.js app. Workers KV is [fast](https://blog.cloudflare.com/faster-workers-kv) and uses Cloudflare's [Tiered Cache](https://developers.cloudflare.com/cache/how-to/tiered-cache/) to increase cache hit rates. When you write cached data to Workers KV, you write to storage that can be read by any Cloudflare location. This means your app can fetch data, cache it in KV, and then subsequent requests anywhere around the world can read from this cache.
23+
24+
To enable caching, you must:
25+
26+
#### 1. Create a KV namespace
27+
28+
```
29+
npx wrangler@latest kv namespace create <YOUR_NAMESPACE_NAME>
30+
```
31+
32+
#### 2. Add the KV namespace to your Worker
33+
34+
The binding name used in your app's worker is `NEXT_CACHE_WORKERS_KV`.
35+
36+
```jsonc
37+
// wrangler.json
38+
{
39+
// ...
40+
"kv_namespaces": [
41+
{
42+
"binding": "NEXT_CACHE_WORKERS_KV",
43+
"id": "<BINDING_ID>"
44+
}
45+
]
46+
}
47+
```

pages/cloudflare/0.3/examples.mdx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { SITE } from '../../../config';
2+
import { Callout } from 'nextra/components';
3+
4+
## Examples
5+
6+
To create a new Next.js app, pre-configured to run on Cloudflare using `@opennextjs/cloudflare`, run:
7+
8+
```
9+
npm create cloudflare@latest -- my-next-app --framework=next --experimental
10+
```
11+
12+
### Basic starter projects
13+
14+
Basic example apps are included in the repository for `@opennextjs/cloudflare` package:
15+
16+
- [*`create-next-app`*](https://github.com/opennextjs/opennextjs-cloudflare/tree/main/examples/create-next-app) — a Next.js project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
17+
- [*`api`*](https://github.com/opennextjs/opennextjs-cloudflare/tree/main/examples/api) — a minimal Next.js project with a single API route
18+
- [*`middleware`*](https://github.com/opennextjs/opennextjs-cloudflare/tree/main/examples/middleware) — a minimal Next.js project using middleware
19+
- [*`vercel-blog-starter`*](https://github.com/opennextjs/opennextjs-cloudflare/tree/main/examples/vercel-blog-starter) — a blog project using SSG
20+
21+
You can use these to understand how to configure your Next.js app to use `@opennextjs/cloudflare`, or refer to [Get Started](/cloudflare/get-started).
22+
23+
### Next.js Commerce Demo
24+
25+
The [Next.js Commerce demo app](https://github.com/vercel/commerce/tree/v1) works with `@opennextjs/cloudflare`. You can view a deployed version of it [here](https://vercel-commerce-on-workers.web-experiments.workers.dev/).
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import { SITE } from '../../../config';
2+
import { Callout } from 'nextra/components';
3+
4+
### Get Started
5+
6+
#### New apps
7+
8+
To create a new Next.js app, pre-configured to run on Cloudflare using `@opennextjs/cloudflare`, run:
9+
10+
```
11+
npm create cloudflare@latest -- my-next-app --framework=next --experimental
12+
```
13+
14+
#### Existing Next.js apps
15+
16+
##### 1. Install @opennextjs/cloudflare
17+
18+
First, install [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare):
19+
20+
```sh
21+
npm install --save-dev @opennextjs/cloudflare@latest
22+
```
23+
24+
##### 2. Install Wrangler
25+
26+
Install the [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/) as a devDependency:
27+
28+
```npm
29+
npm install --save-dev wrangler@latest
30+
```
31+
32+
<Callout>
33+
You must use Wrangler version `3.99.0` or later to deploy Next.js apps using `@opennextjs/cloudflare`.
34+
</Callout>
35+
36+
##### 3. Create a wrangler configuration file
37+
38+
<Callout type='info'>
39+
This step is optional since `@opennextjs/cloudflare` creates this file for you during the build process (if not already present).
40+
</Callout>
41+
42+
A [wrangler configuration file](https://developers.cloudflare.com/workers/wrangler/configuration/) is needed for your
43+
application to be previewed and deployed, it is also where you configure your Worker and define what resources it can access via [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings).
44+
45+
You can create one yourself in the root directory of your Next.js app with the name `wrangler.json` and the following content:
46+
```jsonc
47+
{
48+
"$schema": "node_modules/wrangler/config-schema.json",
49+
"main": ".open-next/worker.js",
50+
"name": "my-app",
51+
"compatibility_date": "2024-12-30",
52+
"compatibility_flags": ["nodejs_compat"],
53+
"assets": {
54+
"directory": ".open-next/assets",
55+
"binding": "ASSETS",
56+
},
57+
"kv_namespaces": [
58+
// Create a KV binding with the binding name "NEXT_CACHE_WORKERS_KV"
59+
// to enable the KV based caching:
60+
// {
61+
// "binding": "NEXT_CACHE_WORKERS_KV",
62+
// "id": "<BINDING_ID>"
63+
// }
64+
],
65+
}
66+
```
67+
68+
<Callout>
69+
As shown above:
70+
- You must enable the [`nodejs_compat` compatibility flag](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) *and* set your [compatibility date](https://developers.cloudflare.com/workers/configuration/compatibility-dates/) to `2024-09-23` or later, in order for your Next.js app to work with @opennextjs/cloudflare
71+
- The `main` and `assets` values should also not be changed unless you modify the build output result in some way
72+
- You can add a binding named `NEXT_CACHE_WORKERS_KV` to make use of Next.js' caching as described in the [Caching docs](/cloudflare/caching)
73+
</Callout>
74+
75+
##### 4. Add an `open-next.config.ts` file
76+
77+
<Callout type='info'>
78+
This step is optional since `@opennextjs/cloudflare` creates this file for you during the build process (if not already present).
79+
</Callout>
80+
81+
Add a [`open-next.config.ts`](https://opennext.js.org/aws/config) file to the root directory of your Next.js app:
82+
83+
```ts
84+
import type { OpenNextConfig } from "@opennextjs/aws/types/open-next.js";
85+
import cache from "@opennextjs/cloudflare/kvCache";
86+
87+
const config: OpenNextConfig = {
88+
default: {
89+
override: {
90+
wrapper: "cloudflare-node",
91+
converter: "edge",
92+
// set `incrementalCache` to "dummy" to disable KV cache
93+
incrementalCache: async () => cache,
94+
tagCache: "dummy",
95+
queue: "dummy",
96+
},
97+
},
98+
99+
middleware: {
100+
external: true,
101+
override: {
102+
wrapper: "cloudflare-edge",
103+
converter: "edge",
104+
proxyExternalRequest: "fetch",
105+
},
106+
},
107+
};
108+
109+
export default config;
110+
```
111+
112+
<Callout>
113+
To use the `OpenNextConfig` type as illustrated above (which is not necessary), you need to install the `@opennextjs/aws` NPM package as a dev dependency.
114+
</Callout>
115+
116+
##### 5. Add a `.dev.vars` file
117+
118+
Then, add a [`.dev.vars`](https://developers.cloudflare.com/workers/testing/local-development/#local-only-environment-variables) file to the root directory of your Next.js app:
119+
120+
```text
121+
NEXTJS_ENV=development
122+
```
123+
124+
The `NEXTJS_ENV` variable defines the environment to use when loading Next.js `.env` files. It defaults to "production" when not defined.
125+
126+
##### 6. Update the `package.json` file
127+
128+
Add the following to the scripts field of your `package.json` file:
129+
130+
```json
131+
"build:worker": "opennextjs-cloudflare",
132+
"dev:worker": "wrangler dev --port 8771",
133+
"preview": "npm run build:worker && npm run dev:worker",
134+
"deploy": "npm run build:worker && wrangler deploy",
135+
"cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts",
136+
```
137+
138+
- `npm run build:worker`: Runs the [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare) adapter. This first builds your app by running the `build` script in your `package.json` (Next.js apps use `next build` by default), and then transforms the build output to a format that you can run locally using [Wrangler](https://developers.cloudflare.com/workers/wrangler/), and deploy to Cloudflare. The build command used by OpenNext can be overridden with the `buildCommand` option in your OpenNext config.
139+
- `npm run dev:worker`: Takes the output generated by `build:worker` and runs it locally in [workerd](https://github.com/cloudflare/workerd), the open-source Workers Runtime, allowing you to run the app locally in the same environment that it will run in production. If you instead run `next dev`, your app will run in Node.js, which is a different JavaScript runtime from the Workers runtime, with differences in behavior and APIs.
140+
- `npm run preview`: Runs `build:worker` and then `dev:worker`, allowing you to quickly preview your app running locally in the Workers runtime, via a single command.
141+
- `npm run deploy`: Builds your app, and then deploys it to Cloudflare
142+
- `cf-typegen`: Generates a `cloudflare-env.d.ts` file at the root of your project containing [the types for the `env`](https://developers.cloudflare.com/workers/wrangler/commands/#types).
143+
144+
##### 7. Add caching with Workers KV
145+
146+
See the [Caching docs](/cloudflare/caching) for information on enabling Next.js caching in your OpenNext project.
147+
148+
##### 8. Remove any `export const runtime = "edge";` if present
149+
150+
Before deploying your app, remove the `export const runtime = "edge";` line from any of your source files.
151+
152+
The edge runtime is not supported yet with `@opennextjs/cloudflare`.
153+
154+
##### 9. Add `.open-next` to `.gitignore`
155+
156+
You should add `.open-next` to your `.gitignore` file to prevent the build output from being committed to your repository.
157+
158+
##### 10. Remove `@cloudflare/next-on-pages` (if necessary)
159+
160+
If your Next.js app currently uses `@cloudflare/next-on-pages`, you'll want to remove it, and make a few changes.
161+
162+
Uninstalling the [`@cloudflare/next-on-pages`](https://www.npmjs.com/package/@cloudflare/next-on-pages) package as well as the [`eslint-plugin-next-on-pages`](https://www.npmjs.com/package/eslint-plugin-next-on-pages) package if present.
163+
164+
Remove any reference of these packages from your source and configuration files.
165+
This includes:
166+
- `setupDevPlatform()` calls in your Next.js config file
167+
- `getRequestContext` imports from `@cloudflare/next-on-pages` from your source files
168+
(those can be replaced with `getCloudflareContext` calls from `@opennextjs/cloudflare`)
169+
- next-on-pages eslint rules set in your Eslint config file
170+
171+
##### 11. Develop locally
172+
173+
You can continue to run `next dev` when developing locally.
174+
175+
During local development, you can access local versions of Cloudflare bindings as indicated in the [bindings documentation](./bindings).
176+
177+
In step 3, we also added the `npm run preview:worker`, which allows you to quickly preview your app running locally in the Workers runtime, rather than in Node.js. This allows you to test changes in the same runtime as your app will run in when deployed to Cloudflare.
178+
179+
##### 12. Deploy to Cloudflare Workers
180+
181+
Either deploy via the command line:
182+
183+
```sh
184+
npm run deploy:worker
185+
```
186+
187+
Or [connect a Github or Gitlab repository](https://developers.cloudflare.com/workers/ci-cd/), and Cloudflare will automatically build and deploy each pull request you merge to your production branch.

0 commit comments

Comments
 (0)