t3-oss / t3-env

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

Support Custom Prefixes for Client Environment Variables in `@t3-oss/env-nextjs` #232

Closed derodero24 closed 1 month ago

derodero24 commented 1 month ago

Currently, when using the @t3-oss/env-nextjs package for environment variable validation and extraction, we are required to use lengthy environment variable names prefixed with NEXT_PUBLIC_ for client-side accessible variables. This often leads to overly verbose code, especially when accessing multiple environment variables.

I propose adding an option to customize the prefix for client-side environment variables within the createEnv function. This enhancement would allow developers to define shorter or different prefixes as per their project's conventions, improving code readability and flexibility.

Example

import { createEnv } from '@t3-oss/env-nextjs';
import { z } from 'zod';

export const env = createEnv({
  client: {
    NP_ENV: z.enum(['prod', 'sandbox', 'demo', 'staging', 'local']),
  },
  runtimeEnv: {
    NP_ENV: process.env.NEXT_PUBLIC_ENV,
  },
  clientPrefix: 'NP_',
});

console.log(env.NP_ENV);

Introducing a customizable prefix option would not affect the existing functionality for those who prefer to use the default setting. It simply provides an additional configuration option for those looking to tailor their environment variable setup more closely to their project's needs.

juliusmarminge commented 1 month ago

the prefix isn't something you control though - it's implemented in the framework to handle this.

if we were to support this it would

a) we'd have to remap NEXT_PUBLIC_FOO to NP_FOO in the lib - you'd still need to have NEXT_PUBLIC_FOO= in your .env. a) be confusing to new devs who knows about nextjs that a variable not named NEXT_PUBLIC_X is shipped to the client

Overall I think it would be a bad call going away from the standard here