Don’t hardcode URLs
In the previous lesson, the frontend hadhttp://localhost:8000 hardcoded. This breaks the moment you deploy — your production API isn’t at localhost. Environment variables let you configure these values per environment.
.env files
An.env file stores key-value pairs that your application reads at startup:
KEY=VALUE. No spaces around the =. No quotes needed (unless the value contains spaces).
Vite environment variables (frontend)
Vite has one important rule: frontend environment variables must start withVITE_.
import.meta.env:
The
VITE_ prefix is a security feature. Your React code gets bundled and sent to the user’s browser — anyone can read it. The prefix prevents you from accidentally exposing secrets like DATABASE_URL or SECRET_KEY in your frontend bundle. Only variables you explicitly mark with VITE_ are included.Using environment variables in React
Python environment variables (backend)
In Python, you already know this pattern. Usepython-dotenv or Pydantic’s BaseSettings:
.env.example — document what’s needed
Create a.env.example file that shows what variables are required, without the actual values:
.env.example to Git. When a new developer clones the project, they copy it to .env and fill in their values:
Multiple environments
You can have different.env files for different situations:
npm run dev→ reads.envnpm run build→ reads.env.production(if it exists)
The companion repo uses
VITE_API_BASE_URL (same concept, more explicit name). Its mobile app uses Expo’s equivalent prefix: EXPO_PUBLIC_API_BASE_URL.What’s next?
Your URLs are configurable. But when your React frontend atlocalhost:5173 tries to call your FastAPI backend at localhost:8000, the browser blocks the request. This is CORS — and it’s the most common error when connecting frontend to backend.
Understanding CORS
Fix cross-origin errors when your React frontend talks to your FastAPI backend