t3-oss / t3-env

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

Using shared variables with no clientPrefix #228

Open julius-retzer opened 2 months ago

julius-retzer commented 2 months ago

Hello, thank you for your effort on this nice library.

According to this issue https://github.com/t3-oss/t3-env/issues/192, when we don't want to use the client prefix, we should use the shared envs. However, even when I do that, I'm getting Attempted to access a server-side environment variable on the client when on client.

There seems to be this piece of code, which seems to completely prevent using the env variable on client:

   const isServerAccess = (prop)=>{
        if (!opts.clientPrefix)
            return true;
        return !prop.startsWith(opts.clientPrefix) && !(prop in shared.shape);
    }

Is this a bug or am I doing something wrong?

chungweileong94 commented 1 month ago

@julius-retzer If you are working in the server-only environment, the server option is all you need, and you can just ignore the clientPrefix & client options. However, one gotcha is that you shouldn't set clientPrefix: "", as it will treat all variables as client variables. If you intended to use t3-env in the client environment, you almost certainly have to use clientPrefix, as most of the frameworks do that, even create-react-app.

The share option is more for special cases like NODE_ENV [reference], where you can access the env from both server & client, without any client prefix.

There seems to be this piece of code, which seems to completely prevent using the env variable on client:

   const isServerAccess = (prop)=>{
        if (!opts.clientPrefix)
            return true;
        return !prop.startsWith(opts.clientPrefix) && !(prop in shared.shape);
    }

This code always assumes that you are in a server environment if the clientPrefix is not set. There might be chances where t3-env wasn't able to tell if you are in the server environment or not, if that's the case you can override the check via the isServer option.

Best if you could provide a repro, easy to check if it's a bug or some configuration mistake🙂