@21st-sdk/nextjs
v0.0.11
Published
Next.js integration for 21st Agents chat
Readme
@21st-sdk/nextjs
Next.js integration for 21st Agents AI agent chat. Provides a server-side token handler so your API key never reaches the client.
Install
npm install @21st-sdk/nextjs @21st-sdk/react ai @ai-sdk/reactQuick Start
1. Set your API key
# .env.local
API_KEY_21ST=an_sk_your_key_hereGet your API key from the API keys page.
2. Create the token route (one line)
// app/api/agent/token/route.ts
import { createTokenHandler } from "@21st-sdk/nextjs/server"
export const POST = createTokenHandler({
apiKey: process.env.API_KEY_21ST!,
})3. Use in your page
// app/page.tsx
"use client"
import { useChat } from "@ai-sdk/react"
import { AgentChat, createAgentChat } from "@21st-sdk/nextjs"
import "@21st-sdk/react/styles.css"
import { useMemo } from "react"
export default function Chat() {
const chat = useMemo(
() => createAgentChat({
agent: "your-agent-slug",
tokenUrl: "/api/agent/token",
}),
[],
)
const { messages, sendMessage, status, stop, error } = useChat({ chat })
return (
<AgentChat
messages={messages}
onSend={(msg) =>
sendMessage({ parts: [{ type: "text", text: msg.content }] })
}
status={status}
onStop={stop}
error={error}
/>
)
}That's it. Your an_sk_ API key stays on the server. The client only receives short-lived JWTs.
How It Works
Browser Your Next.js Server Relay
| | |
|-- POST /api/agent/token ------>| |
| |-- POST /v1/tokens -------->|
| | (with an_sk_ key) |
| |<-- { token, expiresAt } ---|
|<-- { token, expiresAt } ------| |
| |
|-- POST /v1/chat/:agent ------(with short-lived JWT)------->|
|<-- streaming response -----(SSE)---------------------------|License
MIT
