API Keys, .gitignore, Security

AI Track · Prereqs: F-JS-005, A-DEPLOY-001
--- theme: seriph title: "API Keys, .gitignore, Security + Vercel Serverless" info: "Module A-SAFETY-001 — protecting secrets, .gitignore, config.js pattern, Vercel serverless functions" --- # API Keys & Security Keep your secrets secret. --- # Where We Are You can `fetch` data from APIs. Some APIs require an **API key**. ```javascript const response = await fetch( `https://api.openweathermap.org/data/2.5/weather?q=Boston&appid=${API_KEY}` ); ``` Today's question: **where does `API_KEY` come from, and who can see it?** --- # What Is an API Key? A unique string that identifies **you** to an API provider. ``` appid=a1b2c3d4e5f6g7h8i9j0... ``` Why providers require them: - **Track usage** per developer - **Rate-limit** abusers - **Bill** for paid tiers - **Revoke** access if misused Treat an API key like a **password**. > AI tip: When you paste code into AI for help, check for API keys first. Your key goes with it and may appear in AI training data. --- # The Worst Idea Hardcoding the key directly in your JavaScript: ```javascript // app.js <-- pushed to GitHub const API_KEY = 'sk-abc123-real-key-here'; ``` What happens: 1. You push to GitHub 2. Your repos for this course are **public** 3. Bots scrape GitHub for keys **within seconds** 4. Your key is stolen, your account is charged This has cost real developers real money. --- # `.gitignore` — Telling Git to Look Away A `.gitignore` file lists patterns Git should **never track**. ```text # Secrets config.js .env # OS junk .DS_Store Thumbs.db # Dependencies node_modules/ ``` Create this file at the **root** of your repo, before your first commit. > AI tip: Ask AI "generate a .gitignore for a web project" to get a solid starting template. --- # `.gitignore` Rules | Pattern | What it ignores | |---|---| | `config.js` | That exact file in the root | | `*.log` | Any file ending in `.log` | | `build/` | The entire `build` directory | | `!important.log` | Exception — do track this file | After adding `.gitignore`, run `git status`. Ignored files should **not** appear. > If you already committed a file, adding it to `.gitignore` won't remove it. You need `git rm --cached config.js` first. --- # The `config.js` Pattern **Step 1:** Create `config.js` with your key: ```javascript // config.js — DO NOT commit this file const API_KEY = 'sk-abc123-your-real-key'; ``` **Step 2:** Add `config.js` to `.gitignore` **Step 3:** Load it before your main script: ```html <script src="config.js"></script> <script src="app.js"></script> <!-- app.js can now use the API_KEY variable --> ``` --- # Does `config.js` + `.gitignore` Actually Protect the Key? **From GitHub?** Yes. The key never enters your repo. **From users of your deployed site?** No. Open DevTools on any website: - **Sources** tab shows every `.js` file - **Network** tab shows every request, including headers and query strings Anyone visiting your page can read `config.js` in full. --- layout: center --- # So how do real apps protect keys? --- # The Real Solution: Server-Side Proxy Your key lives on a **server** that you control. The browser never sees it. ``` Browser Your Server Weather API | | | |-- /api/weather?q=BOS ->| | | |-- ?q=BOS&appid=KEY --->| | |<-- { temp: 72 } -------| |<-- { temp: 72 } -------| | ``` The browser talks to **your server**. Your server adds the key and talks to the API. The key never reaches the browser. --- # Vercel Serverless Functions **Vercel** lets you deploy tiny server-side functions with zero config. Project structure: ``` my-project/ ├── index.html ├── css/ ├── js/ │ └── app.js └── api/ └── weather.js <-- runs on Vercel's server, not in the browser ``` Any `.js` file inside `api/` becomes a server endpoint automatically. --- # How Serverless Functions Work ``` Browser Vercel (server) Weather API | | | |-- fetch('/api/weather') ->| | | | reads API key from | | | environment variable | | |-- request + API key ----->| | |<-- weather data ----------| |<-- { city, temp } --------| | ``` Your API key is stored in **Vercel's settings**, not in any file. The browser never sees it. You will write your own serverless function in MP3. --- # Calling Your Function from the Browser ```javascript // js/app.js — runs in the browser async function getWeather(city) { const response = await fetch(`/api/weather?city=${city}`); const data = await response.json(); document.querySelector('#temp').textContent = `${data.city}: ${data.temp}°F`; } ``` Notice: **no API key anywhere in the browser code**. Open DevTools, check Network, check Sources -- the key is invisible. > AI tip: Confused by the proxy pattern? Ask AI "explain the difference between client-side and server-side fetching." --- # Vercel Environment Variables 1. Push your project to GitHub 2. Import the repo at **vercel.com/new** 3. Go to **Settings** > **Environment Variables** 4. Add `WEATHER_API_KEY` = your actual key 5. Deploy The key lives on Vercel's servers. It never appears in your code, your repo, or the browser. --- # When to Use What | Approach | Key on GitHub? | Key visible in browser? | Use when | |---|:---:|:---:|---| | Hardcoded in `.js` | Yes | Yes | Never | | `config.js` + `.gitignore` | No | Yes | Class exercises with free API keys | | Vercel serverless function | No | No | Mini Project 3+, any paid/sensitive key | The serverless approach is what professional apps use. You'll set it up in MP3. --- # Your Turn: Protect Your Project In your project repo: 1. Create a `.gitignore` file at the root with entries for `config.js`, `.env`, `.DS_Store`, and `node_modules/` 2. Create a `config.js` file with a placeholder: `const API_KEY = 'your-key-here';` 3. Run `git status` and confirm that `config.js` does **not** appear in the list > AI tip: Ask AI "check my .gitignore -- am I missing anything important for a web project?" to catch common oversights. --- # Key Takeaways 1. **API keys are secrets** -- treat them like passwords 2. **`.gitignore`** keeps files out of your repo -- create it early 3. **`config.js` pattern** prevents GitHub exposure but keys are still visible in the browser 4. **Client-side code is never private** -- anyone can View Source 5. **Vercel serverless functions** hide keys on the server -- the real solution 6. **Environment variables** store secrets outside your codebase

Topics Covered

  • .gitignore
  • config.js pattern
  • why API keys must not be in client-side code
  • Vercel serverless function as the real solution

Content Slides Open fullscreen ↗

Taught In

  • Monday, 6/22 — JS async + fetch · API keys + .gitignore