t3-env icon indicating copy to clipboard operation
t3-env copied to clipboard

Feature request - add support for virtual envs

Open ARiyou2000 opened this issue 1 year ago • 1 comments

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

ARiyou2000 avatar May 08 '24 08:05 ARiyou2000

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}`
})

juliusmarminge avatar May 13 '24 16:05 juliusmarminge