Deployment And Auth
Purpose and Scope
Deployment and auth are not separate afterthoughts in an AI SDK application. Once a model call, tool call, or streamed UI is exposed through a web route or Server Action, it becomes part of the application's security boundary. This page explains how the documented AI SDK primitives should be placed behind authentication checks when they run in deployed applications, especially Next.js route handlers, AI SDK UI chatbots, and AI SDK RSC Server Actions. The goal is to help you decide where to authorize a user before returning model output, tool results, generated UI, or structured data.
Sources: content/docs/05-ai-sdk-rsc/09-authentication.mdx, content/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx
The core rule is simple: authenticate at the application boundary before you let the model or tools touch user-specific data. AI SDK Core standardizes model calls through functions such as generateText and streamText, and those functions can return text, structured output, files, sources, tool calls, tool results, usage, warnings, and step details. That broad result surface is useful for building agents, but it also means an unauthorized request can reveal more than plain text if the route is not protected. Treat every deployed model endpoint as a public API until your code proves otherwise.
Sources: content/docs/03-ai-sdk-core/01-overview.mdx, content/docs/03-ai-sdk-core/05-generating-text.mdx
Relevant Source Files
- content/docs/05-ai-sdk-rsc/09-authentication.mdx - Defines the RSC authentication warning and shows a Server Action that validates a token from cookies before returning streamable UI.
- content/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx - Shows the deployed chatbot route pattern, including message ingestion, streamText, server-side tools, client-side tool outputs, and maxDuration for streaming responses.
- content/docs/03-ai-sdk-core/01-overview.mdx - Establishes AI SDK Core as the standardized layer for text generation, streaming, structured output, and tool usage.
- content/docs/03-ai-sdk-core/05-generating-text.mdx - Documents generateText and streamText result surfaces, including tool calls, tool results, files, sources, usage, warnings, and step metadata.
- content/docs/03-ai-sdk-core/10-generating-structured-data.mdx - Explains schema-validated structured output through the output property on generateText and streamText and notes stream error handling behavior.
- content/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx - Defines tool description, inputSchema, execute, strict mode, toolsContext, and experimental sandbox behavior for tool-enabled model calls.
Auth Boundaries in Deployed AI SDK Apps
In AI SDK RSC, the documented boundary is explicit: the RSC API uses Next.js Server Actions to power streaming values and UI from the server, and Server Actions are public, unprotected endpoints. The authentication page instructs developers to treat Server Actions like public-facing API endpoints and to ensure that the user is authorized before returning any data. The example reads a token from cookies, validates it, and returns an error object instead of a streamable display when validation fails. Only after authorization does it create and complete streamable UI.
Sources: content/docs/05-ai-sdk-rsc/09-authentication.mdx
'use server';
import { cookies } from 'next/headers';
import { createStreamableUI } from '@ai-sdk/rsc';
import { validateToken } from '../utils/auth';
export const getWeather = async () => {
const token = cookies().get('token');
if (!token || !validateToken(token)) {
return { error: 'This action requires authentication' };
}
const streamableDisplay = createStreamableUI(null);
streamableDisplay.update(<Skeleton />);
streamableDisplay.done(<Weather />);
return { display: streamableDisplay.value };
};For AI SDK UI, the deployed boundary is usually an API route that receives UI messages, converts them to model messages, and starts streamText. The chatbot tool usage guide describes a full loop: the user sends a message, the API route calls the model, tool calls are forwarded to the client, server-side tools run through execute, client-side tools return results through addToolOutput, and sendAutomaticallyWhen can trigger another iteration. That loop should be considered an authenticated workflow, not only a model call, because every iteration can produce new tool requests and new results.
Sources: content/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx
System-to-Code Mapping
The AI SDK separates the transport boundary from the model primitive. A Next.js POST route owns request parsing, authentication, authorization, and response policy. AI SDK Core owns the model call through generateText or streamText. AI SDK UI owns the message stream protocol and client integration. Tools sit inside the model call but may execute on the server, execute on the client, or wait for user interaction. This separation is what lets the same core primitives power scripts, chatbots, RSC streams, and agent-like tool loops while still allowing each deployed app to enforce its own auth model.
Sources: content/docs/03-ai-sdk-core/01-overview.mdx, content/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx, content/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx
| Concern | Public primitive | Auth implication |
|---|---|---|
| RSC streaming UI | createStreamableUI inside a Server Action | Validate cookies or session before returning streamable values. |
| Chat API route | POST route calling streamText | Authenticate before converting messages and starting the stream. |
| Server-side tool | tool with execute | Authorize the specific action and data access inside or before execute. |
| Client-side tool | tool call handled by onToolCall and addToolOutput | Confirm user intent and validate returned output before continuing. |
| Structured output | output with Output.object or other schema mode | Schema validation shapes data, but it is not an authorization check. |
API Components and Runtime Behavior
AI SDK Core functions are the model execution primitives behind these deployed surfaces. generateText is documented for non-interactive use cases and agents that use tools, while streamText is documented for interactive chatbots and content streaming. The result object can include final text, generated content across steps, files, provider sources, tool calls, tool results, finish reasons, usage, warnings, and step metadata. In a deployed route, those fields should be treated as response data that may need filtering, logging policy, or suppression depending on the authenticated user's permissions.
Sources: content/docs/03-ai-sdk-core/05-generating-text.mdx
Structured output helps enforce shape, not identity. The structured data guide explains that generateText and streamText use the output property with schemas from Zod, Valibot, or JSON Schema, and that the generated data is validated against the requested structure. This is important for deployment because validated JSON can be safer to consume than arbitrary text, but it does not decide whether the caller may receive the data. If structured output is generated from private documents, tenant data, or privileged tool results, the route still needs an auth check before generation and before returning results.
Sources: content/docs/03-ai-sdk-core/10-generating-structured-data.mdx
Tools require an additional authorization mindset because they can perform actions, not just produce language. The tool calling guide defines tools by description, inputSchema, optional execute, and optional strict mode. A missing execute means the tool call can be forwarded elsewhere, such as to a client or queue, rather than executed in the same process. A present execute means server code may run during the model loop. Use inputSchema for validation, but place permission checks around the action itself, especially for tools that read user data, mutate state, use external APIs, or run sandboxed commands.
Sources: content/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx
Deployment Flow
A secure deployed chatbot route should follow a predictable sequence. First, parse the request only enough to identify the caller and requested operation. Second, validate the session, token, or other credential at the route boundary. Third, authorize the user for the conversation, resources, and tool capabilities requested by the route. Fourth, convert UI messages to model messages and call streamText. Fifth, execute only the server-side tools that the user is permitted to use. Finally, return the AI SDK stream response and make sure client-submitted tool outputs are accepted only for the conversation and tool call they belong to.
Sources: content/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx, content/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx
import {
convertToModelMessages,
createUIMessageStreamResponse,
streamText,
} from 'ai';
export const maxDuration = 30;
export async function POST(req: Request) {
const session = await authenticate(req);
if (!session) {
return new Response('Unauthorized', { status: 401 });
}
const { messages } = await req.json();
const result = streamText({
model: modelFor(session),
messages: await convertToModelMessages(messages),
tools: authorizedToolsFor(session),
});
return createUIMessageStreamResponse({
stream: result.toUIMessageStream(),
});
}The maxDuration export shown in the chatbot route example is a deployment signal as well as a framework detail. Streaming model calls and tool loops can run longer than ordinary request handlers, so the route needs an explicit runtime expectation. The AI SDK docs show streaming responses up to thirty seconds in the example route. Your application should combine that timeout policy with auth policy: reject unauthorized requests before opening a stream, and avoid starting long-running model or tool work for callers who cannot receive the result.
Sources: content/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx
Compact Reference
| Name | Where it appears | Deployment and auth meaning |
|---|---|---|
| generateText | AI SDK Core text generation | Use for server-side generation after authorization; inspect result fields before returning or logging. |
| streamText | AI SDK Core streaming and chatbot routes | Authenticate before starting the stream because errors and data may be delivered as stream parts. |
| output | Structured output on generateText and streamText | Validates generated shape; does not replace session or permission checks. |
| tools | generateText and streamText option | Register only tools the caller may use in the current request. |
| execute | Tool implementation callback | Perform action-level authorization for server-side side effects or private reads. |
| addToolOutput | UI tool-result submission | Accept client tool results only in the correct authenticated chat context. |
| createStreamableUI | AI SDK RSC helper | Return streamable UI only after Server Action authorization succeeds. |
| maxDuration | Route export in UI example | Budget streaming work for deployment, after rejecting unauthorized requests. |
Next Steps
When you implement deployment auth, start with the boundary closest to the network: a route handler, Server Action, or server function. Add the credential check before streamText, generateText, createStreamableUI, or any tool execution. Then review each tool as a separate capability with its own input validation, authorization rules, and result policy. For UI chatbots, also review client-side tool outputs and confirmation flows, because they can continue the model loop. For deeper implementation details, continue with the pages on chatbot tool usage, tools and tool calling, stream protocol transport metadata, sandbox, and agent workflow reference.