Chapter 8: Hackers' Favorite Target! Environment Variables (.env) and Security Protection

In previous chapters, we learned how to apply for Supabase and obtained the database URL and API Key. In the future, you might also apply for Gmail sending passwords or OpenAI Tokens.

Stop what you're doing immediately and listen carefully: There's one fatal mistake you must never make—writing these "secret strings" directly in your code and uploading them to public GitHub! If you make this mistake, your API keys will become hackers' free ATM.


🔒 What Are Environment Variables? Why Use Them?

Imagine you write a safe key (e.g., GMAIL_PASS="super-secret-123") directly in your code send-email.ts. When you share the code with colleagues or upload it to GitHub, everyone in the world can see this key! Anyone with malicious intent can search for it and send thousands of spam emails in your name or delete your entire database.

To solve this problem, engineers invented the concept of Environment Variables. We create a hidden file called .env to store all passwords centrally:

# .env file
NEXT_PUBLIC_SUPABASE_URL="https://your-project.supabase.co"
NEXT_PUBLIC_SUPABASE_ANON_KEY="eyJhbGciOiJIUzI1NiIsIn..."
OPENAI_API_KEY="sk-proj-xxxxxxxxxxxx"
GMAIL_PASS="abcd-efgh-ijkl"

In the code, instead of hardcoding passwords, we use "references" to call them. In the Next.js/React ecosystem, we write it like this:

// Code example
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const openaiKey = process.env.OPENAI_API_KEY;

When the program runs, the system automatically fetches the corresponding passwords from the .env file. This keeps the code clean without any sensitive information.


🛡️ .gitignore: The Life-Saving Invisibility Cloak

Simply moving passwords to the .env file isn't enough! If you upload the .env file itself to GitHub when executing git commit, all your efforts will be wasted!

This is where the .gitignore file comes in. It acts like a customs blacklist, telling Git (the version control system): "These files are too private—never back them up!"

Open the .gitignore file in your project root, and you'll typically see:

node_modules/
.next/
.env
.env.local
.env.*

With these lines, Git will automatically ignore the .env file when you upload your code. Your secrets will remain only on your local machine.

🔥 [Vibe Coder Pro Tip] Create .env.example Since .env isn't uploaded, how will your colleagues (or future you) know which passwords to fill in when downloading the project on another computer? The professional approach is to create a file called .env.example and upload it to GitHub. It contains only variable names, no passwords:

# .env.example
NEXT_PUBLIC_SUPABASE_URL="Fill in your Supabase project URL"
OPENAI_API_KEY="Fill in your OpenAI API Key"

When others download the project, they can copy this file, rename it to .env, and fill in their own passwords. This is the industry gold standard for collaboration etiquette.


⚠️ [Common Pitfall] Why Can't I Access Environment Variables on the Frontend?

This is the most frustrating issue for beginners. You write SECRET_TOKEN="123" in .env, but console.log(process.env.SECRET_TOKEN) in a React component returns undefined.

Solution: Understand the "Security Prefix" concept! Modern frontend frameworks (like Next.js or Vite) block all environment variables from leaking to the user's browser by default for security.

  • Backend-only (Private): If you write OPENAI_API_KEY, this variable can only be accessed server-side (Server Components or API Routes). Frontend attempts to read it will return undefined. This is correct—you should never expose OpenAI keys to users' browsers!
  • Frontend-accessible (Public): If you genuinely need the frontend (browser) to access a variable (e.g., Supabase's Anon Key, which is designed to be public), you must add a specific prefix:
    • In Next.js: NEXT_PUBLIC_ (e.g., NEXT_PUBLIC_SUPABASE_URL).
    • In Vite: VITE_ (e.g., VITE_SUPABASE_URL), accessed via import.meta.env.VITE_SUPABASE_URL.

🚨 Emergency! I Accidentally Uploaded Passwords to GitHub. What Now?

The most common beginner mistake is forgetting to set up .gitignore, accidentally uploading a real-password .env file to public GitHub.

Critical note: Hackers run dedicated bots that scan GitHub 24/7 for leaked keys! If your leak lasts more than a few minutes, your AWS cloud bill could skyrocket by hundreds of thousands, or your OpenAI credits could be drained instantly.

If you discover you've leaked passwords, do NOT attempt to delete the file or modify Git history on GitHub—it's too slow and ineffective (history is permanent).

The only thing you must do: Immediately revoke the leaked password at its source and generate a new one!

  • For OpenAI keys: Log into OpenAI's dashboard and delete the key.
  • For Supabase: Regenerate a new API Key in the settings.
  • For Gmail: Delete the app password in Google Account settings. Once the old password is invalidated, hackers will only have useless data.

💼 [Business Use Case] Separating Development and Production Environments

Mastering environment variables prepares you for large-scale commercial projects. In real enterprise development, you can't use the same database for testing and production—what if you accidentally delete real customer orders during testing?

Environment variables save the day. You can set up a .env.local on your local machine connecting to a "test database." Then, on the Vercel deployment platform, go to Settings -> Environment Variables and enter the "production database" passwords. The same code will connect to the test database on your local machine and automatically switch to the production database when deployed. This is the first step in modern software engineering's CI/CD (Continuous Integration/Continuous Deployment)!

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!