Persisting Conversation History

Save chat messages in MySQL so conversations can resume with their history after a server restart.

🎯 Introduction

Earlier, the history array kept multi-turn messages in Node.js memory. Restarting the service lost those chat records.

This article solves that problem with MySQL, which you have already learned: save user and assistant messages, then load the relevant session's history and pass it to Chat Completions for the next question. We will build a separate Express API step by step and verify that conversations resume after a restart.


🧱 Separate Chat Records by Session

A user may discuss two topics at once, so messages must stay separate. We distinguish them with a session ID (sessionId):

Session ID (illustrative)rolecontent
AuserI am learning Vue 3
AassistantWhat would you like to learn first?
AuserStart with reactivity
BuserWhat should I do if my Node.js service fails to start?

We therefore need two tables: sessions stores sessions, and messages stores messages, with session_id identifying each message's session. A and B are illustrative; the implementation uses UUIDs.

Save both user questions and assistant answers. If the assistant says "Common reactivity APIs include ref() and reactive()" and the user asks "How do I use the first one?", the model needs the preceding answer to know that "the first one" means ref().


🛠 Save and Read Messages with MySQL

1. Create Tables and Configure the Project

Run this in your existing MySQL instance:

CREATE DATABASE IF NOT EXISTS ai_chat CHARACTER SET utf8mb4;
USE ai_chat;

CREATE TABLE IF NOT EXISTS sessions (
    id CHAR(36) PRIMARY KEY,
    title VARCHAR(100) NOT NULL
);

CREATE TABLE IF NOT EXISTS messages (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    session_id CHAR(36) NOT NULL,
    role VARCHAR(20) NOT NULL,
    content TEXT NOT NULL,
    FOREIGN KEY (session_id) REFERENCES sessions(id)
);

messages.session_id references sessions.id, so each session query reads only its own messages. messages.id determines the storage order in this example.

Create an ai-chat project directory, use Node.js 24.x, and install the required dependencies:

npm init -y
npm install --save-exact express@5.1.0 openai@7.62.0 mysql2@3.24.6

Create .env with your actual settings:

AI_API_KEY=your-aihubmix-api-key
AI_BASE_URL=https://aihubmix.com/v1
AI_MODEL=gpt-4o-mini

DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your-mysql-password
DB_NAME=ai_chat

2. Create Sessions

Create 09.store.mjs. First connect to the database and implement session creation and existence checks:

import mysql from "mysql2/promise";
import { randomUUID } from "node:crypto";

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT),
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    connectionLimit: 5
});

export async function createSession() {
    const id = randomUUID();
    await pool.execute(
        "INSERT INTO sessions (id, title) VALUES (?, ?)",
        [id, "New conversation"]
    );
    return id;
}

export async function hasSession(id) {
    const [rows] = await pool.execute(
        "SELECT id FROM sessions WHERE id = ?",
        [id]
    );
    return rows.length > 0;
}

createSession() inserts a record into sessions and returns the generated ID. hasSession() prevents saving or reading messages for nonexistent sessions.

3. Save and Read Messages

Append two functions to the same 09.store.mjs file:

export async function addMessage(sessionId, role, content) {
    await pool.execute(
        "INSERT INTO messages (session_id, role, content) VALUES (?, ?, ?)",
        [sessionId, role, content]
    );
}

export async function getMessages(sessionId) {
    const [rows] = await pool.execute(
        "SELECT role, content FROM messages WHERE session_id = ? ORDER BY id ASC",
        [sessionId]
    );
    return rows;
}

addMessage() saves one message at a time; getMessages() retrieves the current session's messages in order. The query returns only role and content, the fields needed by Chat Completions for the plain-text conversations in this article. SQL ? placeholders bind parameters instead of concatenating user input.


🛠 Build the Chat API Step by Step

Create 09.server.mjs below. Append each code block to the same file; do not duplicate code you have already added.

1. Initialize Express and the Model Client

Start 09.server.mjs with:

import express from "express";
import OpenAI from "openai";
import { createSession, hasSession, addMessage, getMessages } from "./09.store.mjs";

const app = express();
const client = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_BASE_URL
});

app.use(express.json({ limit: "16kb" }));

Database operations come from the 09.store.mjs you just wrote. Next, use them in the appropriate endpoints.

2. Add a Session Creation Endpoint

Append to 09.server.mjs:

app.post("/api/sessions", async (req, res) => {
    try {
        const id = await createSession();
        res.status(201).json({ id });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: "Failed to create session" });
    }
});

The browser first calls POST /api/sessions to obtain an id. Every subsequent question in that session carries the same sessionId, allowing the backend to find its history.

3. Handle the Model's Streaming Answer

The chat endpoint forwards text chunks to the browser, but must not save each chunk as a separate database message. Add a helper that sends each chunk while assembling one assistant answer, then saves it after the stream ends.

Append to 09.server.mjs:

async function streamReply(sessionId, history, res, signal) {
    const stream = await client.chat.completions.create({
        model: process.env.AI_MODEL,
        messages: history,
        stream: true
    }, { signal });

    res.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");
    res.setHeader("Cache-Control", "no-cache, no-transform");
    res.setHeader("X-Accel-Buffering", "no");

    let answer = "";
    let finishReason = null;

    for await (const chunk of stream) {
        const choice = chunk.choices[0];
        if (!choice) continue;

        const text = choice.delta?.content;
        if (text) {
            answer += text;
            res.write(JSON.stringify({ type: "delta", text }) + "\n");
        }
        if (choice.finish_reason != null) {
            finishReason = choice.finish_reason;
        }
    }

    if (finishReason === null) {
        throw new Error("The model stream did not end normally");
    }

    if (answer) {
        await addMessage(sessionId, "assistant", answer);
    }
    res.write(JSON.stringify({ type: "done", finishReason }) + "\n");
    res.end();
}

This reuses the streaming logic from earlier. The additions are answer += text and the final addMessage(): the former collects this turn's answer; the latter saves it as one assistant message. If generation ends at a length limit, the saved content is what actually arrived and may be incomplete.

4. Receive Questions, Read History, and Call the Model

Add POST /api/chat. After receiving sessionId and the user's question, confirm the session exists, save the question in MySQL, and then read its history for streamReply().

Append to 09.server.mjs:

app.post("/api/chat", async (req, res) => {
    const { sessionId, message } = req.body ?? {};

    if (typeof sessionId !== "string" || !sessionId.trim()) {
        return res.status(400).json({ error: "Session ID is required" });
    }
    if (typeof message !== "string" || !message.trim() || message.length > 2000) {
        return res.status(400).json({ error: "Enter a message of 1–2000 characters" });
    }

    const controller = new AbortController();
    res.on("close", () => {
        if (!res.writableEnded) controller.abort();
    });

    try {
        if (!await hasSession(sessionId)) {
            return res.status(404).json({ error: "Session not found" });
        }

        await addMessage(sessionId, "user", message);
        const history = await getMessages(sessionId);
        await streamReply(sessionId, history, res, controller.signal);
    } catch (error) {
        if (controller.signal.aborted || res.destroyed) return;
        console.error(error);

        if (!res.headersSent) {
            res.status(502).json({ error: "Chat request failed" });
        } else {
            res.write(JSON.stringify({ type: "error", message: "Generation interrupted" }) + "\n");
            res.end();
        }
    }
});

The order matters: save the current question before querying history. If one exchange already exists and the user asks "Start with reactivity", the query returns both that earlier exchange and the new question. No extra append is necessary.

The model does not query MySQL itself. streamReply() passes the history returned by getMessages() to Chat Completions so the model can reference it. If the request fails, the saved user message may remain in the database. Retry handling is outside this example's scope.

5. Add an Endpoint for Reading History

Finally, let the page retrieve chat records by session ID. Append to 09.server.mjs:

app.get("/api/sessions/:id/messages", async (req, res) => {
    try {
        if (!await hasSession(req.params.id)) {
            return res.status(404).json({ error: "Session not found" });
        }
        res.json({ messages: await getMessages(req.params.id) });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: "Failed to read history" });
    }
});

app.listen(3000, "127.0.0.1", () => {
    console.log("http://127.0.0.1:3000");
});

09.server.mjs is now complete. It can create sessions, answer questions within a session, and read saved messages. There is no need to repeat all the earlier code in a combined listing.

MySQL can retain the complete history long term, but applications do not necessarily need to pass all of it to the model on every request. For long conversations, use the context management techniques covered earlier to control token costs.

🧪 Verify Conversation Recovery After a Restart

Ensure MySQL is running and the table creation SQL has executed, then start the service from the project root:

node --env-file=.env 09.server.mjs

If your model requests require a local proxy, use:

HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 09.server.mjs

Step 1: Create a session.

curl -s -X POST http://127.0.0.1:3000/api/sessions

This returns {"id":"..."}. Copy the actual ID and replace your-session-id in the following commands.

Step 2: Ask two questions with the same session ID.

curl -N -X POST http://127.0.0.1:3000/api/chat \
    -H 'Content-Type: application/json' \
    -d '{"sessionId":"your-session-id","message":"I am learning Vue 3"}'
curl -N -X POST http://127.0.0.1:3000/api/chat \
    -H 'Content-Type: application/json' \
    -d '{"sessionId":"your-session-id","message":"What did I say I was learning?"}'

Step 3: View the saved history.

curl http://127.0.0.1:3000/api/sessions/your-session-id/messages

If both model calls succeed, the response resembles this (assistant answers are illustrative):

{
    "messages": [
        { "role": "user", "content": "I am learning Vue 3" },
        { "role": "assistant", "content": "Great, we can start with Vue 3." },
        { "role": "user", "content": "What did I say I was learning?" },
        { "role": "assistant", "content": "You said you were learning Vue 3." }
    ]
}

Step 4: Stop and restart the service, then query the same session ID again. If the messages remain, the data survived the Node.js process ending. Further questions can also use this history.

This example is for local learning. A session ID is not a login credential. Before public deployment, verify session ownership and limit model usage.

❓ Knowledge Check

Q: Why not store the entire history array as one database record?

That can work for simple chat records, but every new message requires updating the entire dataset. Storing messages individually lets you append records directly and query them conveniently by session.


🧪 Exercise

Create separate Vue and Node.js sessions and ask questions in each. Restart the service, query the history using both session IDs, and continue either conversation.

Success criteria: The sessions' records remain separate, old messages remain readable after a restart, and the model references only the current session's history.


🎉 You have saved, retrieved, and restored conversation records, allowing the model to continue a conversation after the service restarts.