Skip to content

Authentication

Use the headers option to pass authentication credentials with every request.

const { messages, sendMessage } = useChat({
api: "/chat",
headers: {
Authorization: `Bearer ${token}`,
},
});
const { messages, sendMessage } = useChat({
api: "/chat",
headers: {
"X-API-Key": apiKey,
},
});

If your token refreshes (e.g. via an auth provider), pass the latest value to useChat. Since headers is in the hook’s dependency array, the sendMessage function will always use the current token:

import { useAuth } from "./auth"; // your auth provider
import { useChat } from "@devscalelabs/react-sse-chat";
function Chat() {
const { token } = useAuth();
const { messages, sendMessage } = useChat({
api: "/chat",
headers: {
Authorization: `Bearer ${token}`,
},
});
// sendMessage always uses the latest token
}

For session-based authentication or multi-tenant setups, pass identifiers via the body option instead of headers:

const { messages, sendMessage } = useChat({
api: "/chat",
body: {
session_id: sessionId,
tenant_id: tenantId,
},
});

The body fields are merged into the POST body alongside message:

{
"message": "user text",
"session_id": "abc123",
"tenant_id": "org_456"
}

If your frontend and backend are on different origins, the backend must allow the custom headers via CORS:

// Hono example
import { cors } from "hono/cors";
app.use("/*", cors({
origin: "http://localhost:5173",
allowHeaders: ["Content-Type", "Authorization"],
}));
# FastAPI example
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_headers=["Content-Type", "Authorization"],
)

Without this, the browser will block the request with a CORS error.

Combine headers with onError to handle expired tokens:

const { messages, sendMessage } = useChat({
api: "/chat",
headers: {
Authorization: `Bearer ${token}`,
},
onError: (error) => {
if (error.message.includes("401")) {
// Token expired — redirect to login or refresh
refreshToken();
}
},
});

See Error Handling for more error patterns.