If you build with Node.js, Next.js, Electron or a plain web page, the official ollama npm package is the easiest way to talk to local models. It wraps Ollama’s REST API in clean async functions, with streaming, tools, images and model management built in.
This guide covers everything you need: installing it, chat and generate, streaming, running in the browser, custom hosts, stopping a reply, images, JSON, tools, embeddings, cloud models and the errors people hit most. Examples match the library’s current README (version 0.6.4 on npm).
- Install:
npm i ollama. Ollama itself must be running. - Chat:
await ollama.chat({ model, messages }), thenresponse.message.content. - Stream: add
stream: trueand loop withfor await. - Browser:
import ollama from 'ollama/browser', and allow your site’s origin withOLLAMA_ORIGINS. - Other host:
new Ollama({ host: 'http://192.168.1.50:11434' }). The JS library does not readOLLAMA_HOST.
New to Ollama? My Ollama guide covers install, models, commands and fixes in one place.
Install and First Script
Make sure Ollama is running and you have a model, for example ollama pull llama3.1. Then:
mkdir ollama-js-demo && cd ollama-js-demo
npm init -y
npm i ollama
The examples use ES modules and top-level await, so add "type": "module" to package.json (or name files .mjs). Create index.js:
import ollama from 'ollama'
const response = await ollama.chat({
model: 'llama3.1',
messages: [{ role: 'user', content: 'Why is the sky blue? Two lines.' }],
})
console.log(response.message.content)
Run it with node index.js. Any model from ollama list works. For picks, see best Ollama models.
Chat, Generate and History
chat() takes a list of messages with roles (system, user, assistant, tool). generate() takes a single prompt and returns response.response:
const g = await ollama.generate({ model: 'llama3.1', prompt: 'Write a haiku about GPUs.' })
console.log(g.response)
The model does not remember past calls, so keep the history yourself:
const messages = [{ role: 'system', content: 'You are a concise coding helper.' }]
async function ask(text) {
messages.push({ role: 'user', content: text })
const r = await ollama.chat({ model: 'llama3.1', messages })
messages.push(r.message)
return r.message.content
}
console.log(await ask('What is a closure in JavaScript?'))
console.log(await ask('Show a 3-line example.'))
Settings such as temperature and context size go in options, and keep_alive controls how long the model stays loaded:
await ollama.chat({
model: 'llama3.1',
messages,
options: { temperature: 0.2, num_ctx: 16384 },
keep_alive: '30m',
})
More on these in Ollama context length and Ollama keep_alive.
Streaming
With stream: true you get an async generator. Each part holds the next piece of text:
const stream = await ollama.chat({
model: 'llama3.1',
messages: [{ role: 'user', content: 'Explain VRAM in one paragraph.' }],
stream: true,
})
let full = ''
for await (const part of stream) {
process.stdout.write(part.message.content)
full += part.message.content
}
In a web server you can forward each part to the client with Server-Sent Events or a ReadableStream. See the Express example below.
Stop a Reply (abort)
ollama.abort() stops all streams running on that client. Any for await loop reading them throws an AbortError:
import { Ollama } from 'ollama'
const client = new Ollama() // one client per stream you may cancel
setTimeout(() => client.abort(), 3000)
try {
const stream = await client.generate({ model: 'llama3.1', prompt: 'Tell me a long story', stream: true })
for await (const part of stream) process.stdout.write(part.response)
} catch (err) {
if (err.name === 'AbortError') console.log('\n[stopped]')
else throw err
}
Because abort() cancels everything on that client, the README recommends one Ollama instance per stream when you need separate timeouts or “Stop” buttons.
Use It in the Browser
For front-end code without Node, import the browser build:
import ollama from 'ollama/browser'
const r = await ollama.chat({
model: 'llama3.1',
messages: [{ role: 'user', content: 'Hello from the browser!' }],
})
document.querySelector('#out').textContent = r.message.content
Browsers block cross-site requests unless the server allows them. Ollama allows 127.0.0.1 and 0.0.0.0 origins by default. If your page runs on another origin, such as http://localhost:5173 or a real domain, add it to OLLAMA_ORIGINS and restart Ollama:
# macOS / Linux quick test
OLLAMA_ORIGINS="http://localhost:5173" ollama serve
On Windows, set it as a user environment variable and restart the app. Never expose an Ollama server with an open origin list to the internet. See Ollama environment variables and access Ollama from another computer.
Custom Host and Headers
The default client talks to http://127.0.0.1:11434. Unlike the Python library, it does not read OLLAMA_HOST, so pass the host yourself:
import { Ollama } from 'ollama'
const ollama = new Ollama({
host: process.env.OLLAMA_HOST || 'http://127.0.0.1:11434',
headers: { 'X-App': 'my-tool' },
})
You can also pass your own fetch function, which is handy for proxies or tests.
Images
With a vision model, add images to a message. In Node you can pass file paths, and the library reads and encodes them. In the browser, pass base64 strings or a Uint8Array:
const r = await ollama.chat({
model: 'gemma3',
messages: [{ role: 'user', content: 'What is in this photo?', images: ['./photo.jpg'] }],
})
console.log(r.message.content)
Model picks and tips are in my Ollama vision models guide.
JSON, Tools and Thinking
Structured JSON. Pass a JSON schema as format. Zod 4 can build one for you:
import * as z from 'zod'
const City = z.object({ name: z.string(), country: z.string(), population: z.number() })
const r = await ollama.chat({
model: 'llama3.1',
messages: [{ role: 'user', content: 'Tell me about Tokyo.' }],
format: z.toJSONSchema(City),
options: { temperature: 0 },
})
console.log(City.parse(JSON.parse(r.message.content)))
Tools. Describe your functions with a JSON schema. The model replies with message.tool_calls, you run the function, and you send the result back with role: 'tool' and tool_name.
Thinking. Reasoning models take think: true, false, or 'low' | 'medium' | 'high' where supported. The reasoning arrives in message.thinking.
Each of these has a full guide: structured outputs, tool calling and thinking mode.
Models and Embeddings
await ollama.pull({ model: 'qwen3' })
console.log(await ollama.list()) // installed models
console.log(await ollama.ps()) // loaded models
console.log(await ollama.show({ model: 'qwen3' }))
await ollama.copy({ source: 'qwen3', destination: 'my-qwen' })
await ollama.delete({ model: 'my-qwen' })
console.log(await ollama.version())
// custom model from a base
await ollama.create({ model: 'tutor', from: 'llama3.1', system: 'You are a patient maths tutor.' })
Show download progress by streaming the pull:
const progress = await ollama.pull({ model: 'qwen3', stream: true })
for await (const p of progress) {
if (p.total) process.stdout.write(`\r${p.status} ${Math.round((p.completed / p.total) * 100)}%`)
}
Note that in JavaScript the field is from, not Python’s from_. The README also notes that create does not support the files parameter in ollama-js.
For search and RAG, embed() turns text into vectors:
const e = await ollama.embed({ model: 'embeddinggemma', input: ['first text', 'second text'] })
console.log(e.embeddings.length, e.embeddings[0].length)
More in the Ollama embeddings guide.
Cloud Models and Web Search
To run a bigger model on Ollama’s cloud through your local install, run ollama signin once, pull a cloud tag such as gpt-oss:120b-cloud, and use it like any other model. To call ollama.com directly:
const cloud = new Ollama({
host: 'https://ollama.com',
headers: { Authorization: 'Bearer ' + process.env.OLLAMA_API_KEY },
})
The same key unlocks webSearch({ query }) and webFetch({ url }), which give local models live internet results. See my Ollama web search guide. Cloud prompts leave your PC, unlike local models.
Example: A Tiny Express API
A minimal endpoint that streams replies to the browser as plain text:
import express from 'express'
import { Ollama } from 'ollama'
const app = express()
app.use(express.json())
app.post('/chat', async (req, res) => {
const client = new Ollama() // own client, so abort only affects this request
res.on('close', () => { if (!res.writableEnded) client.abort() }) // user left early
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
try {
const stream = await client.chat({ model: 'llama3.1', messages: req.body.messages, stream: true })
for await (const part of stream) res.write(part.message.content)
} catch (err) {
if (err.name !== 'AbortError') res.write('\n[error] ' + err.message)
}
res.end()
})
app.listen(3000, () => console.log('http://localhost:3000'))
Install Express with npm i express. Add rate limiting and authentication before you put anything like this online.
Troubleshooting
fetch failed / ECONNREFUSED 127.0.0.1:11434
Ollama is not running, or it runs on another host or port. Start the app or ollama serve, then open http://127.0.0.1:11434 in a browser; it should say “Ollama is running”. If the server is elsewhere, pass host.
CORS error in the browser
Your page’s origin is not allowed. Add it to OLLAMA_ORIGINS and restart Ollama, or call Ollama from your own backend instead of the browser.
“model not found”
Pull it first and use the exact name and tag from ollama list.
SyntaxError: Cannot use import statement outside a module
Add "type": "module" to package.json, or rename the file to .mjs.
Error: node:fs or node:path in a front-end bundle
You imported the Node build in browser code. Use import ollama from 'ollama/browser'.
First reply is slow
The model is loading. Keep it warm with keep_alive, and check that it runs on the GPU with ollama ps. If not, see Ollama not using GPU. Server-side details are in the Ollama logs.
FAQ
Does the library work with TypeScript?
Yes. It is written in TypeScript and ships its own types, such as ChatResponse and Message.
Can I use it with Deno or Bun?
The browser build only needs fetch, so it suits most modern runtimes. Test your runtime before relying on the Node build’s file-path image support.
Should I use the OpenAI SDK instead?
The OpenAI SDK also works against http://localhost:11434/v1. The native library adds Ollama extras such as keep_alive, model management, think levels and web search.
Is there a Python version?
Yes. See my Ollama Python library guide. The functions are the same, but Python uses keyword arguments.
Can several users share one Ollama server?
Yes. Ollama queues and runs requests in parallel within its limits. To reach it from other devices, see access Ollama from another computer.
Sources
- ollama-js on GitHub (README: install, browser import, streaming, cloud, API list, abort, custom client, create notes)
- ollama-js source (Node build reads image file paths; default host 127.0.0.1:11434)
- ollama on npm (version 0.6.4)
- Ollama docs: FAQ (OLLAMA_ORIGINS default origins)



