Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Add docs for Cloudflare adapter #3

Merged
merged 21 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
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
2 changes: 1 addition & 1 deletion pages/aws/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ If you're migrating from V2 to V3, you can find the migration guide [here](/migr
---

OpenNext takes the Next.js build output and converts it into packages that can be deployed across a variety of environments.
Natively OpenNext has support for AWS Lambda and classic Node Server. It also offer partial support for the `edge` runtime in Cloudflare Workers.
Natively OpenNext has support for AWS Lambda, [Cloudflare](/cloudflare), and classic Node.js Server.

One notable feature of OpenNext is its ability to split the Next.js output, enabling selective deployment to different targets such as AWS Lambda, Cloudflare Workers, or Amazon ECS. This facilitates a tailored deployment strategy that aligns with the specific needs of your application.

Expand Down
65 changes: 65 additions & 0 deletions pages/cloudflare/bindings.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { SITE } from '../../config';
import { Callout } from 'nextra/components';

### Bindings

[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.

#### How to configure your Next.js app so it can access bindings

Install [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare), and then add a `wrangler.toml` file in the root directory of your Next.js app, as described in [Get Started](/cloudflare/get-started), y
irvinebroque marked this conversation as resolved.
Show resolved Hide resolved

#### How to access bindings in your Next.js app

You can access [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) from any route of your Next.js app via `getCloudlfareContext`:

```js
import { getCloudflareContext } from "@cloudflare/next-on-pages";

export async function GET(request) {
let responseText = "Hello World";

const myKv = (await getCloudflareContext()).env.MY_KV_NAMESPACE;
await myKv.put("foo", "bar");
const foo = await myKv.get("foo");

return new Response(foo);
}
```

#### How to add bindings to your Worker

Add bindings to your Worker by [adding them to your `wrangler.toml` configuration file](/pages/functions/wrangler-configuration/).

## TypeScript type declarations for bindings

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):

```
npx wrangler types --experimental-include-runtime
```

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.

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:

```bash
npx wrangler types --experimental-include-runtime="./runtime.d.ts"
```

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.

## Other Cloudflare APIs (`cf`, `ctx`)

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):

```js
import { getCloudflareContext } from "@opennextjs/cloudflare";


export async function GET(request) {
const { env, cf, ctx } = await getCloudflareContext();

// ...
}
```
38 changes: 38 additions & 0 deletions pages/cloudflare/caching.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { SITE } from '../../config';
import { Callout } from 'nextra/components';

## Caching

`@opennextjs/cloudflare` supports [caching](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data) and [revalidating](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) data returned by subrequests you make in your app by calling [`fetch()`](https://developers.cloudflare.com/workers/runtime-apis/fetch/).

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.

[The cache persists across deployments](https://nextjs.org/docs/app/building-your-application/caching#data-cache). You are responsible for revalidating/purging this cache.

:::note
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.
:::

### How to enable caching

`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.

To enable caching, you must:

#### 1. Create a KV namespace

```
npx wrangler@latest kv namespace create NEXT_CACHE_WORKERS_KV
```

#### 2. Add the KV namespace to your Worker

```
[[kv_namespaces]]
binding = "NEXT_CACHE_WORKERS_KV"
id = "<YOUR_NAMESPACE_ID>"
```

### 3. Set the name of the binding to `NEXT_CACHE_WORKERS_KV`

As shown above, the name of the binding that you configure for the KV namespace must be set to `NEXT_CACHE_WORKERS_KV`.
25 changes: 25 additions & 0 deletions pages/cloudflare/examples.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { SITE } from '../../config';
import { Callout } from 'nextra/components';

## Examples

To create a new Next.js app, pre-configured to run on Cloudflare using @opennextjs/cloudflare, run:

```
npm create cloudflare@latest --no-auto-update --experimental --framework next
```

### Basic starter projects

Two basic example apps are included in the repository for `@opennextjs/cloudflare` package:

- [*`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).
- [*`api`*](https://github.com/opennextjs/opennextjs-cloudflare/tree/main/examples/api) — a minimal Next.js project with a single API route

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).

### Next.js Commerce Demo

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](TODO).

To run this using `@opennextjs/cloudflare`, TODO.
96 changes: 96 additions & 0 deletions pages/cloudflare/get-started.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { SITE } from '../../config';
import { Callout } from 'nextra/components';

### Get Started

#### New apps

To create a new Next.js app, pre-configured to run on Cloudflare using @opennextjs/cloudflare, run:

```
npm create cloudflare@latest --no-auto-update --experimental --framework next
```

#### Existing Next.js apps

##### 1. Install @opennextjs/cloudflare

First, install [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare):

```sh
npm install --save-dev @opennextjs/cloudflare
```

##### 2. Add a `wrangler.toml` file

Then, add a [`wrangler.toml`](https://developers.cloudflare.com/workers/wrangler/configuration/) file to the root directory of your Next.js app:

```toml
main = ".worker-next/index.mjs"
name = "my-app"
compatibility_date = "2024-09-23"
compatibility_flags = ["nodejs_compat"]
experimental_assets = { directory = ".worker-next/assets", binding = "ASSETS" }
```

<Callout>
As shown above, 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.
</Callout>

`wrangler.toml` is where you configure your Worker and define what resources it can access via [bindings](/workers/runtime-apis/bindings/).

##### 3. Update `package.json`

Add the following to the scripts field of your `package.json` file:

```json
"build:worker": "cloudflare", TODO
"dev:worker": "wrangler dev --port 8771",
"preview:worker": "npm run build:worker && npm run dev:worker",
"deploy:worker": "npm run build:worker && wrangler deploy"
```

- `npm run build:worker`: Runs the [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare) adapter. This first builds your app by running `next build` behind the scenes, 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.
- `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.
- `npm run preview:worker`: Runs `build:worker` and then `preview:worker`, allowing you to quickly preview your app running locally in the Workers runtime, via a single command.
- `npm run deploy`: Builds your app, and then deploys it to Cloudflare

### 4. Add caching with Workers KV

`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.

To enable caching, you must:

##### Create a KV namespace

```
npx wrangler@latest kv namespace create NEXT_CACHE_WORKERS_KV
```

##### Add the KV namespace to your Worker

```
[[kv_namespaces]]
binding = "NEXT_CACHE_WORKERS_KV"
id = "<YOUR_NAMESPACE_ID>"
```

#### Set the name of the binding to `NEXT_CACHE_WORKERS_KV`

As shown above, the name of the binding that you configure for the KV namespace must be set to `NEXT_CACHE_WORKERS_KV`.

##### 5. Develop locally

You can continue to run `next dev` when developing locally.

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.

##### 6. Deploy to Cloudflare Workers

Either deploy via the command line:

```sh
npm run deploy
```

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.
61 changes: 60 additions & 1 deletion pages/cloudflare/index.mdx
Original file line number Diff line number Diff line change
@@ -1,2 +1,61 @@
### TODO
import { SITE } from '../../config';
import { Callout } from 'nextra/components';

## Cloudflare

The [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare) adapter lets you deploy Next.js apps to [Cloudflare Workers](https://developers.cloudflare.com/workers) and [Cloudflare Pages](https://developers.cloudflare.com/pages), using the [Node.js "runtime" from Next.js](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).

<Callout>
[@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare) is pre 1.0, and still in active development. You should try it, [report bugs](https://github.com/opennextjs/opennextjs-cloudflare/issues), and [share feedback](https://github.com/opennextjs/opennextjs-cloudflare/discussions) to help make running Next.js apps on Cloudflare easier. We don't quite yet recommend using it for mission-critical production apps.

You can also use [@cloudflare/next-on-pages](https://www.npmjs.com/package/@cloudflare/next-on-pages) to deploy Next.js apps to Cloudflare Pages. You can review the differences in supported Next.js features between @opennextjs/cloudflare and @cloudflare/next-on-pages [here](LINK).
</Callout>

### Get Started

##### New apps

To create a new Next.js app, pre-configured to run on Cloudflare using @opennextjs/cloudflare, run:

```
npm create cloudflare@latest --no-auto-update --experimental --framework next
```

##### Existing Next.js apps

Follow the guide [here](/cloudflare/get-started) to use [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare) with an existing Next.js app.

### Supported Next.js runtimes

Next.js has [two "runtimes"](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes) — "Edge" and "Node.js". When you use `@opennextjs/cloudflare`, your app can use the Node.js runtime, which is more fully featured, and allows you to use the [Node.js APIs](/workers/runtime-apis/nodejs/) that are provided by the Cloudflare Workers runtime.

This is an important difference from `@cloudflare/next-on-pages`, which only supports the "Edge" runtime. The Edge Runtime code in Next.js [intentionally constrains which APIs from Node.js can be used](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/webpack/plugins/middleware-plugin.ts#L820), and the "Edge" runtime does not support all Next.js features.

### Supported Next.js versions

`@opennextjs/cloudflare` supports all minor and patch version of Next.js 13 and 14.

### Supported Next.js features

- [x] [App Router](https://nextjs.org/docs/app) & [Pages Router](https://nextjs.org/docs/pages)
- [x] [API routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes)
- [x] [Dynamic routes](https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes)
- [x] [Static Site Generation (SSG)](https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation)
- [x] [Server-Side Rendering (SSR)](https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering)
- [x] [Incremental Static Regeneration (ISR)](https://nextjs.org/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)

### Not Yet Supported Next.js features

- [ ] [Partial Prerendering (PPR)](https://nextjs.org/docs/app/building-your-application/rendering/partial-prerendering)
- [ ] [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware)
- [ ] [Image optimization](https://nextjs.org/docs/pages/building-your-application/optimizing/images) (you can integrate Cloudflare Images with Next.js by following [this guide](https://developers.cloudflare.com/images/transform-images/integrate-with-frameworks/))
- [ ] [NextAuth.js](https://next-auth.js.org)
- [ ] [Experimental streaming support](https://nextjs.org/blog/next-15-rc#executing-code-after-a-response-with-nextafter-experimental)

### How @opennextjs/cloudflare Works

The OpenNext Cloudflare adapter works by taking the Next.js build output and transforming it, so that it can run in Cloudflare Workers.

When you add [@opennextjs/cloudflare](https://www.npmjs.com/package/@opennextjs/cloudflare) as a dependency to your Next.js app, and then run `pnpx cloudflare` (TODO: why pnpx?), the adapter first builds your app by running `next build`, 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.

irvinebroque marked this conversation as resolved.
Show resolved Hide resolved
You can view the code for @opennextjs/cloudflare [here](https://github.com/opennextjs/opennextjs-cloudflare/blob/main/packages/cloudflare/src) to understand what it does under the hood.
28 changes: 28 additions & 0 deletions pages/cloudflare/troubleshooting.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { SITE } from '../../config';
import { Callout } from 'nextra/components';

## Troubleshooting

### My app fails to build when I import a specific NPM package

First, make sure that the `nodejs_compat` compatibility flag is enabled, and your compatibility date is set to on or after "2024-09-23", in your `wrangler.toml` file. [Refer to the Workers docs](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) for more details on Node.js support in Cloudflare Workers.
irvinebroque marked this conversation as resolved.
Show resolved Hide resolved

Some NPM packages define multiple exports. For example:

```
"exports": {
"other": "./src/other.js",
"node": "./src/node.js",
"browser": "./src/browser.js",
"default": "./src/default.js"
},
```

When you use `@opennextjs/cloudflare`, [Wrangler](https://developers.cloudflare.com/workers/wrangler/) bundles your code before running it locally, or deploying it to Cloudflare. Wrangler has to choose which export to use, when you import a module. By default, Wrangler, which uses [esbuild](https://esbuild.github.io/), handles this in a way that is not compatible with some NPM packages.

You may want to modify how Wrangler resolves multiple exports, such that when you import packages, the `node` export, if present, is used. You can do do by defining the following variables in a `.env` file within the root directory of your Next.js app:

```
WRANGLER_BUILD_CONDITIONS=""
WRANGLER_BUILD_PLATFORM="node"
```
6 changes: 3 additions & 3 deletions pages/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { SITE } from '../config';

# OpenNext

Next.js, unlike Remix, Astro, or the other modern frontends, doesn't have a way to self-host across different platforms. You can run it as a Node application. But this doesn't work the same way as it does on Vercel.
Next.js, unlike Remix, Astro, or the other modern frontends, doesn't have a way to self-host across different platforms. You can run it as a Node.js application. But this doesn't work the same way as it does on Vercel.

---

Expand All @@ -14,10 +14,10 @@ OpenNext is an initiative to bring all these efforts together.

---

OpenNext is currently backed by.
OpenNext is currently backed by:

1. [SST](https://sst.dev) community, maintains the [AWS](aws) adapter
2. [Cloudflare](https://www.cloudflare.com) team, maintains the [Cloudflare](cloudflare) adapter
2. [Cloudflare](https://developers.cloudflare.com/) team, maintains the [Cloudflare](cloudflare) adapter
3. [Netlify](http://netlify.com) team, maintains the [Netlify](netlify) adapter

If you'd like to join the effort, connect with us on [Discord](https://discord.gg/opennextjs).
Expand Down
Loading