AI · Nov 23, 2026 · 11 min read

Ollama in Next.js 15: Local LLM Inference, Streaming & Private RAG

Step-by-step guide to running Llama 3.1 and Mistral models locally via Ollama inside Next.js 15 applications. Covers server streaming, embeddings, private RAG with LanceDB, tool calling, hardware trad

Ollama in Next.js 15: Local LLM Inference, Streaming & Private RAG

Installing Ollama and Pulling Production-Ready Models

Ollama runs LLMs on your hardware without cloud dependencies. Download the binary from the official site for macOS, Linux, or Windows. After installation, verify it works by running ollama --version. As of this writing the stable release is 0.3.9.

Pull two models that balance quality and resource usage: Llama 3.1 8B and nomic-embed-text for embeddings. Execute these commands:

ollama pull llama3.1:8b
ollama pull nomic-embed-text:latest

The 8B parameter model quantized to Q4_K_M uses roughly 5.8 GB of VRAM or unified memory. On an M2 MacBook with 16 GB it generates approximately 35-45 tokens per second. The embedding model is far smaller at 275 MB and runs on CPU without noticeable latency.

Create a custom Modelfile for domain-specific behavior. For a customer-support assistant, create a file named Modelfile.support:

FROM llama3.1:8b
SYSTEM You are a helpful support agent for an SaaS product. Answer concisely. Never hallucinate account details.

Build it with ollama create support-agent -f Modelfile.support. This custom model becomes available as support-agent and can be referenced from your Next.js code.

Creating a Next.js 15 Project with App Router and TypeScript

Initialize the project using the exact command that gives us the latest App Router defaults:

npx create-next-app@15.0.0 ollama-next --typescript --tailwind --eslint --app --yes

Navigate into the directory and install the necessary dependencies. We deliberately avoid the Vercel AI SDK to demonstrate raw streaming mechanics:

npm install langchain @langchain/community lancedb @lancedb/vectordb zod

LangChain.js 0.2 provides the abstraction layer for embeddings and retrieval while keeping the code readable. LanceDB gives us a zero-dependency local vector database that persists to disk.

Building the Ollama Chat API Route with Streaming

Create app/api/chat/route.ts. This route accepts messages from the client and streams tokens directly from Ollama using the /api/chat endpoint. The implementation uses native ReadableStream to enable incremental UI updates:

import { NextRequest } from 'next/server';

export async function POST(req: NextRequest) {
  const { messages, model = 'llama3.1:8b' } = await req.json();

  const response = await fetch('http://localhost:11434/api/chat', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model,
      messages,
      stream: true,
      options: {
        temperature: 0.7,
        top_p: 0.9,
      },
    }),
  });

  const stream = new ReadableStream({
    async start(controller) {
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { done, value } = await reader!.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (!line.trim()) continue;
          try {
            const parsed = JSON.parse(line);
            if (parsed.message?.content) {
              controller.enqueue(
                `data: ${JSON.stringify({ content: parsed.message.content })}\n\n`
              );
            }
          } catch (e) {
            console.error('Parse error', e);
          }
        }
      }
      controller.close();
    },
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
    },
  });
}

This route forwards the exact JSON format Ollama expects and converts the NDJSON response into proper SSE. The client can parse these events with the native EventSource API or a lightweight wrapper. Error handling for disconnected Ollama instances is added in production by wrapping the fetch in a try/catch and returning a 503 status with a clear JSON message.

Creating a Responsive Chat Interface with React Server Components

The frontend uses a client component for the message list and input. We keep state in React and append tokens as they arrive. Here is the core hook that consumes the stream:

'use client';
import { useState, useRef, useCallback } from 'react';

export default function Chat() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || isLoading) return;

    const userMessage = { role: 'user' as const, content: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsLoading(true);

    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages: [...messages, userMessage] }),
    });

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    let assistantMessage = { role: 'assistant' as const, content: '' };
    setMessages(prev => [...prev, assistantMessage]);

    while (true) {
      const { done, value } = await reader!.read();
      if (done) break;
      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = JSON.parse(line.slice(6));
          assistantMessage.content += data.content;
          setMessages(prev => [...prev.slice(0, -1), { ...assistantMessage }]);
        }
      }
    }
    setIsLoading(false);
  }, [input, messages, isLoading]);

  return (
    <form
      {/* message list and input field */}
    </form>
  );
}

