T
TanStack7mo ago
complex-teal

how to pass a process.env value from SSR context to client?

I have a .env variable for my API (let's say process.env.SERVER_API) and I want to make it available in my client. one way I thought to do this was context so my file route components could access it as:
const {apiBase} = Route.useRouteContext();
const {apiBase} = Route.useRouteContext();
my implementation was:
declare global {
interface Window {
SERVER_API: string;
}
}

export function createRouter() {
const queryClient = getQueryClient();
const SERVER_API = process.env[API_BASE_URL_ENV_VAR];
window.SERVER_API = process.env[API_BASE_URL_ENV_VAR];

if (SERVER_API === undefined) {
throw new Error(`Missing environment variable: ${API_BASE_URL_ENV_VAR}`);
}

console.log({env: import.meta.env});

return routerWithQueryClient(
createTanStackRouter({
routeTree,
context: {queryClient, SERVER_API},
defaultPreload: 'intent',
defaultErrorComponent: DefaultCatchBoundary,
defaultNotFoundComponent: () => <NotFound />,
}),
queryClient,
);
}
declare global {
interface Window {
SERVER_API: string;
}
}

export function createRouter() {
const queryClient = getQueryClient();
const SERVER_API = process.env[API_BASE_URL_ENV_VAR];
window.SERVER_API = process.env[API_BASE_URL_ENV_VAR];

if (SERVER_API === undefined) {
throw new Error(`Missing environment variable: ${API_BASE_URL_ENV_VAR}`);
}

console.log({env: import.meta.env});

return routerWithQueryClient(
createTanStackRouter({
routeTree,
context: {queryClient, SERVER_API},
defaultPreload: 'intent',
defaultErrorComponent: DefaultCatchBoundary,
defaultNotFoundComponent: () => <NotFound />,
}),
queryClient,
);
}
the problem is, in ssr.rsx process.env.SERVER_API resolves to a value but in the client process.env.SERVER_API is undefined. is there a way to accomplish what I'm trying to do here without adding the VITE_ prefix? I would prefer to use one env variable and not duplicate it for the client
1 Reply
correct-apricot
correct-apricot7mo ago
unless you do some substitution of process.env on the client it won't be set you could add the value to the router context by returning it from the root's beforeLoad

Did you find this page helpful?