Vibe coding with Claude Code course · Module 9: Discord clone
External API: the Key Stays in the Hold
In this lesson9
Before every expedition the #treasure-hunts channel asks the same question: what will the weather be like in the port? Pirate's Cove doesn't know the weather itself. It asks an external API, someone else's service that your app talks to over the network. Such a service wants to know who is asking, so it issues you an API key: a long string that works like the password to your account there. Whoever gets the key asks on your bill until they use up the limit or run up the charges. In this lesson Claude Code adds a weather widget so that the key never leaves the hold, that is, the server.
What you will learn
- ask for an external API integration through a Route Handler, not from the browser;
- check in Cursor and in the built app where the key really ended up;
- see how the route handles a service error before the crew sees it;
- block Claude Code from reading
.envfiles with adenyrule.
Where the key lives
You keep keys in environment variables, values the app receives from outside rather than from code. In a Next.js project local values live in the .env.local file and code reads them through process.env.NAME. The Next.js documentation says plainly that variables without the NEXT_PUBLIC_ prefix are available only in the Node.js environment, that is, on the server. A variable with that prefix is written into the JavaScript sent to the browser at build time. For an API key that is a death sentence: anyone who opens the page can read it.
That is why the weather is fetched by a Route Handler, an API route on the server that you know from lesson 8_3. The browser asks only your route, and only then does the route ask the weather service, adding the key.
The OpenWeather key
Pirate's Cove uses the Current weather API from OpenWeather. According to its documentation you find the key on your account page, in the "API key" tab. The documentation also marks requests by city name as deprecated and asks for coordinates, while turning a city name into coordinates is the job of a separate Geocoding API. The guild sails to a few well-known ports, so a list of ports with coordinates and a single request are enough.
You paste the key into .env.local yourself in Cursor, never into the conversation with Claude. Everything you write in a session stays in the conversation, and an agent that knows the value can write it straight into the code.
Request for Claude Code:
Add a weather widget for the expedition on the #treasure-hunts channel.
Fetch the weather from OpenWeather (Current weather by coordinates,
units=metric, lang=en) in the Route Handler app/api/weather/route.ts.
Take the key from process.env.OPENWEATHER_API_KEY, without NEXT_PUBLIC_.
Keep the ports with coordinates in lib/ports.ts. The client component
components/WeatherWidget.tsx calls only /api/weather?city=<port id>.
Handle any response other than 200. Do not put the key in code, logs
or the route's response. Do not create .env.local, I will fill it in myself.
At the end run lint, types, build and a curl on the route with an unknown port.What Claude wrote: the list of ports
Open lib/ports.ts in Cursor. A port is an identifier, a name and two coordinates:
export const ports: Port[] = [
{ id: "gdansk", name: "Gdańsk", lat: 54.35, lon: 18.65 },
{ id: "nassau", name: "Nassau", lat: 25.06, lon: -77.35 },
{ id: "port-royal", name: "Port Royal", lat: 17.94, lon: -76.84 },
];The list works as a register of allowed ports. The browser sends only the id, and only the server knows the coordinates, so nobody can send an arbitrary request on your key through your route.
What Claude wrote: the route
Open app/api/weather/route.ts. The GET function receives a NextRequest, a request with a handy nextUrl field for reading the address parameters, and starts with two guards:
const port = ports.find((p) => p.id === request.nextUrl.searchParams.get("city"));
if (!port) {
return Response.json({ error: "Unknown port" }, { status: 400 });
}
const key = process.env.OPENWEATHER_API_KEY;
if (!key) {
return Response.json({ error: "Weather is not configured" }, { status: 503 });
}The first rejects a port outside the list with code 400, "bad request". The second catches a missing key on the server and says so in general terms, without a file name or a value. Next the route builds the address and asks the service:
const url = new URL("https://api.openweathermap.org/data/2.5/weather");
url.search = new URLSearchParams({
lat: String(port.lat), lon: String(port.lon), units: "metric", lang: "en", appid: key,
}).toString();
const res = await fetch(url);
if (!res.ok) {
console.error(`OpenWeather responded ${res.status}`);
return Response.json({ error: "Weather temporarily unavailable" }, { status: 502 });
}URLSearchParams builds the part of the address after the question mark and encodes special characters itself. fetch doesn't report an error for a 401 or 404 response, it rejects only on network errors, which is why the route checks res.ok. Only the status number goes to the log, not the address with the key. The crew gets code 502, which means "the service behind me failed", and a short sentence in English. At the end the route copies only three fields from the response into the Weather type from types/weather.ts: the port name, the temperature rounded with Math.round and the description from data.weather[0].description. Thanks to units=metric the temperature arrives in degrees Celsius, and lang=en asks for the description in English, the same language as the rest of the app.
What Claude wrote: the widget
components/WeatherWidget.tsx has "use client" because it reacts to the choice of a port. The fetching sits in an effect that runs on every change of city:
useEffect(() => {
let ignore = false;
fetch(`/api/weather?city=${city}`)
.then(async (res) => {
const body = await res.json();
if (!ignore) setResult(res.ok ? { city, weather: body } : { city, error: body.error });
})
.catch(() => {
if (!ignore) setResult({ city, error: "No connection to the server" });
});
return () => {
ignore = true;
};
}, [city]);The ignore flag comes from the React documentation: responses from the network can return in a different order than they left, so the result for an old port won't overwrite the new one. The documentation clears the state right inside the effect here, but the react-hooks/set-state-in-effect rule rejects such a call, which npm run lint showed us. So Claude derived the loading state from the data: const loading = result?.city !== city;.
Captain's review
- Where the key is. Open the project-wide search in Cursor (Cmd+Shift+F on a Mac, Ctrl+Shift+F on Windows and Linux). The name
OPENWEATHER_API_KEYshould stand only in the route,NEXT_PUBLIC_should appear nowhere, and a fragment of the key's value must not occur in any code file. - Git doesn't see the secret. The
.gitignorefromcreate-next-appcontains.env*. For usgit status --shortafter adding.env.localshowed only the new code files. - The error doesn't leak. Put a made-up key into
.env.localand ask the route. OpenWeather answered us401with the messageInvalid API key, and the route gave the browser only{"error":"Weather temporarily unavailable"}with code 502. The server log held the lineOpenWeather responded 401. A request for?city=tortugagave 400 and{"error":"Unknown port"}. - A typical agent mistake. An agent to whom you pasted the key in the conversation writes it into the code or adds
NEXT_PUBLIC_, because then the fetch "works" straight from the component. We checked such a version:npm run lintandnpx tsc --noEmitsaid nothing, and afternpm run buildthe key sat in the.next/static/chunks/...jsfile asappid=key-from-the-hold-123. That folder goes to every browser. Ask Claude togrep -ra fragment of the key in.next/staticafter the build: a good result is zero hits.
A key that has once reached the browser or Git history should be treated as burned: generate a new one on the account page.
Payments: the same rule
One day the guild wants to sell a VIP rank. We don't run a payments integration in this course, but the rule is the same as for the weather, and the Stripe documentation describes it precisely. For most new integrations Stripe recommends the Payment Element, a ready-made payment form, together with the Checkout Sessions API. Your server creates the payment object (a Checkout Session or a PaymentIntent) with a secret key, and the browser gets only the public key for loadStripe and a client secret, the key of that one payment. The server always sets the amount, because otherwise the customer would pick their own price. Money moves only when the page calls the confirmation (confirm in Checkout Sessions, stripe.confirmPayment in PaymentIntents), and Stripe sends the payment result to your server as a webhook event. Stripe adds one more thing: a route that creates payment sessions hides the key, but it doesn't protect itself from abuse, so it needs the same lock as the routes from lesson 8_3.
Next step: a lock on the chest with the keys
One place is left from which the key can leak: Claude itself. According to the Claude Code documentation, reading files in the project directory needs no permission even in Manual mode. For us in Manual mode the Read tool returned the whole content of .env.local without asking. The content of the file then lands in the conversation, and from there it can end up in code or in a log.
Request for Claude Code:
Add permissions.deny rules to .claude/settings.json that forbid
reading .env and every .env.* file. Then try to read .env.local
with the Read tool, and then with the cat command, and copy both messages.Open .claude/settings.json. In location 8 this project settings file held a formatting hook, and in Pirate's Cove Claude is only now creating it:
{
"permissions": {
"deny": ["Read(./.env)", "Read(./.env.*)"]
}
}Read(./.env.*) is a pattern in .gitignore syntax: the asterisk covers .env.local, .env.production and every other file that starts like that. You close a whole folder the same way: Read(./secrets/**), where two asterisks cover everything inside, subfolders included. For us Read answered File is in a directory that is denied by your permission settings., and cat .env.local got Permission to use Bash with command cat .env.local has been denied.. The same test in auto mode ended with the same two refusals.
The documentation says exactly what such a rule covers. It works in every mode, including auto and bypassPermissions, and it wins over any allow rule. It blocks the Read tool, while the Grep and Glob tools and files pointed at with @ are covered by Claude Code on a best-effort basis. It also forbids the Edit and Write tools from changing that file. It covers commands that Claude Code recognises in Bash, such as cat, head, tail, sed and tee, and the < and > redirections. It doesn't cover a command that reads files without naming them, such as grep -r pattern ., or a Python or Node script that opens the files itself. A hard block for all processes comes only from an operating-system-level sandbox. So this is the first layer, not the only one, and that is exactly why the key lives only in .env.local anyway.
The .claude/settings.json file travels in the repository, and deny rules from such a file work immediately for everyone who clones the project. Ask for a commit, for example "Weather via Route Handler and deny rules for .env".
In the editor below a widget simulation is waiting, with a browser network panel: see what the browser asks for, break the key and turn on the agent bug with NEXT_PUBLIC_.
Remember: the key to the hold is carried by the captain, not by a parrot on the shoulder that will repeat it to everyone in port.
Code for this lesson: App.jsx
// Weather for the expedition: the browser, your /api/weather route and a pretend OpenWeather.
// Everything runs here, without a network and without a real key.
import { useState } from 'react';
const ports = [
{ id: 'gdansk', name: 'Gdańsk', lat: 54.35, lon: 18.65 },
{ id: 'nassau', name: 'Nassau', lat: 25.06, lon: -77.35 },
{ id: 'port-royal', name: 'Port Royal', lat: 17.94, lon: -76.84 },
];
const VALID_KEY = 'key-from-the-hold-123';
const skies = {
'54.35': { temp: 7.6, description: 'overcast clouds' },
'25.06': { temp: 27.2, description: 'clear sky' },
'17.94': { temp: 29.4, description: 'light intensity shower rain' },
};
// Pretend OpenWeather: a wrong key gives 401, a good one gives the weather.
function openWeather(lat, appid) {
if (appid !== VALID_KEY) {
return { status: 401, body: { cod: 401, message: 'Invalid API key.' } };
}
const sky = skies[String(lat)];
return { status: 200, body: { main: { temp: sky.temp }, weather: [{ description: sky.description }] } };
}
// Your GET /api/weather?city=... route with the same guards as in the lesson.
function weatherRoute(city, serverEnv, log) {
const port = ports.find((p) => p.id === city);
if (!port) return { status: 400, body: { error: 'Unknown port' } };
const key = serverEnv.OPENWEATHER_API_KEY;
if (!key) return { status: 503, body: { error: 'Weather is not configured' } };
const res = openWeather(port.lat, key);
if (res.status !== 200) {
log('OpenWeather responded ' + res.status);
return { status: 502, body: { error: 'Weather temporarily unavailable' } };
}
return { status: 200, body: { port: port.name, temp: Math.round(res.body.main.temp), description: res.body.weather[0].description } };
}
export default function App() {
const [badKey, setBadKey] = useState(false);
const [buggy, setBuggy] = useState(false);
const [network, setNetwork] = useState([]);
const [serverLog, setServerLog] = useState([]);
const [shown, setShown] = useState(null);
function check(city) {
const serverEnv = { OPENWEATHER_API_KEY: badKey ? 'fake-key' : VALID_KEY };
const log = (line) => setServerLog((prev) => [line, ...prev].slice(0, 4));
let entry;
let result;
if (buggy) {
// Agent bug: NEXT_PUBLIC_ writes the key into the browser's JavaScript.
const port = ports.find((p) => p.id === city);
const publicKey = serverEnv.OPENWEATHER_API_KEY;
const res = openWeather(port.lat, publicKey);
entry = { url: 'https://api.openweathermap.org/data/2.5/weather?lat=' + port.lat + '&lon=' + port.lon + '&appid=' + publicKey, status: res.status, leak: true };
result = res.status === 200
? { port: port.name, temp: Math.round(res.body.main.temp), description: res.body.weather[0].description }
: { error: res.body.message };
} else {
const res = weatherRoute(city, serverEnv, log);
entry = { url: '/api/weather?city=' + city, status: res.status, leak: false };
result = res.body;
}
setNetwork((prev) => [entry, ...prev].slice(0, 5));
setShown(result);
}
return (
<div className="min-h-screen space-y-4 bg-slate-100 p-4 font-sans text-slate-900">
<section className="space-y-2 rounded-lg bg-slate-800 p-4 text-slate-100">
<h1 className="font-bold">Weather for the expedition</h1>
<div className="flex flex-wrap gap-2">
{ports.map((p) => (
<button key={p.id} onClick={() => check(p.id)} className="rounded bg-indigo-600 px-3 py-1">{p.name}</button>
))}
<button onClick={() => check('tortuga')} className="rounded border border-slate-400 px-3 py-1">Tortuga (not on the list)</button>
</div>
{shown && shown.error && <p className="text-red-300">{shown.error}</p>}
{shown && !shown.error && <p><span className="text-2xl font-bold">{shown.temp}°C</span> {shown.port}: {shown.description}</p>}
</section>
<div className="space-y-1 text-sm">
<label className="flex items-center gap-2"><input type="checkbox" checked={badKey} onChange={(e) => setBadKey(e.target.checked)} /> Wrong key in .env.local on the server</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={buggy} onChange={(e) => setBuggy(e.target.checked)} /> Agent bug: key in NEXT_PUBLIC_, fetch straight from the component</label>
</div>
<section className="rounded-lg border border-slate-300 bg-white p-3">
<h2 className="font-bold">Browser network panel</h2>
<p className="text-xs text-slate-500">This is what anyone sees who opens the browser's developer tools.</p>
<ul className="mt-2 space-y-1 font-mono text-xs">
{network.map((n, i) => (
<li key={i} className={n.leak ? 'text-red-700' : 'text-slate-800'}>GET {n.url} → {n.status}{n.leak ? ' (key visible!)' : ''}</li>
))}
</ul>
</section>
<section className="rounded-lg border border-slate-300 bg-white p-3">
<h2 className="font-bold">Server log</h2>
<ul className="mt-2 space-y-1 font-mono text-xs">
{serverLog.map((line, i) => <li key={i}>{line}</li>)}
</ul>
</section>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How does WeatherWidget get the weather from OpenWeather?
2. Why does the WeatherWidget effect have an ignore variable that the cleanup function sets to true?
Hands-on tasks in the game
- Horizontal ordering
Arrange the access to the weather description in the route: data.weather[0].description
- Vertical ordering
Arrange the path of the weather request from the click to the screen: