AI Development

How to Build an Offline AI Chatbot Using Node.js

Artificial intelligence chatbots are becoming an important part of modern applications. From customer support assistants to coding helpers, AI chatbots can…

D
DevByteTechnical Author
Published
16 min read2 views
How to Build an Offline AI Chatbot Using Node.js

Artificial intelligence chatbots are becoming an important part of modern applications. From customer support assistants to coding helpers, AI chatbots can answer questions, explain concepts, summarize information, and automate everyday tasks.

Most AI chatbots use cloud-based APIs to generate responses. However, these services may require an internet connection and can introduce usage costs or data privacy concerns.

What if you could build your own AI chatbot that runs entirely on your computer?

In this tutorial, you will learn how to build an offline AI chatbot using Node.js and Ollama. You will run an AI model locally, connect it to a Node.js backend, and create a simple chat interface that lets you communicate with the model without relying on a cloud AI API.

This project is suitable for beginners and developers who want to explore local AI development.

What Is an Offline AI Chatbot?

An offline AI chatbot is an application that can communicate with users without requiring an internet connection for its core AI responses.

Instead of sending every message to an external AI service, the chatbot uses a language model running on your local computer.

For example, you can ask it questions such as:

  • Explain JavaScript promises.

  • Write a simple Node.js function.

  • Help me understand an error message.

  • Explain the difference between MongoDB and MySQL.

  • Generate a basic React component.

The model processes your message locally and generates a response.

However, you must download the model and required software before going offline. The quality and speed of responses depend on your chosen model and computer hardware.

Technologies We Will Use

We will build our chatbot using the following technologies.

Technology

Purpose

Node.js

Runs the backend application

Express.js

Creates the backend API

Ollama

Runs an AI model locally

Local language model

Generates chatbot responses

HTML, CSS, and JavaScript

Builds the chat interface

Fetch API

Sends messages from the frontend to the backend

Why Use Ollama?

Ollama makes it easier to download and run supported AI models on your computer.

It provides a local API that applications can use to communicate with a running model.

Instead of integrating a cloud AI provider into our Node.js application, we will send requests to Ollama running on the same computer.

Official website: https://ollama.com/

How the Offline AI Chatbot Works

Before writing the code, let's understand the application architecture.

┌──────────────────────────┐
│       Chat Interface     │
│       HTML + CSS         │
└────────────┬─────────────┘
             │
             │ User Message
             ▼
┌──────────────────────────┐
│     Node.js + Express    │
│       Backend API        │
└────────────┬─────────────┘
             │
             │ Local HTTP Request
             ▼
┌──────────────────────────┐
│          Ollama          │
│       Local AI Model     │
└────────────┬─────────────┘
             │
             │ Generated Response
             ▼
┌──────────────────────────┐
│      Chat Interface      │
│    Displays the Reply    │
└──────────────────────────┘

When a user sends a message, the frontend sends it to the Node.js backend. The backend forwards the conversation to Ollama, which runs the selected model locally.

Ollama returns the generated response, and the frontend displays it in the chat window.

Once the necessary software and model are downloaded, this workflow can run without internet access.

Step 1: Install Node.js

First, install Node.js on your computer if you haven't already.

Download it from the official website:

https://nodejs.org/

Choose a supported version appropriate for your operating system.

After installation, open your terminal and check whether Node.js and npm are available.

node -v
npm -v

If both commands display version numbers, you are ready to continue.

Step 2: Install Ollama

Download and install Ollama from:

https://ollama.com/

Follow the installation instructions for your operating system.

After installation, open your terminal and check whether the Ollama command is available.

ollama --version

If a version number appears, the command-line tool is available.

Ollama must be running when your Node.js application sends requests to it. Depending on your operating system and installation, Ollama may run as a background application.

Step 3: Download a Local AI Model

Next, download an AI model that your computer can run.

For this tutorial, we will use a small model from the Qwen family as an example:

ollama pull qwen2.5:3b

This downloads the three-billion-parameter Qwen2.5 model from Ollama's model library.

The exact model you choose should depend on your computer's available memory, processing power, and the quality you need. If this particular model is unavailable or unsuitable for your system, choose another compatible model from the Ollama library.

After downloading the model, test it:

