Tutorial build: your first API call, done safely
A short build you can follow: call a third-party API from a server function, keep the key off the client, and prove it is not exposed.
The idea
The smallest possible project that teaches the habit that prevents the most common security mistake in AI-built apps.
Architecture
- One page with a form.
- One server function that holds the key and makes the outbound request.
- No database, no accounts — deliberately.
Tools
| Tool | Role |
|---|---|
| Any AI building platform | Generates the page and the server function |
| A third-party API | Anything with a free tier and a secret key |
The build process
- Ask for the server function first, not the page. The order matters: it puts the key in the right place from the start.
- Read the key from the environment inside the handler, and throw a clear error when it is missing.
- Add the form and have it call your own endpoint, never the provider.
- Return the provider's error text to your logs and a readable message to the user.
What the AI generated
- A validated server endpoint.
- A form with pending and error states.
- An environment variable reference for the key.
What was happening underneath
- The browser only ever talks to your own origin, so there is no key and no cross-origin problem to solve.
- The provider sees one caller — your server — which makes rate limiting and caching straightforward later.
Problems, and what they actually were
The first generated version called the provider from the component.
Underneath: That is the shortest path to working code, and it works perfectly while shipping the key to every visitor.
Fix: Moved the call into a server function and searched the built output to confirm the key was gone.
A missing variable produced a confusing 401 rather than a clear message.
Underneath: An unset variable becomes undefined, and the request goes out with an empty credential.
Fix: Added an explicit check that throws a configuration error naming the variable.
Deployment
- Set the variable in the hosting environment as well as locally.
- Redeployed, then searched the deployed JavaScript for the key to confirm absence.
Lessons learned
- Where code runs matters more than how it is written.
- Fail loudly on missing configuration; silence turns a one-minute fix into an hour.
- Proving a key is absent is a quick search, and worth doing every time.
Read the concepts behind it
- API keys explainedWhat an API key is, what it proves, why some keys are safe in a browser and others are not, and how to handle one without leaking it.
- How to keep API keys out of your frontendA practical method for moving secret-using code to the server, checking what actually shipped to the browser, and proving a key is no longer exposed.