Programming

JavaScript: keep the API key in a .env file

Do not write the key in the code. .env, .gitignore and a Vercel variable.

All lessons · JavaScript lessons: learn from scratch

The key does not belong in the code

Writing the key inside JavaScript is only for practice on your own computer. Once it reaches GitHub, bots find it in seconds. Someone else sends requests with your key, and your limit and balance run out. If it is in the visible part of the site, anyone can see it with F12. The request must go in the background, on the server.

The .env file

The file is named .env, not ad.env. It sits in the project's main folder. The name is in capital letters, words are separated by _. No quotes, no semicolon and no const. The code reads it with process.env.GEMINI_API_KEY. In plain Node.js, first npm install dotenv, then import "dotenv/config".

GEMINI_API_KEY=acar

const apiKey = process.env.GEMINI_API_KEY;

GitHub and Vercel

Write .env and .env.local inside .gitignore. Then the code goes out and the key stays on the device. On Vercel, Settings, Environment Variables: the name is GEMINI_API_KEY and the value is the key itself. After you change the file, stop the terminal and start it again, or the result is undefined. In Next.js do not put NEXT_PUBLIC_ in front of the key: that sends it to the browser.

node_modules
.env
.env.local

Questions

Can I write const and quotes inside .env? No. Only NAME=VALUE. Do not put a space next to the equals sign either.

Why does process.env give undefined? The file just changed and the server still has the old one. Close the terminal and start it again.

Why is NEXT_PUBLIC_ dangerous? That word sends the variable to the browser. Do not use it on a secret key.

Where should the key live? On the server, inside process.env. Not in the code that runs in the browser.

Author: Nibras Code