Next.js LLM Integration with 59API
Integrating LLMs into a Next.js App with 59API
Adding a large language model to a Next.js app is now straightforward, but production-quality integration still requires careful handling of API keys, streaming, errors, and cost. This tutorial shows a practical way to connect a Next.js application to Claude or GPT models through 59API, an AI API relay with a base URL of https://api.59api.com. It is compatible with OpenAI SDK usage patterns, Claude Code, Codex-style workflows, and gives developers pay-as-you-go access to official-quality models without downgrades.
Step 1: Create or open a Next.js project
If you are starting from scratch, create a new App Router project with TypeScript enabled. In your terminal, run a standard Next.js setup command such as npx create-next-app@latest my-ai-app, then enter the project directory. For an existing app, confirm you are using a recent Next.js version and that your app directory is available for route handlers or server actions.
Install the OpenAI SDK because 59API is compatible with OpenAI-style clients. Use npm install openai, pnpm add openai, or yarn add openai depending on your package manager.
Step 2: Add your 59API credentials safely
Create a .env.local file in the root of your project and add your API key. Use a variable such as API_59_KEY. Never expose this value in client components, browser JavaScript, or public environment variables. Your LLM requests should run on the server through a route handler or server action.
59API is useful here because it lets you route requests to Claude models such as Opus, Sonnet, Haiku, and Fable, as well as GPT models, through a low-cost pay-as-you-go relay. For teams experimenting with multiple model families, this avoids wiring separate billing flows and SDK patterns too early.
Step 3: Configure the API client
Create a server-only helper file, for example lib/ai.ts. Import the OpenAI client and initialize it with your 59API key and base URL. Conceptually, the configuration should set apiKey to process.env.API_59_KEY and baseURL to https://api.59api.com. Keep this file imported only by server code.
When choosing a model, start with a fast and affordable option for common chat features, then upgrade only where quality demands it. For example, use a Haiku-class or smaller GPT model for short support answers, and reserve Sonnet, Opus, or stronger GPT models for deep reasoning, coding help, summarization, or agentic workflows. This model-switching flexibility is one reason a relay like 59API can reduce costs without forcing a quality downgrade.
Step 4: Build a server route for chat
In the App Router, create an API route such as app/api/chat/route.ts. Accept a POST request containing the user message and optional conversation history. Validate that the message is a non-empty string and limit its length. This prevents accidental huge prompts and protects your budget.
Inside the route, call the chat completions endpoint with a messages array. Include a system message that defines your assistant’s role, then append the user message. Return the model’s response as JSON. A simple production pattern is to return an object with answer, model, and usage fields when available. Usage data helps you monitor cost per request and identify features that need prompt optimization.
Step 5: Add a client-side chat interface
Create a client component with local state for the input, loading status, error message, and chat messages. On form submit, send a POST request to /api/chat with the latest message. Disable the submit button while the request is running and append the assistant response when the API returns successfully.
Keep the browser payload small. Send only the conversation turns required for context instead of the entire chat history forever. A good initial approach is to send the last 6 to 10 messages, plus a compact summary if the conversation becomes long.
Step 6: Improve prompts for reliable output
Do not rely on vague instructions. Your system prompt should describe the task, audience, boundaries, and output format. For example, if your app answers product questions, tell the model to answer only from provided product data, say when information is missing, and avoid inventing policy details.
- Be specific: tell the model what role it plays and what it must not do.
- Control length: request concise answers when latency and cost matter.
- Use structured outputs: ask for JSON when your UI needs predictable fields.
- Add examples: include one or two ideal responses for critical workflows.
Step 7: Add streaming for a better user experience
For chat interfaces, streaming makes the app feel faster because users see tokens appear as they are generated. In Next.js, implement streaming in your route handler and return a readable stream to the browser. On the client, read chunks from the response body and update the visible assistant message incrementally.
Streaming is especially helpful for longer Claude Sonnet, Claude Opus, or GPT responses. It does not necessarily reduce total generation time, but it improves perceived performance and keeps users engaged while the model works.
Step 8: Handle errors, limits, and cost controls
Production LLM features need guardrails. Add try-catch handling around the API call, return friendly error messages, and log technical details only on the server. Rate-limit requests by user ID, IP, or session. Set maximum input length, maximum output tokens, and timeout behavior.
Track which model each feature uses. Many apps overspend because every request goes to the strongest model. With 59API’s cheap pay-as-you-go access and support for multiple native official-quality models, you can route lightweight tasks to lower-cost models and reserve premium models for high-value actions. If you are testing LLM features in a Next.js product, it is worth signing up for 59API to compare Claude and GPT options under one compatible base URL.
Step 9: Prepare for deployment
Before deploying to Vercel or another platform, add API_59_KEY to your hosting provider’s environment variables. Confirm your API route runs on the server, not in the browser. Test a real request in production, check logs, and verify that errors do not leak secrets.
Finally, create a simple evaluation checklist: response accuracy, latency, average cost, refusal behavior, and formatting consistency. LLM integration is not a one-time install; it improves as you tune prompts, choose better models per task, and observe real user behavior. With Next.js handling the application layer and 59API simplifying affordable access to Claude and GPT models, you can ship AI features quickly while keeping costs predictable.
शुरू करने के लिए तैयार?
कुछ ही मिनटों में Claude और GPT जोड़ें, सबसे कम कीमत पर। साइन अप करें और API key पाएं।
मुफ़्त साइन अप