t3-oss / t3-env

https://env.t3.gg
MIT License
2.45k stars 79 forks source link

Feature request - add support for virtual envs #233

Open ARiyou2000 opened 1 month ago

ARiyou2000 commented 1 month ago

there can be env variables that are not explicitly defined in the env file but are a combination of those variables and can be accessed like follow:

Env file:

BACKEND_CONNECTION_PROTOCOL=http
BACKEND_ADDRESS=192.168.1.100
BACKEND_PORT=8088
BACKEND_API_PREFIX=/mlcore/v4

T3 ENV config:

export const env = createEnv({
  isServer: typeof window === "undefined",
  emptyStringAsUndefined: true,
  /*
   * Serverside Environment variables, not available on the client.
   * Will throw if you access these variables on the client.
   */
  server: {
    BACKEND_CONNECTION_PROTOCOL: z.enum(["http", "https"]).default("http"),
    BACKEND_ADDRESS: z.string().url().min(1).or(z.string().ip()),
    BACKEND_PORT: z.coerce.number().optional(),
    BACKEND_API_PREFIX: z.string().min(1).optional(),
    NEXT_BACKEND_ABSOLUTE_URL: z.string().url().min(1)
  },
  runtimeEnv: {
    BACKEND_CONNECTION_PROTOCOL: process.env.BACKEND_CONNECTION_PROTOCOL,
    BACKEND_ADDRESS: process.env.BACKEND_ADDRESS,
    BACKEND_PORT: process.env.BACKEND_PORT,
    BACKEND_API_PREFIX: process.env.BACKEND_API_PREFIX,
    NEXT_BACKEND_ABSOLUTE_URL: 
      `${process.env.BACKEND_CONNECTION_PROTOCOL}://${process.env.BACKEND_ADDRESS}:${process.env.BACKEND_PORT}${process.env.BACKEND_API_PREFIX}`,
  },
});

and then we can access env.NEXT_BACKEND_ABSOLUTE_URL without process.env.NEXT_BACKEND_ABSOLUTE_URL in env file

juliusmarminge commented 1 month ago

Could you solve this with some plain old javascript or will the proxy break if you do something like:

const $env = createEnv({
  isServer: typeof window === "undefined",
  emptyStringAsUndefined: true,
  /*
   * Serverside Environment variables, not available on the client.
   * Will throw if you access these variables on the client.
   */
  server: {
    BACKEND_CONNECTION_PROTOCOL: z.enum(["http", "https"]).default("http"),
    BACKEND_ADDRESS: z.string().url().min(1).or(z.string().ip()),
    BACKEND_PORT: z.coerce.number().optional(),
    BACKEND_API_PREFIX: z.string().min(1).optional(),
  },
  runtimeEnv: {
    BACKEND_CONNECTION_PROTOCOL: process.env.BACKEND_CONNECTION_PROTOCOL,
    BACKEND_ADDRESS: process.env.BACKEND_ADDRESS,
    BACKEND_PORT: process.env.BACKEND_PORT,
    BACKEND_API_PREFIX: process.env.BACKEND_API_PREFIX,
  },
});

export const env = Object.assign($env, {
  NEXT_BACKEND_ABSOLUTE_URL: `${$env.BACKEND_CONNECTION_PROTOCOL}://${$env.BACKEND_ADDRESS}:${$env.BACKEND_PORT}${$env.BACKEND_API_PREFIX}`
})