loading...

Byte-Sized: .env Keeping things Secure

jaybeekeeper profile image Jarret Bryan ・2 min read

I spent a little time recently looking into how to build a twitter bot with JavaScript; it's actually not super difficult - but it's definitely worth exploring the ethics, intent, potential and ramifications around - but I came across something that I hadn't been familiar with - .env files.

I have my bot projected situated on glitch.me - and the project I remixed already had a .env file included. But I wasn't entirely familiar with the idea.

My Glitch Directory

Glitch is fantastic as a community and a project that I could fork a repository and receive a blank .env file - providing me with the template without betraying the previous repository owner's content and secrets.

But... what is a .env file? And why do I have on Glitch for a twitter bot?

So .env files are the solution to the problem of - how do I keep my APIkeys secure.
I need to talk to the TwitterAPI to make my Twitter bot. But the case for many APIs is just that I would need a secure key to talk to the API. And that key needs to stay secure - I can't just post that to a public repository on Github for the world to see. Anyone could grab it and use it.

Quick solution is the dotenv npm package - Glitch allows me to have the package on their site, but let's say I'm working locally in JS. Quick install:

npm install dotenv --save

Now that I have the package, I require it as early as possible in my program:

require('dotenv').config()

And now I can have my APIKey, set in an .env file -

echo "API_KEY=secure_API-key_here" >> .env

And if open up that file, I can see my secure API key, and it doesn't have to be situated in the other files in my repository. I'm in business! dotenv is going to look for a .env file, and when I run my the required .js file for my application, dotenv will read the .env file and make its contents available to my process as an environment variable. I can access that variable with

process.env.API_KEY

And if I add my .env file to my .gitignore file, I don't have to commit my secrets for the world to see. Keeping my keys secure, and allowing my code to function.

Again, I first game across this in the context of Glitch.me. Glitch.me by default keeps the .env file secure - so even if other users view your code, they don't have access to your secure keys. But your program still does!

Posted on by:

jaybeekeeper profile

Jarret Bryan

@jaybeekeeper

web developer | technologist | #codenewbie | alum of @flatironschool

Discussion

markdown guide