This pattern delivers sub-300 ms perceived latency on local hardware because tokens appear immediately instead of waiting for the full completion. The code reuses the last assistant message object to trigger minimal React reconciliations.

Adding Private Retrieval-Augmented Generation (RAG)

Private RAG keeps all data on your infrastructure. We combine nomic-embed-text with LanceDB. First, install LanceDB and create an ingestion script.

Create scripts/ingest.ts:

import { LanceDB } from '@langchain/community/vectorstores/lancedb';
import { OllamaEmbeddings } from '@langchain/community/embeddings/ollama';
import * as fs from 'fs';

const embeddings = new OllamaEmbeddings({
  model: 'nomic-embed-text',
  baseUrl: 'http://localhost:11434',
});

async function ingest() {
  const docs = [
    {
      pageContent: 'Our enterprise plan includes unlimited seats and SOC2 compliance...',
      metadata: { source: 'pricing.md' },
    },
    // add more documents from your knowledge base
  ];

  const db = await LanceDB.connect('./lancedb');
  await LanceDB.fromDocuments(docs, embeddings, { tableName: 'knowledge' });
  console.log('Ingestion complete');
}

ingest();

Run this script once with ts-node scripts/ingest.ts. The resulting LanceDB folder contains the vector index and can be committed to your repository or mounted as a volume in Docker.

Implementing Context Retrieval in the Chat Route

Extend the API route to perform similarity search before calling the LLM. Add the following logic before the fetch to Ollama:

const vectorStore = await LanceDB.fromExistingTable(embeddings, {
  tableName: 'knowledge',
});

const retriever = vectorStore.asRetriever({ k: 4 });
const relevantDocs = await retriever.getRelevantDocuments(messages[messages.length - 1].content);

const context = relevantDocs.map(doc => doc.pageContent).join('\n\n');

const augmentedMessages = [
  {
    role: 'system',
    content: `Use the following context to answer accurately:\n\n${context}`,
  },
  ...messages,
];

This injects only the most relevant chunks, keeping the context window under 4k tokens for the 8B model. The trade-off is added latency of roughly 80-120 ms for the embedding lookup on typical hardware. For higher traffic you can cache recent queries using a simple in-memory LRU map with a 30-second TTL.

Tool Calling with Local Models

Ollama supports tool calling since version 0.3.0. Define tools using Zod schemas and let the model decide when to call them. Example tool for fetching account status:

const tools = [{
  type: 'function',
  function: {
    name: 'getAccountStatus',
    description: 'Retrieves current account usage and limits',
    parameters: {
      type: 'object',
      properties: {
        userId: { type: 'string' },
      },
      required: ['userId'],
    },
  },
}];

const payload = {
  model: 'support-agent',
  messages: augmentedMessages,
  tools,
  stream: true,
}; 

When the model returns a tool call in the JSON stream, parse it, execute the function locally (database query, API call, etc.), then append the result as a new message and continue the conversation. This creates powerful agents that stay within your VPC.

Hardware Requirements and Performance Trade-offs

Running 8B models comfortably requires at least 6 GB of VRAM or unified memory. A consumer GPU such as RTX 3060 12 GB can run a 70B model at Q3 quantization with acceptable speed. CPU-only inference on a 16-core Ryzen drops throughput to 4-8 tokens per second for the 8B model, which feels sluggish for chat but remains viable for batch processing or overnight report generation.

Quantization levels matter. The :q4_K_M tag offers the best quality/size ratio. The :q2_K variant reduces memory footprint by 60 % but noticeably degrades reasoning on complex tasks. Always benchmark your specific use case with a representative prompt set before choosing a quantization level for production.

Power consumption is another factor. A local setup on a Mac Mini M2 uses 25-45 W during inference versus the financial and environmental cost of repeated calls to OpenAI or Anthropic. For a startup serving 200 daily active users the electricity cost stays under $8 per month.

Production Deployment Patterns

Self-hosting Ollama in production usually means Docker. A production-ready docker-compose.yml includes Ollama, a simple reverse proxy, and persistent storage for the vector database:

services:
  ollama:
    image: ollama/ollama:latest
    ports:
      - "11434:11434"
    volumes:
      - ./ollama:/root/.ollama
      - ./lancedb:/app/lancedb
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
  nextjs:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - ollama

Use NVIDIA Container Toolkit on Linux hosts. For companies without GPU infrastructure, consider a hybrid approach where only the embedding model runs locally and the larger reasoning model is hosted on a dedicated GPU instance with private networking. Never expose the Ollama port to the public internet; always route traffic through your Next.js API routes that can enforce authentication and rate limits.

Observability and Monitoring

Instrument the API route with OpenTelemetry to record token usage, latency per model, and retrieval scores. Export metrics to Prometheus. Track the cosine similarity of retrieved documents; values consistently below 0.65 indicate that your chunking strategy or embedding model needs adjustment.

Log every prompt and completion locally during early production with strict data retention policies. This data becomes invaluable for continued fine-tuning or creating better system prompts. Tools such as LangSmith can connect to Ollama through a custom tracer, although the local nature means you must run the tracing backend on the same private network.

Security and Data Privacy Advantages

Running models locally eliminates data exfiltration risks. No prompt or company knowledge base ever leaves your infrastructure. This satisfies strict compliance regimes such as HIPAA, GDPR Article 28, and certain financial services regulations that prohibit sending customer PII to third-party processors.

Implement additional safeguards inside the Next.js middleware: validate that all requests contain a valid JWT, enforce role-based access to certain tools, and sanitize any user input before it reaches the model. Rate-limit each user to 30 requests per minute to prevent accidental or malicious exhaustion of GPU resources.

Scaling Considerations for Growing User Bases

Single-node Ollama works well up to approximately 40 concurrent users on a single high-end GPU. Beyond that, distribute load across multiple nodes using a simple round-robin load balancer in front of several Ollama containers. Each node can run a different specialized model (one for chat, one for embeddings, one for classification).

Alternatively, explore Ollama's experimental cluster mode or use LiteLLM as a unified gateway that can route requests to the least busy GPU instance. The vector database can be scaled independently by switching from LanceDB to Qdrant or Weaviate when the dataset exceeds 500 000 chunks.

Keep model updates controlled. Create a CI pipeline that pulls new Ollama base models, runs an evaluation suite against 50 golden questions, and only promotes the new model after accuracy stays above 92 %. This prevents silent regressions that cloud providers sometimes introduce with silent updates.

Common Pitfalls and How to Avoid Them

  • Context overflow: Always count tokens before sending. The Llama 3.1 tokenizer is available via the tiktoken package; reject or summarize requests that would exceed 75 % of the model context.
  • Non-deterministic output: Set temperature: 0 for tasks that require factual consistency such as JSON mode or classification.
  • Embedding drift: Use the exact same embedding model for both ingestion and retrieval. Mixing nomic-embed-text with snowflake-arctic-embed creates meaningless similarity scores.
  • Memory leaks in long-lived containers: Restart the Ollama container daily during low-traffic windows. The current version occasionally retains GPU memory after heavy usage.

Putting It All Together: A Complete Customer Support Assistant

Combine the streaming route, RAG retrieval, and tool calling into one cohesive system. The final architecture looks like this:

  1. Next.js client sends message
  2. API route authenticates the user
  3. Retrieve relevant private documentation using LanceDB + nomic embeddings
  4. Augment the system prompt with context and available tools
  5. Stream response from Ollama, parsing tool calls when they appear
  6. Execute tools (database lookup, ticket creation) and feed results back
  7. Return final answer to the user with sources cited from the retrieved documents

This pattern has been used successfully in internal tools at multiple startups to reduce support ticket volume by letting users self-serve accurate answers drawn from private wikis, past tickets, and product documentation without any data leaving the company network.

The complete source code for the example application, including the ingestion script, typed API contracts, and Docker setup, is available in the companion repository linked at the end of this article. You can swap Llama 3.1 for any model Ollama supports, including fine-tuned variants created with LoRA adapters that run efficiently alongside the base model.

By owning the entire inference stack you gain predictability, cost control, and data sovereignty that proprietary APIs cannot match. The techniques shown here scale from a developer laptop to multi-GPU production clusters while remaining entirely within your infrastructure.

Keep reading

Related Articles