ollama run qwen2.5:3b

Try asking a question:

Explain what Node.js is in simple words.

If the model responds, it is working.

Exit the interactive session when you finish testing.

Important: Downloading the model requires an internet connection. You can use it offline after the model has been downloaded successfully.

Step 4: Create the Node.js Project

Now let's create the backend application.

Create a project directory:

mkdir offline-ai-chatbot
cd offline-ai-chatbot

Initialize the Node.js project:

npm init -y

Install Express:

npm install express

We will use Node.js's built-in fetch() API to communicate with Ollama, so no additional HTTP client package is required in a modern supported Node.js version.

Create the following folder structure:

offline-ai-chatbot/
│
├── public/
│   ├── index.html
│   ├── style.css
│   └── script.js
│
├── server.js
└── package.json

The server.js file will contain our Express backend. The public directory will contain the frontend files.

Step 5: Build the Node.js Backend

Create a file named server.js.

Add the following code:

const express = require("express");
const path = require("path");

const app = express();

const PORT = 3000;
const OLLAMA_URL = "http://127.0.0.1:11434";
const MODEL_NAME = "qwen2.5:3b";

app.use(express.json({ limit: "1mb" }));

app.use(express.static(path.join(__dirname, "public")));

app.post("/api/chat", async (req, res) => {
  try {
    const { message, history = [] } = req.body;

    if (typeof message !== "string" || !message.trim()) {
      return res.status(400).json({
        error: "Please enter a message.",
      });
    }

    if (message.length > 4000) {
      return res.status(400).json({
        error: "Message must be 4000 characters or fewer.",
      });
    }

    if (!Array.isArray(history) || history.length > 20) {
      return res.status(400).json({
        error: "Invalid conversation history.",
      });
    }

    const validHistory = history.every(
      (item) =>
        item &&
        ["user", "assistant"].includes(item.role) &&
        typeof item.content === "string" &&
        item.content.length <= 4000
    );

    if (!validHistory) {
      return res.status(400).json({
        error: "Conversation history contains invalid messages.",
      });
    }

    const messages = [
      {
        role: "system",
        content:
          "You are a helpful AI assistant. Give clear, accurate, beginner-friendly answers.",
      },
      ...history.map((item) => ({
        role: item.role,
        content: item.content,
      })),
      {
        role: "user",
        content: message.trim(),
      },
    ];

    const response = await fetch(`${OLLAMA_URL}/api/chat`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: MODEL_NAME,
        messages,
        stream: false,
      }),
      signal: AbortSignal.timeout(120000),
    });

    if (!response.ok) {
      const details = await response.text();

      console.error("Ollama error:", details);

      return res.status(502).json({
        error:
          "The local AI model could not generate a response. Check Ollama and the model configuration.",
      });
    }

    const data = await response.json();

    const reply = data.message?.content;

    if (typeof reply !== "string") {
      return res.status(502).json({
        error: "The AI model returned an invalid response.",
      });
    }

    res.json({ reply });
  } catch (error) {
    console.error("Chat error:", error.message);

    if (error.name === "TimeoutError") {
      return res.status(504).json({
        error: "The AI model took too long to respond. Please try again.",
      });
    }

    res.status(503).json({
      error:
        "Unable to connect to the local AI model. Make sure Ollama is running.",
    });
  }
});

app.listen(PORT, "127.0.0.1", () => {
  console.log(`Offline AI chatbot running at http://127.0.0.1:${PORT}`);
});

Understanding the Backend Code

Let's understand the important parts.

1. Express server

const express = require("express");
const app = express();

Express handles incoming HTTP requests and provides the API endpoint for our chatbot.

2. Local Ollama URL

const OLLAMA_URL = "http://127.0.0.1:11434";

Ollama normally exposes its local API on port 11434.

The address 127.0.0.1 points to the same computer on which the Node.js server is running.

3. Chat endpoint

app.post("/api/chat", async (req, res) => {
  // Chatbot logic
});

This endpoint receives messages from the frontend.

4. Sending the conversation to Ollama

const response = await fetch(`${OLLAMA_URL}/api/chat`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL_NAME,
    messages,
    stream: false,
  }),
});

This sends the current message and conversation history to the local model.

The stream: false option requests a complete response rather than a stream of partial responses.

5. Returning the answer

res.json({ reply });

The backend returns the generated text to the frontend.

The application also validates incoming data and handles common connection errors. Before deploying it beyond your own computer, add appropriate authentication, rate limiting, and other security controls.

Step 6: Create the Chat Interface

Now let's build the frontend.

Inside the public directory, create index.html.

Add the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Offline AI Chatbot</title>

    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <main class="chat-container">
      <header class="chat-header">
        <div>
          <h1>Offline AI Chatbot</h1>
          <p>Powered by Node.js and Ollama</p>
        </div>

        <span class="status">Local AI</span>
      </header>

      <section
        id="chat-messages"
        class="chat-messages"
        aria-live="polite"
        aria-label="Conversation"
      >
        <div class="message assistant">
          Hello! I'm your local AI assistant. How can I help you?
        </div>
      </section>

      <form id="chat-form" class="chat-form">
        <input
          id="message-input"
          type="text"
          placeholder="Ask me anything..."
          aria-label="Your message"
          autocomplete="off"
          required
        />

        <button id="send-button" type="submit">
          Send
        </button>
      </form>

      <p class="footer-text">
        Your messages are processed by the configured local AI model.
      </p>
    </main>

    <script src="script.js"></script>
  </body>
</html>

This HTML creates a basic chat interface with a message area, an input field, and a send button.

Next, we will style it.

Step 7: Style the Chatbot

Create public/style.css.

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background: #f3f5f9;
  font-family: Arial, sans-serif;
  color: #1f2937;
}

.chat-container {
  width: 100%;
  max-width: 760px;
  height: min(700px, 90vh);
  min-height: 400px;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.08);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.chat-header h1 {
  margin: 0 0 6px;
  font-size: 22px;
}

.chat-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.status {
  padding: 7px 11px;
  background: #dcfce7;
  color: #166534;
  border-radius: 20px;
  font-size: 12px;
  white-space: nowrap;
}

.chat-messages {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 20px;
  overflow-y: auto;
}

.message {
  max-width: 85%;
  padding: 12px 15px;
  border-radius: 12px;
  line-height: 1.6;
  overflow-wrap: anywhere;
  white-space: pre-wrap;
}

.message.user {
  align-self: flex-end;
  background: #2563eb;
  color: #ffffff;
}

.message.assistant {
  align-self: flex-start;
  background: #f3f4f6;
  color: #111827;
}

.message.error {
  border: 1px solid #fecaca;
  background: #fef2f2;
  color: #991b1b;
}

.chat-form {
  display: flex;
  gap: 10px;
  padding: 16px;
  border-top: 1px solid #e5e7eb;
}

.chat-form input {
  flex: 1;
  min-width: 0;
  padding: 13px;
  border: 1px solid #d1d5db;
  border-radius: 9px;
  outline: none;
  font-size: 15px;
}

.chat-form input:focus {
  border-color: #2563eb;
}

.chat-form button {
  padding: 0 20px;
  border: none;
  border-radius: 9px;
  background: #2563eb;
  color: #ffffff;
  font-size: 15px;
  cursor: pointer;
}

.chat-form button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.footer-text {
  margin: 0;
  padding: 0 16px 14px;
  text-align: center;
  color: #6b7280;
  font-size: 12px;
}

@media (max-width: 480px) {
  body {
    padding: 8px;
  }

  .chat-container {
    height: 94vh;
  }

  .chat-header {
    padding: 15px;
  }

  .chat-messages {
    padding: 14px;
  }

  .chat-form {
    padding: 12px;
  }

  .chat-form button {
    padding: 0 14px;
  }
}

This stylesheet creates a responsive chat interface that works on desktop and mobile screens.

Step 8: Add Chat Functionality

Now we need to connect the frontend to our Node.js backend.

Create public/script.js.

const chatForm = document.getElementById("chat-form");
const messageInput = document.getElementById("message-input");
const sendButton = document.getElementById("send-button");
const chatMessages = document.getElementById("chat-messages");

const conversationHistory = [];

