Type-safe JSON-RPC and XML-RPC client for Odoo — works with Node.js, Next.js, React and any modern JS runtime.
- Dual protocol — JSON-RPC (
/web/dataset/call_kw) and XML-RPC (/xmlrpc/2/object) in one package - Full TypeScript — typed domains, field values, ORM options, and error classes
- Auth strategies — session/password auth or API key (Odoo 14+)
- Retry & timeout — reads are retried with exponential backoff on network failures and timeouts; errors returned by Odoo and calls that change data are never retried
- Async pagination —
orm.paginate()async generator for bulk record processing - Zero dependencies — uses native
fetch(Node 18+, all browsers) - Login with Odoo — OpenID Connect with PKCE through
OdooLogin, returning an Odoo session - Typed errors —
OdooAuthenticationError,OdooAccessError,OdooValidationError, etc.
OdooConnect is the single entry point. It wires together three layers:
Services sit in the middle and own all business logic — AuthService handles the three auth paths (session, XML-RPC password, API key), OrmService translates your method calls into the correct RPC payloads and handles version-specific API differences between Odoo 14 and 19.
Clients at the bottom do exactly one thing: fire an HTTP request and deserialise the response. JsonRpcClient owns the session cookie across calls in Node.js environments. XmlRpcClient includes a zero-dependency XML serialiser/deserialiser.
Shared infra (retry, typed errors) is used by both clients. Errors returned by Odoo are never retried — they surface immediately. Network failures and timeouts back off exponentially, for reads only: a call that may change data is sent once, so a lost response never applies it twice.
The protocol is hot-swappable — set protocol: 'xmlrpc' and the same ORM API routes through XML-RPC. The service layer never knows the difference.
- Node.js ≥ 18 (for native
fetchandDOMParser) - Odoo 14, 15, 16, 17, 18, 19
npm install @vvhybe/odoo-client
# or
pnpm add @vvhybe/odoo-client
# or
yarn add @vvhybe/odoo-clientFrom GitHub Packages. Each release is also published to GitHub Packages. npmjs.com needs no setup; GitHub Packages needs an .npmrc next to your package.json and a personal access token (classic) with the read:packages scope:
@vvhybe:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}Then npm install @vvhybe/odoo-client as above, with GITHUB_TOKEN set in your environment.
import { OdooConnect } from '@vvhybe/odoo-client';
// Option A: factory method (authenticates immediately)
const odoo = await OdooConnect.connect({
url: 'https://mycompany.odoo.com',
db: 'mydb',
username: 'admin@example.com',
password: 'secret',
});
// Option B: manual
const odoo = new OdooConnect({ url, db, username, password });
await odoo.authenticate();
// CRUD
const partners = await odoo.orm.searchRead('res.partner', [['is_company', '=', true]], {
fields: ['name', 'email', 'phone'],
limit: 50,
order: 'name asc',
});
const id = await odoo.orm.create('res.partner', { name: 'Acme Corp', is_company: true });
await odoo.orm.write('res.partner', [id], { phone: '+1 555 0100' });
await odoo.orm.unlink('res.partner', [id]);interface OdooConfig {
url: string; // Base URL — e.g. https://mycompany.odoo.com
db: string; // Database name
username?: string; // Required for password/apiKey auth
password?: string; // Required for password auth
apiKey?: string; // Alternative to password (Odoo 14+)
protocol?: 'jsonrpc' | 'xmlrpc'; // Default: 'jsonrpc'
timeout?: number; // ms. Default: 30000
retries?: number; // Retries of a read after a network failure or timeout. Default: 3
retryDelay?: number; // Base backoff ms. Default: 500
context?: OdooContext; // Merged into every RPC call
session?: OdooSession; // Start logged in with an existing session (JSON-RPC only; needs sessionId)
}| Method | Description |
|---|---|
new OdooConnect(config) |
Create instance (does not authenticate) |
OdooConnect.connect(config) |
Create + authenticate in one step |
odoo.authenticate() |
Authenticate and return the session |
odoo.getSession() |
Returns current OdooSession or null |
odoo.getSessionId() |
Returns the session id the client holds (so an app can store it), or null |
odoo.disconnect() |
Clears the session |
odoo.orm |
OrmService — see below |
odoo.auth |
AuthService — low-level auth access |
odoo.jsonRpc |
JsonRpcClient — direct RPC access |
odoo.xmlRpc |
XmlRpcClient — direct RPC access |
// Search + read in one call
orm.searchRead<T>(model, domain?, options?): Promise<T[]>
// Read by ids
orm.read<T>(model, ids, options?): Promise<T[]>
// Read one record — throws OdooNotFoundError if missing
orm.readOne<T>(model, id, options?): Promise<T>
// Search and return ids
orm.search(model, domain?, options?): Promise<number[]>
// Count matching records
orm.searchCount(model, domain?, context?): Promise<number>
// Autocomplete helper: returns [(id, display_name), ...]
orm.nameSearch(model, name, domain?, limit?, context?): Promise<[number, string][]>
// Async generator — yields pages of records
orm.paginate<T>(model, domain?, options?): AsyncGenerator<T[]>// Create one record — returns new id
orm.create(model, values, context?): Promise<number>
// Create multiple records — returns list of ids
orm.createMany(model, valuesList, context?): Promise<number[]>
// Update records
orm.write(model, ids, values, context?): Promise<boolean>
// Delete records
orm.unlink(model, ids, context?): Promise<boolean>// Get field definitions
orm.fieldsGet(model, attributes?, context?): Promise<OdooFieldsGet>
// Call any model method
orm.callMethod<T>(model, method, args?, kwargs?, context?): Promise<T>Domains follow Odoo's standard domain format:
import type { OdooDomain } from '@vvhybe/odoo-client';
const domain: OdooDomain = [
['is_company', '=', true],
['country_id.code', '=', 'MA'],
];
// Logical operators
const complex: OdooDomain = [
'|',
['email', 'ilike', '@gmail.com'],
['email', 'ilike', '@yahoo.com'],
];Supported leaf operators: =, !=, >, >=, <, <=, like, ilike, not like, not ilike, in, not in, child_of, parent_of, =like, =ilike.
import type { TypedOdooRecord } from '@vvhybe/odoo-client';
interface ResPartner {
name: string;
email: string;
phone: string | false;
is_company: boolean;
country_id: [number, string] | false;
}
const partners = await odoo.orm.searchRead<TypedOdooRecord<ResPartner>>(
'res.partner',
[['is_company', '=', true]],
{ fields: ['name', 'email', 'phone', 'country_id'] },
);
// partners[0].name is string ✓
// partners[0].id is number ✓Instead of writing model interfaces by hand, generate them from the server's own field definitions (fields_get):
ODOO_URL=https://mycompany.odoo.com ODOO_DB=mydb ODOO_USERNAME=admin@example.com ODOO_PASSWORD=secret \
npx @vvhybe/odoo-client typegen res.partner sale.order --out src/odoo-types.ts- Credentials come only from
ODOO_URL,ODOO_DB,ODOO_USERNAME, andODOO_PASSWORDorODOO_API_KEY. With an API key, the command uses XML-RPC. SetODOO_VERSION(14–19) for servers older than 19. - Without
--out, the file is printed.--outcreates missing folders. - Each model becomes one interface named in PascalCase (
sale.order→SaleOrder), typed the waysearchReadreturns values: many2one[number, string] | false, x2manynumber[], selection a union of its keys, text and date fieldsstring | false. Each field keeps its label as a doc comment. - The output has no timestamp or server details, so regenerating gives clean diffs.
- Exit codes:
0success,1usage, environment or file-writing error,2Odoo error. AnODOO_URLwith a user name or password is refused, so it never appears in an error message. Two models that would get the same interface name (res.partnerandres_partner) are refused too.
Every field is declared. For a searchRead that asks for some fields only, pick them:
import type { TypedOdooRecord } from '@vvhybe/odoo-client';
import type { ResPartner } from './odoo-types';
type PartnerRow = TypedOdooRecord<Pick<ResPartner, 'name' | 'email' | 'company_type'>>;
const partners = await odoo.orm.searchRead<PartnerRow>('res.partner', [], {
fields: ['name', 'email', 'company_type'],
});
// partners[0].company_type is "person" | "company" | false ✓The same generator is available as functions: generateModelTypes(model, fieldsGet) and generateTypesFile([{ model, fields }]).
// Process all active products in pages of 200
for await (const page of odoo.orm.paginate('product.product', [['active', '=', true]], {
fields: ['name', 'default_code', 'list_price'],
pageSize: 200,
})) {
await syncToDatabase(page);
console.log(`Synced ${page.length} products`);
}const odoo = await OdooConnect.connect({
url: 'https://mycompany.odoo.com',
db: 'mydb',
username: 'admin@example.com',
apiKey: process.env.ODOO_API_KEY,
});Generate API keys in Odoo under Settings → Users → your user → API Keys.
const odoo = await OdooConnect.connect({
url: 'https://mycompany.odoo.com',
db: 'mydb',
username: 'admin@example.com',
password: 'secret',
protocol: 'xmlrpc', // ← switch here; the rest of the API is identical
});
const ids = await odoo.orm.search('sale.order', [['state', '=', 'sale']]);import {
OdooAuthenticationError,
OdooAccessError,
OdooValidationError,
OdooNotFoundError,
OdooNetworkError,
OdooTimeoutError,
OdooRpcError,
} from '@vvhybe/odoo-client';
try {
await odoo.orm.create('res.partner', { name: '' });
} catch (error) {
if (error instanceof OdooValidationError) {
console.error('Validation failed:', error.message);
} else if (error instanceof OdooAccessError) {
console.error('Permission denied:', error.message);
} else if (error instanceof OdooNetworkError) {
console.error('Network issue:', error.message, error.cause);
} else if (error instanceof OdooTimeoutError) {
console.error('Timed out after', error.timeoutMs, 'ms');
}
}Odoo's exceptions map to these classes. JSON-RPC uses the exception class in error.data.name, and XML-RPC uses the fault code:
| Odoo raises | JSON-RPC data.name |
XML-RPC faultCode |
Thrown as |
|---|---|---|---|
| Wrong login or API key | odoo.exceptions.AccessDenied |
3 | OdooAuthenticationError |
| Expired session | odoo.http.SessionExpiredException (code 100) |
— | OdooSessionExpiredError, a subclass of OdooAuthenticationError |
| No access right | odoo.exceptions.AccessError |
4 | OdooAccessError |
| Business rule or constraint | odoo.exceptions.UserError, ValidationError |
2 | OdooValidationError |
| Deleted record | odoo.exceptions.MissingError |
— | OdooNotFoundError |
| Anything else | any other | 1 | OdooRpcError (exceptionType, debug) |
None of these is retried: Odoo already answered, and sending the call again gives the same answer.
Retries. Only network failures and timeouts are retried, and only for calls that read: search_read, read, search, search_count, name_search, fields_get, the web_* readers, read_group and authentication. create, write, unlink, custom methods (callMethod) and custom paths (callPath) are sent once. If the response to one of them is lost, Odoo may already have applied it, so read the data again before you retry.
// lib/odoo.ts (server-only)
import { OdooConnect } from '@vvhybe/odoo-client';
let _client: OdooConnect | null = null;
export async function getOdoo() {
if (_client?.getSession()) return _client;
_client = await OdooConnect.connect({
url: process.env.ODOO_URL!,
db: process.env.ODOO_DB!,
username: process.env.ODOO_USERNAME!,
password: process.env.ODOO_PASSWORD!,
});
return _client;
}// app/api/partners/route.ts
import { NextResponse } from 'next/server';
import { getOdoo } from '@/lib/odoo';
export async function GET() {
const odoo = await getOdoo();
const partners = await odoo.orm.searchRead('res.partner', [], {
fields: ['name', 'email'],
limit: 100,
});
return NextResponse.json(partners);
}// JSON-RPC — call a custom Odoo controller
const result = await odoo.jsonRpc.callPath('/my_module/custom_endpoint', {
model: 'my.model',
record_id: 42,
});
// XML-RPC — call a non-standard method directly
const result = await odoo.xmlRpc.executeKw(
'mydb', uid, 'password',
'my.model', 'my_custom_method',
[[42]], { option: true },
);import type { OdooCommand } from '@vvhybe/odoo-client';
await odoo.orm.write('sale.order', [orderId], {
order_line: [
[0, 0, { product_id: 7, product_uom_qty: 3, price_unit: 99.99 }], // CREATE
[1, 55, { product_uom_qty: 5 }], // UPDATE
[2, 60, 0], // DELETE
] satisfies OdooCommand[],
});OdooLogin lets a user sign in to your app with their Odoo account, through OpenID Connect with PKCE (S256). The user never types a password in your app, and your app can receive a ready-to-use Odoo session.
It needs the Odoo module bbg_auth_provider on the Odoo side. Register your app there (Settings → Users & Companies → Connected Apps): you give it the return address (redirectUri), and Odoo gives you a client id and a client secret. Keep both on the server, for example in environment variables.
- Your server calls
login.start(). It returns the Odoo address to send the browser to (url) and the values to remember (keep). - The user signs in to Odoo, if they are not already, and allows your app.
- Odoo redirects the browser to your
redirectUriwith?code=…&state=…, or with?error=…. - Your server calls
login.finish()with those query parameters and thekeepfrom step 1. It checks thestate, swaps the code for tokens, verifies the ID token, and returns the claims and, when Odoo allows it, an Odoo session.
import { OdooLogin } from '@vvhybe/odoo-client';
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable ${name}`);
return value;
}
const login = new OdooLogin({
url: required('ODOO_URL'),
clientId: required('ODOO_CLIENT_ID'),
clientSecret: required('ODOO_CLIENT_SECRET'),
redirectUri: 'https://app.example.com/auth/callback',
});
const { url, keep } = await login.start();
// Store `keep`, then redirect the browser to `url`.import {
OdooLoginError,
OdooNetworkError,
OdooTimeoutError,
} from '@vvhybe/odoo-client';
// In the handler of `redirectUri`, with `query` its URLSearchParams
// and `keep` the value stored at the start:
try {
const { claims, session, odoo } = await login.finish({
code: query.get('code'),
state: query.get('state'),
error: query.get('error'),
expected: keep,
});
console.log(claims.sub, claims.name, claims.email);
if (session && odoo) {
const partners = await odoo.orm.searchRead('res.partner', [], {
fields: ['name'],
limit: 5,
});
console.log(session.uid, odoo.getSessionId(), partners.length);
}
} catch (error) {
if (error instanceof OdooLoginError) {
console.error('Login refused:', error.reason);
} else if (error instanceof OdooNetworkError || error instanceof OdooTimeoutError) {
console.error('Odoo could not be reached');
} else {
throw error;
}
}interface OdooLoginConfig {
url: string; // Odoo address your server reaches (token and key calls)
db?: string; // Needed when the Odoo serves several databases
clientId: string;
clientSecret: string;
redirectUri: string; // The return address registered for the app in Odoo
scope?: string[]; // Default: ['openid', 'profile', 'odoo_session']
timeout?: number; // ms. Default: 30000
version?: OdooVersion; // Passed to the OdooConnect that finish() returns
}| Method | Description |
|---|---|
login.start({ browserUrl? }) |
Returns { url, keep }. url is where to send the browser. Pass browserUrl when the browser reaches Odoo at a different address than your server does (for example a public host against an internal one). It becomes the address the browser is sent to, so take it from your configuration or an allow-list, never from the request. |
login.finish({ code, state, error?, expected }) |
Checks the callback and returns { claims, accessToken, session, odoo }. expected is the keep from start(). Throws OdooLoginError for every refusal, and OdooNetworkError or OdooTimeoutError when Odoo cannot be reached. |
new OdooLogin() throws an OdooConfigError when url or redirectUri is not an absolute http or https address, or when clientId, clientSecret or redirectUri is empty.
keep holds the state, the nonce and the PKCE codeVerifier. The callback is only safe if it comes back unchanged, so your app must seal it between the two requests, and nothing in the browser must be able to read or edit it. Use an httpOnly cookie, encrypted or signed, with SameSite=Lax (so the browser sends it back on Odoo's redirect; Strict would drop it), Secure in production, and a short life of about 10 minutes. Delete it once the callback is handled.
The result.
claimsare the verified ID token claims:sub,name,preferred_username,emailand so on, depending on the scopes.accessTokenis the access token, for Odoo'suserinfoendpoint, which your app calls itself. On an Odoo with several databases, that call also needs the database'ssession_idcookie (see "Several databases"), which the library does not expose; on a one-database Odoo it works as is.sessionandodoocome from theodoo_sessionscope.sessionis anOdooSession(uid,db,username,sessionId), andodoois anOdooConnectalready logged in with it (JSON-RPC). Both arenullwhen Odoo did not grant that scope, for example if you left it out ofscope.
What is checked in the ID token. The algorithm must be RS256; the signature must match a key of Odoo's JWKS (fetched on demand, and once more if the kid is new); iss must be the origin of url; aud must be clientId; exp must not be past (60 seconds of leeway); nonce must be the one from start(); and the required claims (sub, iat) must be present.
What is checked in odoo_session. It is not signed, so its uid must be the ID token's sub, its db must be db when you set one, and its id must be cookie-safe.
finish() throws an OdooLoginError. Its reason (also its code) says what happened:
reason |
When |
|---|---|
state_mismatch |
The state in the callback is missing or is not the one from start() (expired or forged request), or expected is missing or incomplete. It is checked first, so a forged ?error=… link is a state_mismatch too. |
access_denied |
The user refused, or is not allowed to use the app (?error=access_denied, with the right state). |
odoo_error |
Odoo sent another error, sent no code or no tokens, its token call failed, or its signing keys could not be fetched. |
invalid_client |
Odoo refused the client id or secret. |
invalid_grant |
Odoo refused the code or the request (400): for example the code expired or was already used, or the PKCE check failed. |
invalid_id_token |
The ID token failed one of the checks above. |
no_session |
Odoo sent an odoo_session the client cannot use: malformed, for another database than db, or for another user than the ID token's. |
When Odoo cannot be reached, finish() throws an OdooNetworkError or an OdooTimeoutError instead. These are not login refusals, and trying again may work. Handle all three.
When the Odoo serves several databases, set db. start() then sends the browser through /web/login?db=…, so the user signs in to that database, and finish() names the same database when it calls Odoo. Without db, the address goes straight to /bbg_auth_provider/authorize.
Two route handlers: /api/auth/odoo starts the login, /api/auth/odoo/callback finishes it. The example seals keep with iron-session's sealData / unsealData; that is one choice, any authenticated encryption works. APP_SECRET must be a random string of at least 32 characters.
getLogin() makes the OdooLogin on first use rather than when the module loads, because next build imports route modules without the runtime environment variables. It keeps that one instance, so Odoo's keys stay cached between logins.
// lib/odoo-login.ts
import { OdooLogin } from '@vvhybe/odoo-client';
export function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable ${name}`);
return value;
}
export const COOKIE = 'odoo_login';
export const COOKIE_TTL = 600; // seconds
let login: OdooLogin | undefined;
/** The app's one OdooLogin, made on first use. */
export function getLogin(): OdooLogin {
login ??= new OdooLogin({
url: required('ODOO_URL'),
clientId: required('ODOO_CLIENT_ID'),
clientSecret: required('ODOO_CLIENT_SECRET'),
redirectUri: `${required('APP_PUBLIC_URL')}/api/auth/odoo/callback`,
});
return login;
}
const BASE = 'http://app.invalid'; // a fixed placeholder origin
/**
* Only a path of this app ("/orders?x=1"), never another site and never the
* login page itself. Control characters are refused because URL parsing drops
* tabs and line breaks ("/\t/evil.test" would otherwise become another site).
* A path that resolves to "//…" is refused because parsing also resolves dot
* segments: "/..//evil.test" becomes "//evil.test", another site.
*/
export function safePath(next: string | null): string {
if (!next || !next.startsWith('/') || /[\u0000-\u001f\u007f\\]/.test(next)) {
return '/';
}
try {
const url = new URL(next, BASE);
if (
url.origin !== BASE ||
url.pathname.startsWith('//') ||
url.pathname === '/login' ||
url.pathname.startsWith('/login/')
) {
return '/';
}
return url.pathname + url.search + url.hash;
} catch {
return '/';
}
}// app/api/auth/odoo/route.ts
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
import { sealData } from 'iron-session';
import { COOKIE, COOKIE_TTL, getLogin, required, safePath } from '@/lib/odoo-login';
export async function GET(request: Request) {
const next = safePath(new URL(request.url).searchParams.get('next'));
const { url, keep } = await getLogin().start();
const sealed = await sealData(
{ keep, next },
{ password: required('APP_SECRET'), ttl: COOKIE_TTL },
);
(await cookies()).set(COOKIE, sealed, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax', // sent back on Odoo's redirect
path: '/api/auth/odoo',
maxAge: COOKIE_TTL,
});
return NextResponse.redirect(url);
}// app/api/auth/odoo/callback/route.ts
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
import { unsealData } from 'iron-session';
import {
OdooLoginError,
OdooNetworkError,
OdooTimeoutError,
} from '@vvhybe/odoo-client';
import type { OdooLoginKeep } from '@vvhybe/odoo-client';
import { COOKIE, COOKIE_TTL, getLogin, required, safePath } from '@/lib/odoo-login';
function failure(reason: string): NextResponse {
const target = new URL('/login', required('APP_PUBLIC_URL'));
target.searchParams.set('error', reason);
return NextResponse.redirect(target);
}
export async function GET(request: Request) {
const jar = await cookies();
const sealed = jar.get(COOKIE)?.value;
jar.delete({ name: COOKIE, path: '/api/auth/odoo' }); // single use
if (!sealed) return failure('state_mismatch');
// unsealData does not throw for a tampered, expired or wrongly keyed seal:
// it returns {}.
const stored = await unsealData<{ keep?: OdooLoginKeep; next?: string }>(
sealed,
{ password: required('APP_SECRET'), ttl: COOKIE_TTL },
);
if (!stored.keep) return failure('state_mismatch');
const query = new URL(request.url).searchParams;
try {
const { claims, session } = await getLogin().finish({
code: query.get('code'),
state: query.get('state'),
error: query.get('error'),
expected: stored.keep,
});
// Open your own session here: claims.sub is the stable user id, and
// session?.sessionId is the Odoo session if you need to call Odoo later.
void claims;
void session;
return NextResponse.redirect(
new URL(safePath(stored.next ?? null), required('APP_PUBLIC_URL')),
);
} catch (error) {
if (error instanceof OdooLoginError) return failure(error.reason);
if (error instanceof OdooNetworkError || error instanceof OdooTimeoutError) {
return failure('unreachable');
}
throw error;
}
}/login reads the error parameter and shows a message for it. Do not put the Odoo session id in a URL or in a cookie that scripts can read: store it server-side, or in a sealed httpOnly cookie, and rebuild the client later with new OdooConnect({ ..., session }) (see "Starting from an existing session").
An OdooConnect can start already logged in, without calling authenticate(). Give it the session (with its sessionId) that you stored after the login. odoo.getSessionId() returns the session id the client holds, so you can store it.
const odoo = new OdooConnect({
url: required('ODOO_URL'), // the helper from the first example
db: session.db,
session, // { uid, db, username, sessionId }
});A session is an HTTP cookie, so this works over JSON-RPC only. OdooConnect throws an OdooConfigError if session has no sessionId, or if protocol is 'xmlrpc'.
ODOO_URL=https://mycompany.odoo.com
ODOO_DB=mydb
ODOO_USERNAME=admin@example.com
ODOO_PASSWORD=secret
# or
ODOO_API_KEY=your-api-keyPlease see CONTRIBUTING.md for details on how to get started.
Please follow the Conventional Commits format.
To ensure a healthy and welcoming community, we adhere to the following standards:
-
ReportService— render and download PDF/XLSX reports -
WebsocketService— Odoo bus real-time subscriptions - Batch request support (single HTTP round-trip for multiple calls)
- React hooks package (
@vvhybe/odoo-client-react) - Model type generator from
fields_getoutput
MIT © whybe