Skip to content

Commit 23a6c8f

Browse files
committed
fix(app): improve instance caching
1 parent 1b1bcec commit 23a6c8f

2 files changed

Lines changed: 24 additions & 19 deletions

File tree

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { definePlugin } from "nitro";
2+
import { useNitroHooks } from "nitro/app";
23

34
export default definePlugin((nitroApp) => {
4-
nitroApp.hooks.hook("response", (event) => {
5+
const hooks = useNitroHooks();
6+
hooks.hook("response", (event) => {
57
event.headers.set("content-type", "html; charset=utf-8");
68
});
79
});

src/runtime/internal/app.ts

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,16 @@ declare global {
4040
const APP_ID = import.meta.prerender ? "prerender" : "default";
4141

4242
export function useNitroApp(_id = APP_ID): NitroApp {
43+
let instance = globalThis.__nitro__?.[_id];
44+
if (instance) {
45+
return instance;
46+
}
4347
globalThis.__nitro__ ??= {};
44-
return (globalThis.__nitro__[_id] ??= initNitroApp());
48+
instance = globalThis.__nitro__[_id] = createNitroApp();
49+
if (hasPlugins) {
50+
initNitroPlugins(instance);
51+
}
52+
return instance;
4553
}
4654

4755
export function useNitroHooks(_id = APP_ID): HookableCore<NitroRuntimeHooks> {
@@ -89,23 +97,6 @@ export function fetch(
8997
return fetch(resource, init);
9098
}
9199

92-
function initNitroApp(): NitroApp {
93-
const nitroApp = (globalThis.__nitro__ = createNitroApp());
94-
if (hasPlugins) {
95-
for (const plugin of plugins) {
96-
try {
97-
plugin(
98-
nitroApp as NitroApp & { hooks: NonNullable<NitroApp["hooks"]> }
99-
);
100-
} catch (error: any) {
101-
nitroApp.captureError?.(error, { tags: ["plugin"] });
102-
throw error;
103-
}
104-
}
105-
}
106-
return nitroApp;
107-
}
108-
109100
function createNitroApp(): NitroApp {
110101
const hooks = hasHooks ? new HookableCore<NitroRuntimeHooks>() : undefined;
111102

@@ -171,6 +162,18 @@ function createNitroApp(): NitroApp {
171162
return app;
172163
}
173164

165+
function initNitroPlugins(app: NitroApp) {
166+
for (const plugin of plugins) {
167+
try {
168+
plugin(app as NitroApp & { hooks: NonNullable<NitroApp["hooks"]> });
169+
} catch (error: any) {
170+
app.captureError?.(error, { tags: ["plugin"] });
171+
throw error;
172+
}
173+
}
174+
return app;
175+
}
176+
174177
function createH3App(config: H3Config) {
175178
// Create H3 app
176179
const h3App = new H3Core(config);

0 commit comments

Comments
 (0)