OpenAI's API powers many of the AI features we build: chat assistants, content generation, data extraction and agents. This guide shows the exact setup we use in Next.js projects with the official TypeScript SDK and the Responses API.
1. Setup and security
Create an API key in the OpenAI dashboard, add it to your environment variables and install the SDK. The SDK reads OPENAI_API_KEY automatically. We also store the model name in an environment variable, because OpenAI releases new models regularly.
npm install openai zodOPENAI_API_KEY=sk-...
OPENAI_MODEL=model-name-from-the-openai-models-pageimport OpenAI from "openai";
// Server-only module. Do not import this in client components.
export const openai = new OpenAI();
export const MODEL = process.env.OPENAI_MODEL!;“Treat the model like any external service: keep the key on the server, validate what comes back and log what it costs.”— Strategic Takeaway
2. Your first request
The Responses API takes instructions (how the model should behave) and input (the user's request), and returns the text in output_text.
"use server";
import { openai, MODEL } from "@/lib/openai";
export async function writeProductDescription(name: string, features: string[]) {
const response = await openai.responses.create({
model: MODEL,
instructions: "You write clear, benefit-led product descriptions in under 80 words. British English.",
input: `Product: ${name}\nFeatures: ${features.join(", ")}`,
});
return response.output_text;
}3. Streaming answers to the browser
For chat interfaces, waiting several seconds for a full answer feels slow. Streaming sends text as it is generated. This route handler streams plain text that any frontend can read.
import { openai, MODEL } from "@/lib/openai";
export async function POST(request: Request) {
const { message } = await request.json();
const stream = await openai.responses.create({
model: MODEL,
instructions: "You are a helpful assistant for our customers. Be brief and friendly.",
input: message,
stream: true,
});
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
controller.enqueue(encoder.encode(event.delta));
}
}
controller.close();
},
});
return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
}const res = await fetch("/api/chat", { method: "POST", body: JSON.stringify({ message }) });
const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
setAnswer((prev) => prev + decoder.decode(value)); // append text as it arrives
}4. Getting reliable JSON with structured outputs
When your code needs to use the result (for example, saving extracted invoice fields to a database), free text is fragile. Structured outputs force the model to return data that matches your schema.
import { z } from "zod";
import { zodTextFormat } from "openai/helpers/zod";
import { openai, MODEL } from "@/lib/openai";
const Invoice = z.object({
supplier: z.string(),
invoiceNumber: z.string(),
totalAmount: z.number(),
currency: z.string(),
dueDate: z.string().describe("ISO date, e.g. 2026-12-01"),
});
export async function extractInvoice(invoiceText: string) {
const response = await openai.responses.parse({
model: MODEL,
instructions: "Extract the invoice details. If a field is missing, make your best guess and keep it realistic.",
input: invoiceText,
text: { format: zodTextFormat(Invoice, "invoice") },
});
return response.output_parsed; // fully typed Invoice object
}5. Pricing and cost control
OpenAI charges per million tokens, with different rates for input, cached input and output on every model. Flagship models cost much more than the smaller, faster ones, so we match the model to the job: small models for classification and short drafts, flagship models for complex reasoning.
Two built-in savings are worth knowing: repeated prompt prefixes are billed at a discounted cached-input rate, and the Batch API halves the price for work that can wait for results. Embeddings are very cheap. text-embedding-3-small costs $0.02 per million tokens (checked November 2026).
- Set a monthly budget and usage alerts in the OpenAI dashboard.
- Put stable instructions first and variable content last, to benefit from prompt caching.
- Limit output length and conversation history you send back with each request.
- Log usage (input and output tokens) per feature, so you know which feature costs what.
Official resources
Principles for deliberate execution
- 1Call OpenAI only from the server: route handlers, server actions or a backend API.
- 2Stream responses for chat-style features so users see answers immediately.
- 3Use structured outputs with a Zod schema whenever your code needs to read the result.
- 4Use cached input and the Batch API to cut costs for repeated or non-urgent work.