Most tutorials show you how to get a Google Gemini API key and then paste it straight into the code. That’s fine for a 30-second test. It’s a bad habit to carry into a real project.
Here’s how to get a key, use it, and keep it from becoming a problem.
1. Get your Google Gemini API key.
Create a key for free in Google AI Studio. Copy it once, then treat it like a password.
2. Put it in an environment variable.
Name it GEMINI_API_KEY. The official client libraries read that variable automatically, so you never have to touch the key in code.
# macOS / Linux
export GEMINI_API_KEY="your-key-here"
# Windows (PowerShell)
setx GEMINI_API_KEY "your-key-here"
3. Make your first request
Python
pip install -q -U google-genai
from google import genai
# Picks up GEMINI_API_KEY from the environment
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash", # swap for the current model in the docs
contents="Explain how AI works in a few words",
)
print(response.text)
JavaScript
npm install @google/genai
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-2.5-flash", // swap for the current model in the docs
contents: "Explain how AI works in a few words",
});
console.log(response.text);
No key appears anywhere in the code, which is the point.
4. Keep it out of Git
Add this before your first commit:
.env
.env.local
If a key ever lands in a commit, deleting the file isn’t enough because it stays in your history. Revoke it and generate a new one.
5. Never ship it to the browser
This is the mistake I see most. If your frontend calls Gemini directly, your key is visible to anyone who opens DevTools. Put a thin server in between:
// server.js (Express)
import express from "express";
import { GoogleGenAI } from "@google/genai";
const app = express();
app.use(express.json());
const ai = new GoogleGenAI({});
app.post("/api/ask", async (req, res) => {
const result = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: req.body.prompt,
});
res.json({ text: result.text });
});
app.listen(3000);
Your frontend calls /api/ask. The key never leaves the server. Add rate limiting and auth to that endpoint too, or someone will burn through your quota using your own proxy.
6. One key per environment
Use separate keys for dev, staging, and production. If one leaks, you revoke one key instead of breaking everything. It also makes usage easier to track.
Quick checklist
- Key stored in an environment variable
-
.envin.gitignore - No key in frontend code
- Server-side proxy with rate limiting
- Separate keys per environment
- A rotation plan before you need one
Final thought
A Google Gemini API key takes two minutes to create and a lot longer to clean up after it leaks. Set up the boring parts first.
How do you manage your keys? Env files, a secrets manager, something else? Tell me in the comments.
Top comments (0)