Installation
Requirements
- Node.js 22+ (tested on 22 / 24 / 26; follow current LTS in production)
- pnpm (official quickstart default; npm / bun / yarn also work)
- At least one secret:
AI_GATEWAY_API_KEY(Gateway) or a vendor key such asOPENAI_API_KEY
AI SDK 7 is ESM-only. Next.js App Router apps are usually already ESM. For a plain Node script, set "type": "module" in package.json or use .mjs. require('ai') fails.
Create a Next.js app (recommended)
Official App Router quickstart:
Choose App Router and Tailwind if prompted. See this site’s Next.js tutorial for framework details.
Install AI SDK packages
For direct OpenAI (not Gateway strings), also install:
Configure secrets
Create .env.local at the project root (Next.js loads it; do not commit it):
Gateway reads AI_GATEWAY_API_KEY by default. Direct OpenAI reads OPENAI_API_KEY.
Temporary PowerShell:
Secrets belong in route handlers, Server Actions, and Node scripts only. Never prefix them with NEXT_PUBLIC_.
Two ways to name a model (do not mix them up)
1. Gateway (default global provider) — a string, no vendor package:
gateway('anthropic/claude-sonnet-4.5') is equivalent to the string form. You can also import { gateway } from '@ai-sdk/gateway'.
2. Direct OpenAI — install @ai-sdk/openai:
Gateway "openai/gpt-4.1-mini" is not openai('gpt-4.1-mini'). The first routes through Gateway; the second hits the OpenAI API. Mixing them connects the wrong backend or yields “model not found”.
Plain Node (no Next.js)
Add "type": "module" to package.json. Use the same generateText API. Chat UI is what needs @ai-sdk/react and React.
Suggested layout
See the TypeScript and Next.js tutorials for language and App Router conventions.
Troubleshooting
ERR_REQUIRE_ESM / require is not defined?
The project is not ESM. Add "type": "module", or use import only under Next.js app/.
Node too old?
node -v must be ≥ 22.
Gateway 401?
Check the filename .env.local, restart pnpm dev, and confirm the key is an AI Gateway key.
Direct OpenAI timeouts?
You may need a proxy, Gateway, or local Ollama (see Providers).