← More Guides

R Environment Variables (.Renviron) - Keep API Keys and Secrets Safe

Video Notes

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.

Creating Environment Variables

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:

  1. OSF_TOKEN — a personal access token for communicating with the OSF API.
  2. DEBUG — a flag that allows me to toggle debug output on or off
OSF_TOKEN=MZTr1kK6hVaUH0urNfe72hVNwybiqfk56UfK2vORK1vYWYYJ8uxNQh6otyLnSiZe6D3bZq
DEBUG=true

⚠️ Tokens function like passwords and should always be kept private. The token shown in my demo has been destroyed.

Rules for .Renviron

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.

Restart Your R Session

After editing .Renviron, you must restart your R session for changes to take effect.

Accessing Environment Variables

Once defined, environment variables can be accessed in R using:

Sys.getenv("VARIABLE_NAME")

For example:

OSF_TOKEN <- Sys.getenv("OSF_TOKEN")

Demo Script

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")
}

Add .Renviron to .gitignore

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.

.Renviron.example

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:

  1. Copy .Renviron.example to .Renviron
  2. Fill in their credentials or the ones you provide them
  3. Restart their R session

This keeps secrets secure while making setup straightforward and consistent across environments.

Debugging Tips

You can list all environment variables via:

Sys.getenv()

If a variable is missing:

Unlock all the notes for $4

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!

Payment Info

/
$4 6 months
$25 forever
Please check the form for errors
Questions? help@codewithsusan.com
← More Guides