Skip to content

Instantly share code, notes, and snippets.

@JLarky
Last active May 3, 2023 03:41
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
This is @t3-oss/env-core but if you don't want to send zod to client bundle (be careful, it's for Astro, not Next.js) https://twitter.com/JLarky/status/1653595995744395264
// src/t3Env.ts
import { createEnv, LooseOptions, StrictOptions } from '@t3-oss/env-core';
import { z, ZodType, ZodString } from 'zod';
function validateEnv<
TPrefix extends string,
TServer extends Record<string, ZodType> = NonNullable<unknown>,
TClient extends Record<string, ZodType> = NonNullable<unknown>
>(opts: LooseOptions<TPrefix, TServer, TClient> | StrictOptions<TPrefix, TServer, TClient>) {
return opts;
}
const x = validateEnv({
clientPrefix: 'PUBLIC_',
server: {
DATABASE_URL: z.string().url(),
OPEN_AI_API_KEY: z.string().min(1),
},
client: {
// PUBLIC_AUTH_URL_WRONG: z.number().min(1),
PUBLIC_AUTH_URL: z.string().min(1),
},
runtimeEnv: import.meta.env,
skipValidation:
!!import.meta.env.SKIP_ENV_VALIDATION &&
import.meta.env.SKIP_ENV_VALIDATION !== 'false' &&
import.meta.env.SKIP_ENV_VALIDATION !== '0',
});
// this function would be dead code eliminated
const client = () => {
// add check that values are strings
const v = (_: ZodString[]) => {};
// this line will error if the client env is not a string
v(Object.values(x.client));
// generate type just for the client
return z.object(x.client);
};
export type ClientEnv = z.infer<ReturnType<typeof client>>;
// export env for server code
export const serverEnv = createEnv(x);
// src/config.ts
import type { ClientEnv } from './t3Env';
// use clientEnv for client-only code so that you don't ship zod dependency to the client
export const env = import.meta.env as unknown as ClientEnv;
// src/components/example.tsx
import { env } from '../config';
console.log(env.PUBLIC_AUTH_URL);
// src/pages/example.ts
import { serverEnv } from '../t3Env';
console.log(serverEnv.OPEN_AI_API_KEY);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment