From 70995c1098b641bb1aa510f291e193e4724f27d4 Mon Sep 17 00:00:00 2001 From: Aleksei Gurianov Date: Tue, 13 Aug 2024 20:44:56 +0000 Subject: [PATCH] feat(core): expose isServer value to reuse across app (#258) --- .changeset/great-eyes-divide.md | 5 +++++ examples/astro/src/t3-env.ts | 2 ++ examples/nextjs/app/env.ts | 2 ++ examples/nuxt/env.ts | 2 ++ packages/core/src/index.ts | 3 ++- packages/core/test/smoke.test.ts | 22 ++++++++++++++++++++++ 6 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 .changeset/great-eyes-divide.md diff --git a/.changeset/great-eyes-divide.md b/.changeset/great-eyes-divide.md new file mode 100644 index 00000000..0e8e8368 --- /dev/null +++ b/.changeset/great-eyes-divide.md @@ -0,0 +1,5 @@ +--- +"@t3-oss/env-core": minor +--- + +expose isServer value to reuse across app diff --git a/examples/astro/src/t3-env.ts b/examples/astro/src/t3-env.ts index 868e3eee..a6f0164b 100644 --- a/examples/astro/src/t3-env.ts +++ b/examples/astro/src/t3-env.ts @@ -15,3 +15,5 @@ export const env = createEnv({ skipValidation: import.meta.env.SKIP_ENV_VALIDATION === "development", clientPrefix: "PUBLIC_", }); + +const isServer = env.isServer; diff --git a/examples/nextjs/app/env.ts b/examples/nextjs/app/env.ts index ec089fe9..c2106415 100644 --- a/examples/nextjs/app/env.ts +++ b/examples/nextjs/app/env.ts @@ -18,3 +18,5 @@ export const env = createEnv({ }, extends: [vercel()], }); + +const isServer = env.isServer; diff --git a/examples/nuxt/env.ts b/examples/nuxt/env.ts index ce3023f6..d91e381b 100644 --- a/examples/nuxt/env.ts +++ b/examples/nuxt/env.ts @@ -9,3 +9,5 @@ export const env = createEnv({ NUXT_PUBLIC_GREETING: z.string(), }, }); + +const isServer = env.isServer; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 72770be2..8eacbbd9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -209,7 +209,7 @@ export type CreateEnv< TypeOf> & TypeOf> & UnReadonlyObject> - > + > & { isServer: boolean } >; export function createEnv< @@ -294,6 +294,7 @@ export function createEnv< if (typeof prop !== "string") return undefined; if (ignoreProp(prop)) return undefined; if (!isValidServerAccess(prop)) return onInvalidAccess(prop); + if (prop === "isServer") return isServer; return Reflect.get(target, prop); }, // Maybe reconsider this in the future: diff --git a/packages/core/test/smoke.test.ts b/packages/core/test/smoke.test.ts index 64324498..9796a17f 100644 --- a/packages/core/test/smoke.test.ts +++ b/packages/core/test/smoke.test.ts @@ -620,3 +620,25 @@ describe("extending presets", () => { }); }); }); + +describe("isServer is correctly exposed", () => { + test("for server", () => { + const env = createEnv({ + server: {}, + runtimeEnv: {}, + isServer: true, + }); + + expect(env.isServer).toBe(true); + }); + + test("for client", () => { + const env = createEnv({ + server: {}, + runtimeEnv: {}, + isServer: false, + }); + + expect(env.isServer).toBe(false); + }); +});