Environment variables allow you to keep sensitive or machine-specific values out of your R scripts and out of version control.
Examples of information you might store in environment variables:
Instead of hardcoding sensitive information into your scripts, you store it separately in a .Renviron file and retrieve it when needed.
To work with environment variables in R, create a file named .Renviron in the root of your project. This file is automatically read when an R session starts.
In this file, each line defines one environment variable using the format:
VARIABLE_NAME=value
In the video example, I define two environment variables:
OSF_TOKEN — a personal access token for communicating with the OSF API.DEBUG — a flag that allows me to toggle debug output on or offOSF_TOKEN=MZTr1kK6hVaUH0urNfe72hVNwybiqfk56UfK2vORK1vYWYYJ8uxNQh6otyLnSiZe6D3bZq
DEBUG=true
⚠️ Tokens function like passwords and should always be kept private. The token shown in my demo has been destroyed.
Each line must follow this pattern:
NAME=value
Rules:
It’s not required for the name to be capitalized, but it’s a common convention.
Here’s a valid example:
OPENAI_API_KEY=sk-abc123
DB_HOST=localhost
DB_USER=susan
DB_PASSWORD=supersecret
If you need spaces in a value, use underscores instead:
PROJECT_NAME=My_Project_Name
Do not write:
PROJECT_NAME = My Project
That format will not work correctly.
After editing .Renviron, you must restart your R session for changes to take effect.
Once defined, environment variables can be accessed in R using:
Sys.getenv("VARIABLE_NAME")
For example:
OSF_TOKEN <- Sys.getenv("OSF_TOKEN")
Below is a simple example using the OSF_TOKEN and DEBUG variables.
require("httr")
# Get values from environment
OSF_TOKEN <- Sys.getenv("OSF_TOKEN")
# Since environment variables are stored as strings, we explicitly convert DEBUG to a logical value:
DEBUG <- Sys.getenv("DEBUG") == "TRUE"
# Demo request to OSF servers to check authentication
# ⭐ Note use of OSF_TOKEN ⭐
request <- GET(
"https://api.osf.io/v2/users/me/",
add_headers(Authorization = paste("Bearer", OSF_TOKEN))
)
response_text <- content(request, as = "text", encoding = "UTF-8")
if (
grepl(
"User provided an invalid OAuth2 access token",
response_text
)
) {
# ⭐ Note use of DEBUG ⭐
if (DEBUG) {
print("❌ Invalid access token; failed to auth with OSF servers")
}
}
# ⭐ Note use of DEBUG ⭐
if (DEBUG) {
print("✅ Auth test with OSF servers successful")
}
If your project uses Git, you should never commit your .Renviron file. It often contains API keys, tokens, and other sensitive information.
To prevent it from being tracked, add this line to your .gitignore file:
.Renviron
Each collaborator must create their own .Renviron file locally with their own credentials.
To make onboarding easier, create a .Renviron.example file and commit it to your repository. This file documents which environment variables are required without including any real secrets.
Example:
# Copy this file to .Renviron and fill in real values.
# Do NOT commit your .Renviron file.
# ===== API KEYS =====
OPENAI_API_KEY=your_openai_api_key_here
OSF_TOKEN=your_osf_token_here
# ===== DATABASE =====
DB_HOST=localhost
DB_USER=your_db_username
DB_PASSWORD=your_db_password
# ===== APP SETTINGS =====
DEBUG=true
ENVIRONMENT=development
New collaborators can simply:
This keeps secrets secure while making setup straightforward and consistent across environments.
You can list all environment variables via:
Sys.getenv()
If a variable is missing:
No subscriptions, no auto-renewals.
Just a simple one-time payment that helps support my free, to-the-point videos without sponsered ads.
Unlocking gets you access to the notes for this video plus all 200+ guides on this site.
Your support is appreciated. Thank you!