Adapters

Cloudflare

Run your h3 apps in Cloudflare Workers

You can directly host your h3 applications to Cloudflare Workers using Web Adapter.

Usage

Create app entry:

app.mjs
import { createApp, defineEventHandler } from "h3";

export const app = createApp();

app.use(defineEventHandler(() => "Hello world!"));

Create entry for a Cloudflare Worker:

cloudflare.mjs
import { toWebHandler } from "h3";
import { app } from "./app.mjs";

const handler = toWebHandler(app);

export default {
  async fetch(request, env, ctx) {
    return handler(request, {
      cloudflare: { env, ctx },
    });
  },
};

Then, create a simple wrangler.toml:

wrangler.toml
name = "h3-app"
main = "cloudflare.mjs"
compatibility_date = "2023-08-01"

Finally, use wrangler dev to locally preview:

npx wrangler dev

To deploy, use wrangler deploy:

npx wrangler deploy

WebSocket support

Read more in crossws.unjs.io/adapters/cloudflare.
import wsAdapter from "crossws/adapters/cloudflare";

const { handleUpgrade } = wsAdapter(app.websocket);

export default {
  async fetch(request, env, ctx) {
    if (request.headers.get("upgrade") === "websocket") {
      return handleUpgrade(request, env, context);
    }
    return handler(request, {
      cloudflare: { env, ctx },
    });
  },
};

👉 See pi0/h3-on-edge demo for a fully working example (deployment).