digitros/nextjs-fastapi

Reading Vercel Environment Variables in Python

knnhcn opened this issue · 3 comments

How can I read Environment Variables defined in Vercel e.g. when running in production?

Also in development?

After some research and trials I found a way to use .env variables in Python code. However, there are some additional steps required to do so:

First, add python-dotenv to your requirements.txt:

fastapi==0.95.2
uvicorn[standard]
python-dotenv

Then, in your index.py, load the .env file:

from dotenv import load_dotenv
load_dotenv()

Finally, you can use your keys defined in .env like below:

os.getenv("MY_KEY")

This also worked in production when deployed to Vercel and variables defined in Vercel Environment Variables.

You can also install python-decouple for that.

fastapi
uvicorn[standard]
python-decouple

Then, when you want to use an environment variable, you can use:

from decouple import config
ENVIRONMENT_VARIABLE = config("YOUR_ENVIRONMENT_VARIABLE")