Skip to content

Commit 81113d6

Browse files
committed
perf: try eagerly initializing proxy
1 parent ad306e1 commit 81113d6

2 files changed

Lines changed: 15 additions & 18 deletions

File tree

.eslintrc

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
{
22
"extends": ["eslint-config-unjs"],
3-
"rules": {}
3+
"rules": {
4+
"unicorn/prefer-top-level-await": 0,
5+
},
46
}

src/runtime/plugin.dev.ts

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,20 @@ import type { PlatformProxy } from "wrangler";
33
// @ts-ignore
44
import { useRuntimeConfig, getRequestURL } from "#imports";
55

6-
export default <NitroAppPlugin>function (nitroApp) {
7-
let _proxy: Promise<PlatformProxy>;
6+
const _proxy = _getPlatformProxy()
7+
.catch((error) => {
8+
console.error("Failed to initialize wrangler bindings proxy", error);
9+
return _createStubProxy();
10+
})
11+
.then((proxy) => {
12+
(globalThis as any).__env__ = proxy.env;
13+
return proxy;
14+
});
815

9-
nitroApp.hooks.hook("request", async (event) => {
10-
// Lazy initialize proxy when first request comes in
11-
if (!_proxy) {
12-
const start = performance.now();
13-
_proxy = _getPlatformProxy()
14-
.catch((error) => {
15-
console.error("Failed to initialize wrangler bindings proxy", error);
16-
return _createStubProxy();
17-
})
18-
.finally(() => {
19-
const time = Math.round(performance.now() - start);
20-
console.info(`✔ Cloudflare dev proxy took ${time}ms to initialize.`);
21-
});
22-
}
16+
(globalThis as any).__env__ = _proxy.then((proxy) => proxy.env);
2317

18+
export default <NitroAppPlugin>function (nitroApp) {
19+
nitroApp.hooks.hook("request", async (event) => {
2420
const proxy = await _proxy;
2521

2622
// Inject the various cf values from the proxy in event and event.context
@@ -42,7 +38,6 @@ export default <NitroAppPlugin>function (nitroApp) {
4238
// Replicate Nitro production behavior
4339
// https://github.com/unjs/nitro/blob/main/src/runtime/entries/cloudflare-pages.ts#L55
4440
// https://github.com/unjs/nitro/blob/main/src/runtime/app.ts#L120
45-
(globalThis as any).__env__ = proxy.env;
4641
(event.node.req as any).__unenv__ = {
4742
...(event.node.req as any).__unenv__,
4843
waitUntil: event.context.waitUntil,

0 commit comments

Comments
 (0)