| title | How to Type-Safe Environment Variables with React Router 7 (Framework) |
|---|---|
| description | Learn how to create type-safe environment variables in your React Router 7 application using the @t3-oss/env-core and zod libraries. |
| date | 2025-5-25 |
| category | Tutorial |
| writing | false |
| published | true |
@t3-oss/env-core is a library that provides a type-safe way to manage environment variables in your application. It uses zod for schema validation and can be used with any framework like Next.js, Nuxt or Agnostic Core (our case).
If you don't have a React Router, you can create one using the following command:
pnpm dlx create-react-router@latest my-react-router-appInstall the following dependencies:
pnpm i @t3-oss/env-core zod -E- Create a
.envfile in the root of your project:
# 馃搫 .env
VITE_HELLO="Hello from env variable"- Create a new file named
env.public.tsin theappdirectory. This file will contain the schema for your public environment variables:
// 馃搫 env.public.ts
import { z } from 'zod';
import { createEnv } from '@t3-oss/env-core';
export const envPublic = createEnv({
clientPrefix: 'VITE_',
client: {
VITE_HELLO: z.string()
//...
},
runtimeEnv: import.meta.env,
emptyStringAsUndefined: true
});- Usage:
// 馃搫 routes/_index.tsx
import { envPublic } from '@/env.public';
const Homepage = () => {
return <p>{envPublic.VITE_HELLO}</p>;
};
export default Homepage;- Create a
.envfile in the root of your project:
# 馃搫 .env
DATABASE_URL=""- Create a new file named
env.server.tsin theappdirectory. This file will contain the schema for your server environment variables:
// 馃搫 env.server.ts
import { z } from 'zod';
import { createEnv } from '@t3-oss/env-core';
export const envServer = createEnv({
server: {
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(['development', 'test', 'production']).default('development')
},
runtimeEnv: process.env,
emptyStringAsUndefined: true
});- Usage:
// 馃搫 routes/api.hello.ts
import { envServer } from '@/env.server';
export const loader = async () => {
return new Response(`Node Env: ${envServer.NODE_ENV}`);
};馃殌 Ready.