Where your OpenAI API key lives and what it can spend

Create an OpenAI API key for your app, keep it on the server, test it, and set project spend limits before real users can run up a bill.

Simon, Founder of Shipyard

By · Founder of Shipyard

4 minute read

The key, the variable and the project

To add OpenAI models to an app you create a secret key on the API keys page at platform.openai.com/api-keys, store it on your server as OPENAI_API_KEY, and decide how much the key is allowed to spend before anyone else can reach it. The full secret is shown once, when you create it. If you lose it, create a new one and revoke the old one; there is no way to read it back.

The API platform is not the ChatGPT app. A ChatGPT subscription does not pay for API calls and does not create keys. New API accounts use prepaid billing: you buy credits first, and each request is deducted from that balance. OpenAI's help centre says purchased credits expire after one year and are not refundable, so buy what you expect to use rather than a large balance you might not spend.

Projects keep one product away from the others

Keys belong to a project inside your organization. A project is the natural boundary for a product: it has its own keys, its own usage view and its own limits. Create one project per product and create the key inside it, so a runaway loop in a side project shows up, and stops, where it started.

When you create the key you also choose who owns it. A key owned by a service account is meant for an app running on a server, and it keeps working if the person who made it leaves the team. A key owned by your own user is fine for testing on your laptop. For the key your production app reads, pick the service account.

Spend limits, credits and what actually stops requests

Three separate things can stop your app from getting answers, and they produce different errors. When the prepaid balance runs out, requests fail with credit_balance_exhausted. When you set a hard spend limit on the project or the organization and reach it, requests fail with a 429 and the code project_spend_limit_exceeded or organization_spend_limit_exceeded. And OpenAI assigns every organization an approved monthly usage limit that depends on its usage tier, which is separate from anything you configure.

A hard limit is the setting that protects you, and it is a choice: in the project's Limits settings you turn on enforcement so that requests fail once the limit is reached. A limit without enforcement only sends alerts. OpenAI's own billing help also warns not to treat the prepaid balance as an instant cutoff, because usage can briefly take it below zero. Keep the balance modest and set an enforced project limit as well.

Retrying does not fix any of these. A loop that retries on every 429 just hammers a closed door. Read the error code and handle the three cases differently: add credit, raise or wait out the limit, or back off for real rate limits.

A quick check that the key works

Listing models is a cheap way to confirm the key is valid and to copy a current model name, since names change with each release. As with every provider, a key that passes this check can still fail on a real request if the project has no credit, so send one real request after you add credit before you call the integration finished.

Terminal
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

Calling the model from a server route

Install the SDK with npm install openai. OpenAI's quickstart notes that the official SDKs read OPENAI_API_KEY from the environment on their own, so a client created with no arguments needs no key in code. In Next.js the call goes in a route handler or a server action. The variable has no NEXT_PUBLIC_ prefix, which keeps it out of the bundle sent to browsers.

The example reads the model from OPENAI_MODEL, a second variable you set on your host yourself, so switching models is a settings change rather than a new deploy. If you leave it unset the request goes out without a model and fails, which is easy to spot in your logs.

TypeScript
// app/api/ask/route.ts
import OpenAI from 'openai'

const client = new OpenAI() // reads OPENAI_API_KEY

export async function POST(req: Request) {
  // Check the session and a per-user rate limit here, before spending credits.
  const { question } = await req.json()

  const response = await client.responses.create({
    model: process.env.OPENAI_MODEL!, // set on your host, copied from GET /v1/models
    input: question,
    max_output_tokens: 800,
  })

  return Response.json({ text: response.output_text })
}

The route is now the thing to protect

Moving the key to the server stops strangers from reading it, but an open route that anyone can post to spends your credits just as well. Require a signed-in user, count requests per user and per address, and cap the length of each answer so a single request has a known worst case.

Keep .env files out of git, use a different key for development and production, and rotate a key the moment you suspect it has leaked. OpenAI also lets administrators set a maximum lifetime for keys at the organization or project level, which forces old keys to expire instead of living forever in a forgotten config.

What Shipyard does here

Shipyard does not call the model and never needs your OpenAI account. When you pick OpenAI as the AI provider, a launch writes your key into the host as OPENAI_API_KEY, on the server side only, and the build prompt it hands your coding agent tells it to keep every model call behind a server route. Creating the key, funding the project and setting the limit stay with you, because they are spending decisions.

Sources

Launch in an hour, not a weekend

Shipyard connects your accounts once, then sets up the domain, hosting, database, email and payments for every new product.

Get started See how it works

Read next