Tutorial | R | dotenv

Often when learning a new package or testing out some code, I find myself writing my credentials and API tokens in plain text in my code. This is not the ideal way to code, especially if I don’t want to regenerate my tokens and change my passwords every time I share my code. Using credentials and API tokens in your Data Science and programming projects is inevitable, but leaving them exposed is avoidable. Using the dotenv
package in R is one way to keep these sensitive bits of information safe from prying eyes.
The Problem
In a previous project, I used the [mapsapi](https://cran.rstudio.com/web/packages/mapsapi/vignettes/intro.html)
package to access the Google Maps API. I had a data frame of points of interest, cities, states, and countries that I wanted to geocode, or get the longitude and latitude for. To get this information from the Google Maps API, I needed an API token. This API token is specific to me, and for a higher number of calls to the API, you need to pay.
So imagine you created a similar project and uploaded it to GitHub. You soon see a very large charge on your credit card. Why? You left your API token in the code and someone abused your access to the API and ran up serious charges on your account.
You left your API token in your code and someone ran up serious charges on your account
API tokens give enormous amounts of power to control applications. With certain API’s, usage is monitored and you will be billed for your usage! With this in mind, it is important to keep your credentials safe when using them in your coding projects.
A Solution
Enter environment variables. Jim Medlock has a great explanation of what they are in his An Introduction to Environment Variables and How to Use Them. In that post he says:
_An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time._
Here I will use them to keep my Google Maps API token safely out of my GitHub commits. This same process can be used for any other sensitive information you add to your code. For example, if you need to use your username or password for accessing a database, you will want to use something like the dotenv
package to keep it safe.
Note: I say a solution because there are multiple ways to do everything. This is the one I find simple and useful for my projects
Before We Begin
Before we begin, here is a quick look at the snippet of code that we will be improving with environment variables. It loads the required package, defines the API key in plain text, and sends a request to the API for each location in the places
character vector.
library(mapsapi)
G_API_KEY <- "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
geo_obs <- mp_geocode(places, key=G_API_KEY)
Our goal is to remove the need to keep the token in this script, but still be able to use it in our code.
Installation
Let’s start with installing the package. We can do this using the install.packages()
function.
> install.packages("dotenv")
.env Setup
Now let’s setup our .env
file. This file should always live in the project’s top level folder, or root directory. Create a new text file in that location, renaming it to .env
. Windows will ask you to confirm that you want to change the file type. Click yes.

Next, open the .env
file with a text editor. I prefer Atom or [Notepad](https://www.microsoft.com/en-us/p/windows-notepad/9msmlrh6lzf3?activetab=pivot:overviewtab)++, but Notepad will work just fine. By convention, environment variables are all uppercase with words separated by underscores. We can name ours GOOGLE_MAPS_API and paste our token in. Save and close the file.
GOOGLE_MAPS_API=XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Note: Make sure you create a blank line at the end of this file otherwise R will have an issue processing the file
Add to .gitignore
Now the assumption here is that you are using GitHub for version control in your data science projects. If you aren’t, you should be! It is a great way to roll back changes to your code if something goes wrong. GitHub also enables collaboration with others. You wouldn’t want them to also have your token, so we have some work to do. If you don’t have a repository setup for the project or don’t know how to, don’t sweat it, I’ll cover this in another post. You can safely move on to the next section.
GitHub will save all of the changes to the code, but we need to exclude the .env
file as that is what contains our token. To make sure that the .env
file is not committed to the repository, open up the .gitignore
file in your project folder and add the following line.
*.env
Adding this line will ignore the .env
file that we created earlier. By using the asterisk (*), we are excluding all files in the top level folder or root directory that have the .env
extension from being committed to the repository.
Loading Environment Variables
Now that we have the .env
file with our sensitive information and it won’t get committed to our repository, we need to actually use it in our R script.
First we need to load the dotenv
package. Add this to the example script.
library(dotenv)
The load_dot_env()
function will be used to load the .env
file to the environment variables. This function will look for the .env
file in the current working directory.
load_dot_env()
If you had to name your file something other than .env
, the function call should look like below, with cred.env
replaced with your filename.
load_dot_env("cred.env")
To use the environment variable in our script, we can use the Sys.getenv()
function in our mp_geocode()
function (or wherever else you are using your environment variables).
geo_obs <- mp_geocode(places, key=Sys.getenv("GOOGLE_MAPS_API"))
The last thing to do is delete the line that has the API key in plain text. After that the final script will look like this:
library(mapsapi)
library(dotenv)
load_dot_env()
geo_obs <- mp_geocode(places, key=Sys.getenv("GOOGLE_MAPS_API"))
Closing Remarks
The dotenv
package is a great way to obscure sensitive information. It doesn’t have to be limited to use with the Google Maps API. Anywhere code is using login credentials, database connection information, API tokens, or anything else you don’t want to share with the world, put it in your .env
file.
For more on the dotenv
R package, check out the GitHub Repository for the package. It includes more documentation for the package.