📄 ai-sdk/docs/ai-sdk-rsc/saving-and-restoring-states

File: saving-and-restoring-states.md | Updated: 11/15/2025

Source: https://ai-sdk.dev/docs/ai-sdk-rsc/saving-and-restoring-states

AI SDK

Menu

v5 (Latest)

AI SDK 5.x

AI SDK by Vercel

AI SDK 6 Beta

Foundations

Overview

Providers and Models

Prompts

Tools

Streaming

Getting Started

Navigating the Library

Next.js App Router

Next.js Pages Router

Svelte

Vue.js (Nuxt)

Node.js

Expo

Agents

Agents

Building Agents

Workflow Patterns

Loop Control

AI SDK Core

Overview

Generating Text

Generating Structured Data

Tool Calling

Model Context Protocol (MCP) Tools

Prompt Engineering

Settings

Embeddings

Image Generation

Transcription

Speech

Language Model Middleware

Provider & Model Management

Error Handling

Testing

Telemetry

AI SDK UI

Overview

Chatbot

Chatbot Message Persistence

Chatbot Resume Streams

Chatbot Tool Usage

Generative User Interfaces

Completion

Object Generation

Streaming Custom Data

Error Handling

Transport

Reading UIMessage Streams

Message Metadata

Stream Protocols

AI SDK RSC

Overview

Streaming React Components

Managing Generative UI State

Saving and Restoring States

Multistep Interfaces

Streaming Values

Handling Loading State

Error Handling

Handling Authentication

Migrating from RSC to UI

Advanced

Reference

AI SDK Core

AI SDK UI

AI SDK RSC

Stream Helpers

AI SDK Errors

Migration Guides

Troubleshooting

Copy markdown

Saving and Restoring States

==========================================================================================================================

AI SDK RSC is currently experimental. We recommend using AI SDK UI for production. For guidance on migrating from RSC to UI, see our migration guide .

AI SDK RSC provides convenient methods for saving and restoring AI and UI state. This is useful for saving the state of your application after every model generation, and restoring it when the user revisits the generations.

AI State


Saving AI state

The AI state can be saved using the onSetAIState callback, which gets called whenever the AI state is updated. In the following example, you save the chat history to a database whenever the generation is marked as done.

app/ai.ts

export const AI = createAI<ServerMessage[], ClientMessage[]>({  actions: {    continueConversation,  },  onSetAIState: async ({ state, done }) => {    'use server';
    if (done) {      saveChatToDB(state);    }  },});

Restoring AI state

The AI state can be restored using the initialAIState prop passed to the context provider created by the createAI function. In the following example, you restore the chat history from a database when the component is mounted.

import { ReactNode } from 'react';import { AI } from './ai';
export default async function RootLayout({  children,}: Readonly<{ children: ReactNode }>) {  const chat = await loadChatFromDB();
  return (    <html lang="en">      <body>        <AI initialAIState={chat}>{children}</AI>      </body>    </html>  );}

UI State


Saving UI state

The UI state cannot be saved directly, since the contents aren't yet serializable. Instead, you can use the AI state as proxy to store details about the UI state and use it to restore the UI state when needed.

Restoring UI state

The UI state can be restored using the AI state as a proxy. In the following example, you restore the chat history from the AI state when the component is mounted. You use the onGetUIState callback to listen for SSR events and restore the UI state.

app/ai.ts

export const AI = createAI<ServerMessage[], ClientMessage[]>({  actions: {    continueConversation,  },  onGetUIState: async () => {    'use server';
    const historyFromDB: ServerMessage[] = await loadChatFromDB();    const historyFromApp: ServerMessage[] = getAIState();
    // If the history from the database is different from the    // history in the app, they're not in sync so return the UIState    // based on the history from the database
    if (historyFromDB.length !== historyFromApp.length) {      return historyFromDB.map(({ role, content }) => ({        id: generateId(),        role,        display:          role === 'function' ? (            <Component {...JSON.parse(content)} />          ) : (            content          ),      }));    }  },});

To learn more, check out this example that persists and restores states in your Next.js application.


Next, you will learn how you can use @ai-sdk/rsc functions like useActions and useUIState to create interactive, multistep interfaces.

On this page

Saving and Restoring States

AI State

Saving AI state

Restoring AI state

UI State

Saving UI state

Restoring UI state

Deploy and Scale AI Apps with Vercel.

Vercel delivers the infrastructure and developer experience you need to ship reliable AI-powered applications at scale.

Trusted by industry leaders:

  • OpenAI
  • Photoroom
  • leonardo-ai Logoleonardo-ai Logo
  • zapier Logozapier Logo

Talk to an expert