Learn how to prompt AI to handle fetch calls, error states, and environment variables safely.
Let's think about it this way for a sec
When it comes to connecting APIs, AI tends to write only the happy path. In vibe coding, you need to explicitly ask for loading, empty, error, and unauthorized states too. Never put keys in source code. Make the distinction between NEXT_PUBLIC_ and server-only variables clear. Spell it out in your prompt: the client should never call a secret key directly.
Connecting it to everyday life
If you want to call a Notes API, ask for it like this: "the route handler should read the key only on the server, the client should just fetch /api/notes, and it should show an inline error on a 400." If AI pulls in some heavyweight SDK you don't actually need, cut it. Check the request yourself in the Network tab. And giving it an example JSON for the response shape usually gets you a more accurate result.
Let's try it together
export async function GET() {
const apiKey = process.env.NOTES_API_KEY;
if (!apiKey) {
return Response.json({ error: "Missing server configuration" }, { status: 500 });
}
const response = await fetch("https://example.com/notes", {
headers: { Authorization: `Bearer ${apiKey}` },
cache: "no-store",
});
if (!response.ok) {
return Response.json({ error: "Upstream failed" }, { status: 502 });
}
return Response.json(await response.json());
}You'll be able to review and approve a rough API route that doesn't leak secrets.5-Minute Try-It
Write a bad example of a fetch call made directly from the client. Explain why it's risky and how you'd prompt AI to fix it.
A Quick Word of Caution
Never treat AI output as automatically correct. Have a human read through the code and test it — and double-check secrets and user data — before you rely on it.