Vibe coding with Claude Code course Β· Module 10: TikTok clone
Clip covers with AI: a model checked in the docs
In this lesson11
The clip is trimmed, the caption is ready but in the feed the clip greets the viewer with its first frame: a dark deck and a blurred hand. The crew wants to type a few words, for example "a chest full of gold on a beach at sunset", and get a vertical cover. Such an image is drawn by a model that generates images from a description, and Treasure Reels will ask it for one through the OpenAI API. This is a feature of the app, not a tool for writing code: Claude Code still writes the code, and OpenAI only paints covers for the users of the clone.
Every cover costs money on your OpenAI account, and you already know the rule from lesson 8_4: the key stays in the hold, meaning on the server. There is a new trap: a model name, which gets old faster than Claude's knowledge.
What you will learn
- order research of the current documentation before a single line of code is written;
- read a Route Handler that calls the image API with the key from the server and keeps the model name in one constant;
- check the description limit, an error that does not give away the key, and a stand-in cover for a crew without an OpenAI account;
- catch two typical agent mistakes in Cursor: a model from memory and the OpenAI package in the browser.
First, scouting the documentation
Claude's knowledge has a date, and the list of OpenAI models changes every few weeks. A model that Claude remembers well may already have a shutdown date or may have stopped working. That is why you start with scouting, as in lesson 5_4: Claude reads the pages with the built-in WebSearch and WebFetch tools, and you demand a link for every finding.
Request for Claude Code:
Do not write code. Read the current OpenAI documentation:
https://developers.openai.com/api/docs/guides/image-generation
https://developers.openai.com/api/docs/deprecations
and the README of the openai package on GitHub. Write: which image
models are current, which are being retired and when, in which field
the image comes back, whether the API may be called from the browser
and which Node.js version the package requires. A link to the page
for every finding. At the end a plan of covers for Treasure Reels,
without code.You compare the answer with the pages you open yourself, because from lesson 5_1 you know that WebFetch gives an extract, not the whole page. State as of November 2026: the current line is gpt-image-2.6 in two variants, gpt-image-2.6-sunburst for detailed work on an image and gpt-image-2.6-flare for fast generation, the previous line gpt-image-2.5 also works, the model gpt-image-2 is being retired with a shutdown on 10 February 2027, and gpt-image-1 and the DALL-E models no longer work. Three findings are more lasting. The image comes back in the b64_json field, which means as base64, an image written as text. The guide warns that before using GPT Image models you may need to verify your organization in the OpenAI console. The package README says it requires Node.js 22 or newer, and that in the browser it is blocked by default so that the key is not exposed.
The compiler will not defend you against an old name. In our run the types of the current openai package still listed dall-e-3 and gpt-image-1, so npx tsc --noEmit would have let both names through, and the error would have come out only at the first cover, in front of the crew.
Request: a cover through a Route Handler
You turn the plan from the report into a request that names the files, the constraints and the proof. Notice that the model name is not in it: Claude takes it from the documentation it has just read.
Request for Claude Code:
Add generating a clip cover. Install the openai package.
The Route Handler app/api/cover/route.ts (POST) calls images.generate
with the model from the documentation you read, kept in one constant
COVER_MODEL. The key from process.env.OPENAI_API_KEY, without NEXT_PUBLIC_
and without dangerouslyAllowBrowser. A description of 1 to 300 characters
(a constant in lib/cover.ts), a vertical image, the result from b64_json
as a data: address. An API error: a generic message and status 502, only
the status and the code in the log. Without a key the route returns a
stand-in cover from public/covers. The CoverGenerator component calls
only /api/cover, the page is /cover. Do not create the .env.local file.
At the end tests of the route, lint, types, build and curl without a key.What Claude wrote: the limit in one place
Open lib/cover.ts in Cursor. The description limit and the shape of the route's response live in a small file that both the server and the form read:
export const COVER_PROMPT_MAX = 300;
export type CoverResponse =
| { image: string; placeholder?: boolean }
| { error: string };CoverResponse is a union, a "one or the other" type: the route returns either an image, optionally marked as a stand-in, or an error. The text field in the form gets maxLength={COVER_PROMPT_MAX}, but that is only a hint for an honest pirate, because a request can be sent while bypassing the form. The real limit is checked by the route.
What Claude wrote: the route's guards
Open app/api/cover/route.ts. At the top stands the only model name in the project, and the POST function starts by checking the description:
// The only place with the model name. Check it in the OpenAI docs before changing it.
const COVER_MODEL = "gpt-image-2.6-flare";
export async function POST(request: Request) {
const body: unknown = await request.json().catch(() => null);
const prompt =
typeof body === "object" && body !== null && "prompt" in body && typeof body.prompt === "string"
? body.prompt.trim()
: "";
if (prompt.length === 0 || prompt.length > COVER_PROMPT_MAX) {
return Response.json(
{ error: `The cover description must be 1 to ${COVER_PROMPT_MAX} characters long` },
{ status: 400 },
);
}.catch(() => null) turns a body that is not JSON into null, so a broken request gets status 400 instead of a server error. The unknown type forces the code to check that prompt really is a string. A bad description will not go out to OpenAI, so you will not pay for it. The second guard protects the key:
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
return Response.json({ image: "/covers/placeholder.svg", placeholder: true });
}Without a key the route returns a stand-in cover from public/covers/ with the placeholder flag, so the app works also for someone who has no OpenAI account or who is waiting for the organization verification. The response gives away neither the name of the variable nor the file with the key.
What Claude wrote: the API call
Only now does the route create the OpenAI client with the key and ask for an image:
try {
const openai = new OpenAI({ apiKey });
const result = await openai.images.generate({
model: COVER_MODEL,
prompt,
size: "1024x1536",
quality: "low",
output_format: "jpeg",
});
const b64 = result.data?.[0]?.b64_json;
if (!b64) {
return Response.json({ error: "Cover generation is temporarily unavailable" }, { status: 502 });
}
return Response.json({ image: `data:image/jpeg;base64,${b64}` });1024x1536 is one of the three sizes that the OpenAI guide recommends, and the only vertical one. The guide recommends quality: "low" for fast drafts, and says that JPEG is produced faster than PNG. The route glues the base64 from b64_json to the prefix data:image/jpeg;base64, to make a data: address, which is an image written straight into the address, and the browser shows it without another request. The cover is not saved to disk: after a page refresh it will vanish, and saving is a separate step.
What Claude wrote: an error without secrets
When OpenAI refuses, the package throws an APIError, an error with the HTTP code in the status field and the error code in the code field:
} catch (err) {
if (err instanceof APIError) {
console.error(`OpenAI responded ${err.status ?? "without a status"} ${err.code ?? ""}`);
if (err.code === "moderation_blocked") {
return Response.json(
{ error: "The content filter rejected this description. Change it and try again." },
{ status: 400 },
);
}
} else {
console.error("Could not call OpenAI");
}
return Response.json({ error: "Cover generation is temporarily unavailable" }, { status: 502 });
}
}Only the status and the code go to the log, not the OpenAI message. That is not overkill: in our run the answer to a made-up key contained in its message the key's masked beginning and its last three characters. moderation_blocked is, according to the guide, a description rejected by the content filter, which is not retried without changing the description, so the crew gets status 400 and a request for a different description. Every other error is status 502, which means "the service behind me failed", as with the weather in lesson 8_4.
What Claude wrote: the component
components/CoverGenerator.tsx has "use client", a description field with a character counter and a button that sends fetch with the POST method to /api/cover. It does not import the openai package and does not know the key. The image is shown by the Image component from Next.js:
<Image
src={result.image}
alt={`Clip cover: ${prompt}`}
width={1024}
height={1536}
unoptimized
className="h-auto w-full rounded-lg"
/>According to the Next.js documentation, unoptimized serves the image as it is, skipping image optimization. A data: address is a ready file, and the stand-in cover is an SVG, so there is nothing to shrink here.
Captain's review
- The key and the package only in the route. Search the project (Cmd+Shift+F on a Mac, Ctrl+Shift+F on Windows) for
OPENAI_API_KEYandfrom "openai": both only inroute.ts.NEXT_PUBLIC_anddangerouslyAllowBrowserhave not a single hit. Then the test from lesson 8_4: in our run after a build with a made-up key in.env.local, a search for a fragment of it in.next/staticgave zero files. - A typical agent mistake: the package in the browser. The agent pastes
new OpenAI()into a component with"use client". In our run the package started in the browser-like environment of the tests refused to start with an error beginning withIt looks like you're running in a browser-like environment.. The agent likes to "fix" this withdangerouslyAllowBrowser: trueand a key fromNEXT_PUBLIC_, which is exactly the leak from lesson 8_4. You undo such a fix with/rewind. - The second typical mistake: a model from memory. Search for
COVER_MODEL: one definition, and its value agrees with the scouting report. A model name in a second file or a model from a retired line is a fix to make right away. - The error does not leak. Put a made-up key into
.env.local, build and start the app, then sendcurlto the route. In our run OpenAI answered401with the codeinvalid_api_key, the route returned{"error":"Cover generation is temporarily unavailable"}with status 502, and the server log held the lineOpenAI responded 401 invalid_api_key. A description of 301 characters got 400, and without a key the route returned{"image":"/covers/placeholder.svg","placeholder":true}. Tests of the route with a fakefetchcheck the same without the network. - Cost. The route is open to anyone who knows the address, and every call goes on your bill. Before Treasure Reels sails out to people, the route gets a lock with the session from lesson 8_3 and a limit of covers per person. You check current prices on the OpenAI website.
Without an OpenAI account
The stand-in cover is enough to finish this module. If you have an account, you paste the key into .env.local in Cursor yourself, never into the conversation with Claude, and you carry the deny rules for .env files from lesson 8_4 over to this project. Remember also lesson 9_2: a worktree is a fresh checkout without .env.local, so add this file to .worktreeinclude.
Next step
The next request is short: "Add .env.example with an empty OPENAI_API_KEY and an exception for this file in .gitignore". The exception is needed because the .env* line from create-next-app hides .env.example too. Then a commit, for example "Clip covers through a Route Handler". Saving the cover as the poster of a recording is a separate, small request for the next voyage.
In the editor below waits a cover generator with a fake server and a network panel. Change the state of the key on the server, type a description that is too long, and then turn on the agent's mistake with the key in the browser and see what shows in the network panel.
Remember: a map gets old faster than a compass, so before you sail out for a cover, check in the port log whether the island still exists, and leave the key to the treasury in the hold.
Code for this lesson: App.jsx
// Cover generator in miniature: a fake server and a fake OpenAI instead of the real API.
// In the project the route is served by app/api/cover/route.ts, and the key lives only in .env.local on the server.
import { useState } from 'react';
const COVER_PROMPT_MAX = 300;
const COVER_MODEL = 'gpt-image-2.6-flare';
const REAL_KEY = 'sk-proj-hold-123';
const KEYS = { none: '', fake: 'sk-proj-made-up-999', real: REAL_KEY };
// The cover colour is computed from the description, so the same description gives the same image.
function paint(prompt) {
let hash = 0;
for (const ch of prompt) hash = (hash * 31 + ch.charCodeAt(0)) % 360;
return { hue: hash, title: prompt.slice(0, 40) };
}
// Fake OpenAI: checks the key and the content filter, then paints.
function fakeOpenAI(key, prompt) {
if (key !== REAL_KEY) return { status: 401, code: 'invalid_api_key' };
if (/blood|violence/i.test(prompt)) return { status: 400, code: 'moderation_blocked' };
return { status: 200, cover: paint(prompt) };
}
// Fake Route Handler POST /api/cover: it runs "on the server", so it knows the key.
function coverRoute(body, serverKey, log) {
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
if (prompt.length === 0 || prompt.length > COVER_PROMPT_MAX) {
return { status: 400, json: { error: 'The cover description must be 1 to ' + COVER_PROMPT_MAX + ' characters long' } };
}
if (!serverKey) return { status: 200, json: { placeholder: true } };
const res = fakeOpenAI(serverKey, prompt);
if (res.status === 200) return { status: 200, json: { cover: res.cover } };
log('OpenAI responded ' + res.status + ' ' + res.code);
if (res.code === 'moderation_blocked') {
return { status: 400, json: { error: 'The content filter rejected this description. Change it and try again.' } };
}
return { status: 502, json: { error: 'Cover generation is temporarily unavailable' } };
}
export default function App() {
const [prompt, setPrompt] = useState('');
const [keyMode, setKeyMode] = useState('none');
const [agentBug, setAgentBug] = useState(false);
const [result, setResult] = useState(null);
const [network, setNetwork] = useState([]);
const [serverLog, setServerLog] = useState([]);
function handleSubmit(event) {
event.preventDefault();
const log = (line) => setServerLog((prev) => [...prev, line]);
if (agentBug) {
// Agent mistake: a key from NEXT_PUBLIC_ and a call to OpenAI straight from the browser.
setNetwork((prev) => [...prev, {
url: 'POST https://api.openai.com/v1/images/generations',
detail: 'Authorization: Bearer ' + REAL_KEY + ' | model: ' + COVER_MODEL,
leak: true,
}]);
const res = fakeOpenAI(REAL_KEY, prompt);
setResult(res.status === 200 ? { cover: res.cover } : { error: 'Error ' + res.status });
return;
}
const res = coverRoute({ prompt }, KEYS[keyMode], log);
setNetwork((prev) => [...prev, {
url: 'POST /api/cover',
detail: 'body: {"prompt": "' + prompt.slice(0, 30) + '"} | response ' + res.status,
leak: false,
}]);
setResult(res.json);
}
const tooLong = prompt.length > COVER_PROMPT_MAX;
return (
<div className="min-h-screen bg-gray-950 p-4 text-white flex flex-col gap-4 md:flex-row">
<form onSubmit={handleSubmit} className="flex w-full max-w-sm flex-col gap-2">
<label htmlFor="cover-prompt" className="text-sm font-semibold">Cover description</label>
<textarea
id="cover-prompt"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
placeholder="A chest full of gold on a beach at sunset"
className="rounded border border-gray-600 bg-gray-900 p-2 text-sm"
/>
<p className={tooLong ? 'text-xs text-red-400' : 'text-xs text-gray-400'}>
{prompt.length}/{COVER_PROMPT_MAX} (no maxLength, so you can test the route)
</p>
<button type="submit" className="rounded bg-amber-500 px-4 py-2 font-semibold text-black">
Generate cover
</button>
{result && result.error && <p role="alert" className="text-sm text-red-400">{result.error}</p>}
{result && result.placeholder && (
<div className="flex aspect-[2/3] w-40 flex-col items-center justify-center rounded-lg bg-sky-900 text-center text-sm">
<span className="text-4xl">β</span>
<span>stand-in cover</span>
</div>
)}
{result && result.cover && (
<div
className="flex aspect-[2/3] w-40 items-end rounded-lg p-2 text-sm font-semibold"
style={{ background: 'linear-gradient(160deg, hsl(' + result.cover.hue + ' 70% 45%), hsl(' + ((result.cover.hue + 60) % 360) + ' 70% 20%))' }}
>
{result.cover.title}
</div>
)}
</form>
<div className="flex-1 space-y-3 text-sm">
<fieldset className="space-y-1">
<legend className="font-semibold">Key in .env.local on the server</legend>
{[['none', 'no key'], ['fake', 'made-up key'], ['real', 'valid key (simulation)']].map(([value, label]) => (
<label key={value} className="flex items-center gap-2">
<input type="radio" name="key" value={value} checked={keyMode === value} onChange={() => setKeyMode(value)} />
{label}
</label>
))}
</fieldset>
<label className="flex items-center gap-2">
<input type="checkbox" checked={agentBug} onChange={(e) => setAgentBug(e.target.checked)} />
Agent mistake: the SDK in the browser with a key from NEXT_PUBLIC_
</label>
<div>
<p className="font-semibold">Browser network panel</p>
<ul className="space-y-1">
{network.length === 0 && <li className="text-gray-400">No requests.</li>}
{network.map((entry, i) => (
<li key={i} className={entry.leak ? 'rounded bg-red-950 p-2' : 'rounded bg-gray-800 p-2'}>
<code>{entry.url}</code>
<br />
<span className="text-xs">{entry.detail}</span>
</li>
))}
</ul>
</div>
<div>
<p className="font-semibold">Server log</p>
<ul className="text-xs text-gray-300">
{serverLog.length === 0 && <li>Empty.</li>}
{serverLog.map((line, i) => <li key={i}>{line}</li>)}
</ul>
</div>
</div>
</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. What does Treasure Reels use the OpenAI image API for?
2. Where did Claude write the image model name, and why?
Hands-on tasks in the game
- Horizontal ordering
Put in order the line that the Route Handler starts the image API call with: