Last active
July 20, 2024 16:36
-
-
Save rmarscher/9bb6ed54dc9535f4b81bed147204c7e9 to your computer and use it in GitHub Desktop.
Waku Cloudflare Pages Dev Server Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { GetPlatformProxyOptions } from "wrangler" | |
import type { Middleware } from "waku/config" | |
type Handler = ReturnType<Middleware> | |
export const cloudflareDevServer = (cfOptions: GetPlatformProxyOptions) => { | |
const middleware: Middleware = (options) => { | |
if (import.meta.env && import.meta.env.MODE === "production") { | |
// pass through | |
return (_ctx, next) => next() | |
} | |
const wsAssign = import("miniflare").then(({ WebSocketPair }) => { | |
Object.assign(globalThis, { WebSocketPair }) | |
}) | |
let env: Record<string, unknown> = options.env || {} | |
const proxy = import("wrangler").then(({ getPlatformProxy }) => | |
getPlatformProxy({ | |
...cfOptions, | |
}).then((proxy) => { | |
env = { ...env, ...proxy.env } | |
return proxy | |
}), | |
) | |
return async (ctx, next) => { | |
await wsAssign | |
const awaitedProxy = await proxy | |
Object.assign(ctx.req, { cf: awaitedProxy.cf }) | |
Object.assign(globalThis, { | |
caches: awaitedProxy.caches, | |
__WAKU_PRIVATE_ENV__: { ...env, executionContext: awaitedProxy.ctx }, | |
}) | |
await next() | |
} | |
} | |
return { default: middleware } | |
} | |
export default cloudflareDevServer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @type {import('waku/config').Config} */ | |
export default { | |
middleware: () => { | |
return [ | |
...(import.meta.env && import.meta.env.MODE !== "production" | |
? [ | |
import("./waku.cloudflare-dev-server").then(({ cloudflareDevServer }) => { | |
return cloudflareDevServer({ | |
// Optional config settings for the Cloudflare dev server (wrangler proxy) | |
// https://developers.cloudflare.com/workers/wrangler/api/#parameters-1 | |
persist: { | |
path: ".wrangler/state/v3", | |
}, | |
}) | |
}), | |
] | |
: []), | |
import("waku/middleware/dev-server"), | |
import("waku/middleware/headers"), | |
import("waku/middleware/ssr"), | |
import("waku/middleware/rsc"), | |
] | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment