Add OpenAI API Integration
Cursor prompt to add a secure, typed OpenAI integration in Next.js — server-only keys, structured outputs, and persisted runs.
Problem this prompt solves
The fastest path — fetch('https://api.openai.com') from a client component — leaks keys, skips authz, and gives you no audit trail when a prompt goes wrong. A durable integration lives on the server, validates inputs, bounds tokens/timeouts, and records each run against the owning user and resource.
When to use it
- You are adding the first AI feature to a Next.js App Router app with Supabase auth already in place.
- You have a prototype that calls OpenAI from the browser and need to move it server-side before beta.
- You want structured JSON outputs (not free-form chat UI) tied to a database record.
- You need streaming later but must ship a reliable non-streaming path first.
Cursor prompt
Add a production-minded OpenAI integration to this Next.js (App Router, TypeScript) app. Use the official openai SDK on the server only. Requirements: 1) Create a small server module (e.g. lib/ai/openai.ts) that reads OPENAI_API_KEY, sets a default model via env (OPENAI_MODEL), and exports typed helpers. 2) Implement one product-facing AI action as a Route Handler or Server Action: - Require an authenticated Supabase user - Verify the user owns the target resource (RLS or explicit check) - Validate input with zod (max lengths, allowed fields) - Call OpenAI with: temperature defaults, max_tokens cap, and a timeout - Prefer structured output (JSON schema / zod parse) matching the product need - Persist an ai_runs (or equivalent) row: status, model, token usage, latency, error message - Return a typed result to the UI; never return the raw SDK error object 3) UI: a clear trigger button, loading/disabled state, and inline error display. 4) Optional: if the product benefits from streaming, add a streaming route AFTER the non-streaming path works — do not start with streaming only. 5) .env.example: OPENAI_API_KEY, OPENAI_MODEL. Document that keys are server-only. 6) Add a short comment or README section: how to rotate keys and how to switch models. Safety and cost defaults: - Reject empty/oversized inputs before calling the API - Cap max_tokens appropriately for the use case - Do not log full prompts/responses to stdout in production; log run ids and error codes - Do not expose the API key, organization id, or upstream stack traces to the client If the schema for ai_runs is missing, propose minimal SQL and wire it up. Match existing project patterns.
Expected result
A server-only OpenAI helper, one authenticated AI action with zod validation, persisted run metadata (model, tokens, latency, errors), and a UI path that handles loading and failure without leaking secrets.
Implementation notes
- Keep prompts in server code or a private prompts module — not in client bundles.
- Parse model JSON defensively; models drift and partial JSON will show up in production.
- Record prompt_tokens and completion_tokens from the API response even if you do not bill yet.
- Use AbortSignal / timeout so a hung upstream call cannot exhaust serverless duration silently.
- Start with a cheap default model in env; swap via OPENAI_MODEL without code edits.
- If you need file or long-context inputs later, design the run record to store storage paths, not megabyte strings in Postgres.
Testing checklist
- Authenticated user can run the action and sees a persisted success result after refresh.
- Unauthenticated request to the route returns 401/403.
- User B cannot run the action against user A’s resource id.
- Oversized input is rejected before any OpenAI call (check logs/network).
- Invalid API key produces a user-safe error and a failed ai_runs row.
- Token usage fields are populated on success.
- No OPENAI_API_KEY string appears in client bundles or network responses.
Common mistakes
- NEXT_PUBLIC_OPENAI_API_KEY — instant key leak.
- No ownership check on the resource id — IDOR on generations.
- Trusting model JSON without validation — UI crashes on shape changes.
- Retrying blindly on all errors — duplicate side effects and double spend.
- Logging full prompts containing user PII to third-party log drains.
- Building a full chat playground when the product needs a single structured transform.
Building something real?
If you’ve moved beyond experimenting and need help defining or building your MVP, RemoteGeek can help turn the idea into a focused implementation plan.
Related resources
Related Cursor prompts
Reduce OpenAI API Costs
Cursor prompt to audit and cut OpenAI spend — caching, smaller models, token caps, batching, and usage-aware product defaults.
Add Model Routing
Cursor prompt to implement task-based model routing — cheap models for simple work, stronger models for hard tasks, with overrides and logging.
Add Rate Limiting
Cursor prompt to add practical rate limiting to AI and auth routes on Vercel/Next.js before public traffic hits your OpenAI bill.
Build a SaaS MVP with Cursor
A Cursor prompt that scaffolds a production-shaped AI SaaS MVP on Next.js, Supabase, and Vercel — auth, core workflow, and deploy path included.
Next recommended guide
How to Build an AI SaaS MVP with Cursor: Step-by-Step GuideA practical path from idea to public beta: scope an AI SaaS MVP, stack it on Next.js + Supabase + Vercel, drive Cursor sessions, wire AI safely, and control cost.
RemoteGeek Builder Notes
One practical lesson each week. No hype.
AI building, automation, and technology-risk notes for professionals and solo builders. Signing up stores your email for follow-up — automated newsletter delivery may be connected later.