function addMessage(content, role, isError = false) {
  const messageElement = document.createElement("div");

  messageElement.classList.add("message", role);

  if (isError) {
    messageElement.classList.add("error");
  }

  // Use textContent to avoid interpreting model output as HTML.
  messageElement.textContent = content;

  chatMessages.appendChild(messageElement);
  chatMessages.scrollTop = chatMessages.scrollHeight;

  return messageElement;
}

chatForm.addEventListener("submit", async (event) => {
  event.preventDefault();

  const message = messageInput.value.trim();

  if (!message || sendButton.disabled) {
    return;
  }

  addMessage(message, "user");

  messageInput.value = "";
  messageInput.disabled = true;
  sendButton.disabled = true;

  const loadingMessage = addMessage("Thinking...", "assistant");

  try {
    const response = await fetch("/api/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message,
        history: conversationHistory,
      }),
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || "Unable to get a response.");
    }

    loadingMessage.textContent = data.reply;

    conversationHistory.push(
      { role: "user", content: message },
      { role: "assistant", content: data.reply }
    );

    // Keep recent messages so the request does not grow indefinitely.
    if (conversationHistory.length > 20) {
      conversationHistory.splice(
        0,
        conversationHistory.length - 20
      );
    }
  } catch (error) {
    loadingMessage.textContent = error.message;
    loadingMessage.classList.add("error");
  } finally {
    messageInput.disabled = false;
    sendButton.disabled = false;
    messageInput.focus();
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }
});

How Does the Frontend Work?

When a user submits a message, JavaScript sends it to /api/chat using the Fetch API.

The backend generates a response through Ollama and returns it as JSON.

The frontend then displays the response in the chat window.

We also maintain a short conversation history so the model can use recent messages as context.

This allows you to ask follow-up questions instead of treating every message as an unrelated conversation.

Step 9: Run the Offline AI Chatbot

Your project is now ready to test.

Make sure Ollama is installed, the model has been downloaded, and Ollama is running.

From your project directory, start the Node.js server:

node server.js

You should see a message similar to:

Offline AI chatbot running at http://127.0.0.1:3000

Open your browser and visit:

http://127.0.0.1:3000

You should see your chatbot interface.

Try asking:

What is Node.js?

Then ask a follow-up question:

Can you give me a simple example?

The chatbot should use the recent conversation history to help answer the second question.

Once you have downloaded the required software and model, you can disconnect from the internet and test the chatbot again.

If it continues to respond, your basic offline AI chatbot is working.

Step 10: Test the Chatbot Without Internet

Testing offline functionality is important because a locally running application does not automatically mean every component works without an internet connection.

Follow these steps:

  1. Download the model while connected to the internet.

  2. Start Ollama and confirm the model works.

  3. Start your Node.js application.

  4. Open the chatbot in your browser.

  5. Disconnect from the internet.

  6. Send a new message and wait for the model to respond.

If the chatbot works, the core request-and-response flow is running locally.

If it fails, check whether Ollama is still running, whether the model is available locally, and whether your application depends on any external services.

The browser, Node.js server, and Ollama communicate over your computer's loopback network. This local communication does not require an internet connection.

Common Problems and Solutions

While building your chatbot, you may encounter a few common errors.

1. Unable to Connect to Ollama

You might see an error indicating that the local AI model cannot be reached.

Possible causes:

  • Ollama is not running.

  • The local API is unavailable.

  • The configured URL or port is incorrect.

Solution:

Check whether Ollama is running, then test the local API:

curl http://127.0.0.1:11434/api/tags

If the API responds with model information, Ollama is reachable.

2. Model Not Found

You might see an error indicating that the selected model is unavailable.

Solution:

List your downloaded models:

ollama list

Make sure the model name in server.js matches the name shown in the list.

If it is missing, download the model using the appropriate ollama pull command.

3. Slow Responses

Local AI models may take time to generate responses, especially on computers with limited memory or processing power.

Possible solutions:

  • Try a smaller model.

  • Avoid sending unnecessary conversation history.

  • Close resource-intensive applications.

  • Choose a model suited to your hardware.

4. Chatbot Does Not Remember Previous Messages

The example keeps recent messages in an in-memory JavaScript array.

If you refresh the page, that history is lost.

To preserve conversations across restarts, you could add a local database such as SQLite or store conversations in files. For production use, consider how you will handle conversation privacy and data retention.

