Skip to content

Commit

Permalink
feat: support cloudflare env in runtimeConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
Hebilicious committed Jun 18, 2023
1 parent 46f4ddf commit 7f840dc
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 4 deletions.
23 changes: 21 additions & 2 deletions src/runtime/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,46 @@ const ENV_PREFIX_ALT =
_inlineRuntimeConfig.nitro.envPrefix ?? process.env.NITRO_ENV_PREFIX ?? "_";

// Runtime config
let appliedRuntimeConfig = {};
const _sharedRuntimeConfig = _deepFreeze(
_applyEnv(klona(_inlineRuntimeConfig))
);
const getRuntimeConfig = () => ({
..._sharedRuntimeConfig,
...appliedRuntimeConfig,
});

export function useRuntimeConfig<
T extends NitroRuntimeConfig = NitroRuntimeConfig
>(event?: H3Event): T {
// Backwards compatibility with ambient context
if (!event) {
return _sharedRuntimeConfig as T;
return getRuntimeConfig() as T;
}
// Reuse cached runtime config from event context
if (event.context.nitro.runtimeConfig) {
return event.context.nitro.runtimeConfig;
}
// Prepare runtime config for event context
const runtimeConfig = klona(_inlineRuntimeConfig) as T;
const runtimeConfig = klona(getRuntimeConfig()) as T;
_applyEnv(runtimeConfig);
event.context.nitro.runtimeConfig = runtimeConfig;
return runtimeConfig;
}

export function applyEnvToRuntimeConfig(
env: Record<string, any>,
prefixes = ["NITRO", "NUXT"]
) {
const safeEnv = Object.fromEntries(
Object.entries(env).filter(([key]) =>
prefixes.some((prefix) => key.startsWith(`${prefix}_`))
)
);
appliedRuntimeConfig = safeEnv;
return useRuntimeConfig();
}

// App config
const _sharedAppConfig = _deepFreeze(klona(_inlineAppConfig));
export function useAppConfig(event?: H3Event) {
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/entries/cloudflare-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
// @ts-ignore Bundled by Wrangler
// See https://github.com/cloudflare/kv-asset-handler#asset_manifest-required-for-es-modules
import manifest from "__STATIC_CONTENT_MANIFEST";
import { applyEnvToRuntimeConfig } from "../config";
import { requestHasBody } from "../utils";
import { nitroApp } from "#internal/nitro/app";
import { useRuntimeConfig } from "#internal/nitro";
Expand Down Expand Up @@ -51,7 +52,7 @@ export default {

// Expose latest env to the global context
globalThis.__env__ = env;

applyEnvToRuntimeConfig(env);
return nitroApp.localFetch(url.pathname + url.search, {
context: {
cf: (request as any).cf,
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/entries/cloudflare-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
Request as CFRequest,
EventContext,
} from "@cloudflare/workers-types";
import { applyEnvToRuntimeConfig } from "../config";
import { requestHasBody } from "#internal/nitro/utils";
import { nitroApp } from "#internal/nitro/app";
import { isPublicAssetURL } from "#internal/nitro/virtual/public-assets";
Expand Down Expand Up @@ -38,7 +39,7 @@ export default {

// Expose latest env to the global context
globalThis.__env__ = env;

applyEnvToRuntimeConfig(env);
return nitroApp.localFetch(url.pathname + url.search, {
context: {
cf: request.cf,
Expand Down
3 changes: 3 additions & 0 deletions test/presets/cloudflare-module.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ describe("nitro:preset:cloudflare-module", async () => {
scriptPath: resolve(ctx.outDir, "server/index.mjs"),
sitePath: resolve(ctx.outDir, "public"),
bindings: {
NITRO_HELLO: "world",
NUXT_HELLO: "world",
SECRET: "secret",
ASSETS: {
fetch: async (request) => {
const contents = await fsp.readFile(
Expand Down
3 changes: 3 additions & 0 deletions test/presets/cloudflare-pages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ describe("nitro:preset:cloudflare-pages", async () => {
modules: true,
scriptPath: resolve(ctx.outDir, "_worker.js"),
bindings: {
NITRO_HELLO: "world",
NUXT_HELLO: "world",
SECRET: "secret",
ASSETS: {
fetch: async (request) => {
const contents = await fsp.readFile(
Expand Down
13 changes: 13 additions & 0 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,17 @@ export function testNitro(
expect(headers["server-timing"]).toMatch(/-;dur=\d+;desc="Generate"/);
});
}

if (
["cloudflare-module", "cloudflare-pages"].includes(ctx.nitro.options.preset)
) {
it("can load environment variables", async () => {
const { data } = await callHandler({
url: "/config",
});
expect(data.runtimeConfig.NITRO_HELLO).toBe("world");
expect(data.runtimeConfig.NUXT_HELLO).toBe("world");
expect(data.runtimeConfig.SECRET).toBeUndefined();
});
}
}

0 comments on commit 7f840dc

Please sign in to comment.