T
TanStack5mo ago
rising-crimson

Secure env variables from get on browser

I have database and env variables, and want make sure that this not accessed by client in any way, is there a way to make sure that this happens, and get error or something if called from client?
11 Replies
foreign-sapphire
foreign-sapphire5mo ago
you could wrap it into a getter function and wrap that again with serverOnly this will throw on the client then but work as expected on the server
rising-crimson
rising-crimsonOP5mo ago
What part of docs describe this to use it ?
hollow-tomato
hollow-tomato5mo ago
hollow-tomato
hollow-tomato5mo ago
I have something like this, but I cannot get it to work:
import dotenv from "dotenv";

if (import.meta.env.SSR) {
dotenv.config({ path: ".env.local" });

const INSTANT_API_KEY = process.env.INSTANT_API_KEY;

console.log({ INSTANT_API_KEY });
}

type EnvVariables = {
INSTANT_API_KEY: string;
};

// On the server side, access environment variables
export const envVariables: EnvVariables = {
INSTANT_API_KEY: process.env.INSTANT_API_KEY as string,
};
import dotenv from "dotenv";

if (import.meta.env.SSR) {
dotenv.config({ path: ".env.local" });

const INSTANT_API_KEY = process.env.INSTANT_API_KEY;

console.log({ INSTANT_API_KEY });
}

type EnvVariables = {
INSTANT_API_KEY: string;
};

// On the server side, access environment variables
export const envVariables: EnvVariables = {
INSTANT_API_KEY: process.env.INSTANT_API_KEY as string,
};
is it me or it is weird there's not documentation on loading environment variables on the server-side with Tanstack Start or Vite directly? @Mohammed Elsayed how did you get it to work?
rising-crimson
rising-crimsonOP5mo ago
I just use process.env.{var name that not startingwith vite as this will be accessed on client only} and this working
hollow-tomato
hollow-tomato5mo ago
are you using tanstack start?
rising-crimson
rising-crimsonOP5mo ago
Yes
harsh-harlequin
harsh-harlequin5mo ago
I've been using t3-env and seems to work pretty well so far. the full env is accessible from the server, loaded at runtime client prefixed variables are also available on the frontend, but those are set at build time it seems, so not very useful
robust-apricot
robust-apricot4mo ago
This was working for me up until the alpha update dropping Vinxi Now process.env doesnt have any of my variables. import.meta works but only for variables prefixed with VITE_
sensitive-blue
sensitive-blue4mo ago
You’ll probably need to create two files in the env folder, sever and client https://env.t3.gg/docs/core
Env
Never build your apps with invalid environment variables again. Validate and transform your environment with the full power of Zod.
harsh-harlequin
harsh-harlequin4mo ago
check out this thread for some approaches for this on alpha https://discord.com/channels/719702312431386674/1238170697650405547/1371507529980444884

Did you find this page helpful?