5. Browser Cannot Load the Chat Interface

Make sure the Express server is running and that your browser is visiting the correct local address.

Also verify that your HTML, CSS, and JavaScript files are located inside the public directory.

Advantages of Building an Offline AI Chatbot

Building your own offline AI chatbot has several benefits.

1. Improved Control Over Data

With a properly configured local workflow, messages can be processed on your computer instead of being sent to an external AI inference service.

2. No Per-Request Cloud AI Fees

You can avoid cloud inference charges when you use a local model. However, your computer still consumes electricity and requires sufficient hardware.

3. Offline Availability

Once the model and software are installed, the chatbot can continue working without an internet connection.

4. Customization

You can customize the system prompt, frontend, backend logic, and model selection.

5. Learning Opportunity

This project helps you understand how local language models, HTTP APIs, and backend applications work together.

Limitations of an Offline AI Chatbot

Local AI also has some limitations.

  • Hardware requirements: Your computer needs enough memory and processing power to run the selected model.

  • Model quality: Smaller models may produce less accurate answers than more capable models.

  • Knowledge limitations: A local model may not know about recent events or newly released software.

  • No automatic internet research: An offline chatbot cannot retrieve live information from the web unless you add an online data source.

  • Security considerations: A local application can still expose data if its APIs, file access, or network settings are configured insecurely.

For the best results, start with simple tasks and gradually improve your chatbot's capabilities.

Ideas to Improve Your Offline AI Chatbot

Once the basic version is working, you can extend it in several ways.

1. Add Streaming Responses

Instead of waiting for the complete answer, display generated text as it arrives.

Ollama supports streaming responses, which can make the chat experience feel faster.

2. Add Conversation Storage

Use SQLite to store previous conversations locally.

This would allow users to reopen earlier chats even after restarting the application.

3. Build a React Frontend

Replace the HTML interface with React or Next.js.

You could add reusable components, conversation lists, loading indicators, and a more advanced user interface.

4. Add Local Document Search

Integrate a retrieval-augmented generation (RAG) system so the chatbot can answer questions about your own documents.

You could use local embeddings and a vector database to retrieve relevant information before sending it to the language model.

5. Add Voice Input

Use browser speech-recognition capabilities where supported, or integrate a locally running speech-recognition model for a more fully offline experience.

6. Create a Local AI Coding Assistant

Modify the system prompt and add carefully controlled project-file access to build a coding assistant.

If you allow the chatbot to edit files or execute commands, introduce strict permission checks and require approval for sensitive actions.

Frequently Asked Questions

Can I build an AI chatbot using Node.js?

Yes. You can build a chatbot with Node.js by connecting your backend to a language model through an API. With Ollama, that API can point to a model running locally on your computer.

Can an AI chatbot work without the internet?

Yes. A chatbot can work offline if its AI model and required software are already installed locally and the application does not depend on external services for its core functionality.

Is Ollama free to use?

Ollama provides software for running supported AI models locally. Model licensing varies, so check the license of the specific model you plan to use, especially for commercial projects.

Which AI model is best for an offline chatbot?

There is no single best model for every computer. Smaller models are often easier to run, while larger models may provide stronger responses but require more resources. Test a few compatible models on your hardware.

Can I use a local AI chatbot for commercial projects?

Potentially, yes. Review the licenses of the AI model and every other component you use. Also evaluate security, data protection, performance, and the needs of your application before deploying it commercially.

Does this chatbot send my messages to the cloud?

In the example above, the Node.js backend sends prompts to Ollama at a loopback address on the same computer. This keeps the core inference workflow local, provided you use a local model and do not add external services that transmit the data.

Conclusion

Building an offline AI chatbot using Node.js is a practical way to learn local AI development.

By combining Node.js, Express, Ollama, and a compatible language model, you can create a chatbot that answers questions without relying on a cloud AI API for its core responses.

In this tutorial, we created a backend API, connected it to a local model, built a simple chat interface, and tested the application without an internet connection.

You can now extend the project with conversation storage, streaming responses, voice interaction, document search, or a React frontend.

Start with a small local model, get the basic chatbot working, and gradually add more advanced AI features as your experience grows.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