Zoho Books API: Bulk update thousands of records using Node.js with OAuth refresh, retries and resume support

Zoho Books API: Bulk update thousands of records using Node.js with OAuth refresh, retries and resume support

Hello everyone,

During Zoho Books implementations, one common challenge is updating a large number of existing records. The current options are usually:

  • Update records manually from the UI using Mass Update (with limited batch size).
  • Update records one by one through code using the API.

For large data corrections, migrations, or post-implementation changes, manually updating records is not practical, so I created a Node.js utility that safely performs bulk custom-field updates through the Zoho Books API.

The workflow

  1. Create a custom view containing the records that need to be updated.
  2. Export the records and extract their IDs into a text file (one ID per line).
  3. Point the script at the IDs file.
  4. Define the custom fields and new values in .env.
  5. Run the migration in three stages: probedry-runrun.

Alternatively, instead of exporting IDs manually, you can write a small search function that retrieves the records you need and generates the IDs file automatically.

What the script supports

  • Multiple custom-field updates in the same request.
  • Any Books module (recurring invoices, invoices, contacts, bills, ...) via configuration — no code changes.
  • Zero-ceremony OAuth: you provide only the Self Client grant code — the script exchanges it for a refresh token on first run, persists it locally, and mints access tokens automatically from then on. No manual token calls, no hardcoded tokens.
  • Automatic re-refresh if Zoho invalidates the access token mid-run (401 handling).
  • Request timeouts, retry with backoff for HTTP 429 and 5xx (honours Retry-After).
  • Canary update: one record is updated and verified with a follow-up GET before the batch starts — a typo in a dropdown value aborts after one record, not after thousands.
  • Progress milestones roughly every 10% of the batch, with a live ETA (the initial estimate is measured from the canary request's actual round-trip, not guessed).
  • Resume capability: every outcome is appended to results.jsonl; re-running skips records already updated successfully. A token problem or a network drop mid-run costs nothing.
  • Failed-ID export (failed_ids.txt) for targeted retry.

Configuration

Everything lives in .env. You need exactly: data center, org ID, client ID/secret, a Self Client grant code, the module, the IDs file, and the fields to set — nothing else:

ZB_DC=eu
ZB_ORG_ID=123456789

ZB_CLIENT_ID=1000.xxxxx
ZB_CLIENT_SECRET=xxxxx
ZB_AUTH_CODE=1000.xxxxx

ZB_MODULE=recurringinvoices

ZB_IDS_FILE=invoice_ids.txt
ZB_THROTTLE_MS=700

ZB_FIELDS=[{"api_name":"cf_status","value":"Approved"},{"api_name":"cf_sync_date","value":"2026-07-16"}]

ZB_AUTH_CODE is the grant code from the API console (Self Client → Generate Code, with the scopes below). It is single-use and expires within 3–10 minutes, so run the script right after generating it — the first run exchanges it for a permanent refresh token and saves it to .zb_token_store.json. Add both .env and .zb_token_store.json to .gitignore, and revoke the client when the migration is done.

Gotchas worth knowing:

  • ZB_FIELDS must stay on a single line — dotenv does not parse unquoted multi-line values.
  • ZB_DC must match the data center the client was created on. A client from api-console.zoho.eu will not authenticate against accounts.zoho.com.
  • If the exchange fails with invalid_code, the grant code expired or was already consumed — generate a fresh one and re-run immediately.

ZB_MODULE is the URL path segment (recurringinvoices, invoices, contacts, ...). Note that Books responses wrap the record in a singular root key (invoice, recurring_invoice, ...) that doesn't match the URL segment — the script auto-detects it from the first GET, so you don't have to know this.

Usage

Probe the configuration and field mapping (read-only — this also performs the one-time grant-code exchange on first run):

bash
node zoho-books-bulk-cf-update.mjs probe

Update and verify one record, then stop:

bash
node zoho-books-bulk-cf-update.mjs dry-run

Execute the complete migration:

bash
node zoho-books-bulk-cf-update.mjs run

Sample run output:

48 IDs total · 0 already ok · 48 pending
auto-detected response entity key: "invoice"
Probe 639896000003678005: custom_fields present: cf_status, cf_sync_date, ...
cf_status → customfield_id 639896000000729241 (current: "Draft")
Canary update on 639896000003678005 ...
Canary verified.
Small batch (47 records) — throttle lowered to 300 ms.
1/48 · ETA 1.1 min
5/48 · ETA 1.0 min
10/48 · ETA 0.9 min
...
48/48 Done · ok=48 fail=0

Implementation details

The update process intentionally runs sequentially instead of firing parallel requests, to respect the per-minute API limit (100 requests/min per organization), avoid failures caused by throttling, and keep the migration predictable. The default 700 ms delay keeps the rate at roughly 85 requests/min. Batches of 90 records or fewer physically cannot breach the per-minute cap, so the script speeds those up automatically.

One detail that matters across orgs: custom fields in the update payload are addressed by customfield_id where possible. The script GETs one record first, resolves each api_name to its customfield_id, and only falls back to api_name addressing if the field is not present on the sample record.

Required scopes:

ZohoBooks.invoices.READ
ZohoBooks.invoices.UPDATE

(or the equivalent scopes for the module you are updating — always least-privilege rather than ZohoBooks.fullaccess.all)

Production considerations

  • Mind the daily API cap as well as the per-minute one — it varies by Books plan. A 10,000-record migration may need to be split across days on lower plans.
  • Dropdown custom fields must receive a value that matches an option exactly (spacing, hyphens, casing — especially with non-Latin characters). The canary catches this before the batch runs.
  • An in-memory ID list is fine into the tens of thousands; the point of results.jsonl is durability — progress survives crashes, token expiry, and Ctrl+C.
  • For extremely large or recurring migrations, the same logic can move into a queue-based Node.js worker where you control execution time, retry strategy, parallelism, and monitoring.

Where this is useful

  • Updating custom fields after migrations.
  • Fixing incorrectly imported data.
  • Updating integration-generated records.
  • Applying bulk corrections after changing business logic.
  • Cleaning up data after implementation projects.

Sharing this pattern because bulk updates are a common challenge when working with the Zoho Books API. Script and example .env attached.



        • Recent Topics

        • Important updates to your Salesforce integrations in Zoho Creator

          Hello everyone, We're writing to inform you of an important change regarding Salesforce integrations in Zoho Creator. Salesforce has introduced new security requirements for third-party platforms that connect with their services via APIs. To comply with
        • Password Policy in Zoho Mail: Set password rules to keep your organization secure

          Weak or repetitive passwords are one of the most common causes of unauthorized account access in organizations. Zoho Mail's Password Policy feature allows administrators to define and enforce specific password requirements for all users in the organization,
        • What is Workqueue and how to hide it?

          Hi, My CRM suddenly have this "Workqueue", may I ask how to set the permission of this tab?
        • Zoho Community Digest - July 2026| Part 4

          Hi everyone, and welcome back! We're closing out July with a strong final week, from a major LinkedIn integration in Zoho Recruit to AI-powered forecasting in Zoho Analytics. There are also a few heads-ups worth noting, including API changes in Zoho CRM
        • Zoho CRM Community Digest - July 2026| Part 2

          Hello everyone! The second half of July brought five CRM updates, including a heads-up for developers on API changes coming in October, one Quick Win on keeping your attribution data intact through lead conversion, two Dev's Corner threads worth bookmarking,
        • Shared Snippets Everyone

          Hi, Now that the Shared Snippets have been released and I think will be the most used feature implemented in 2023 :) Creating and Using Snippets in Ticket Responses - Online Help | Zoho Desk Maintain consistency in ticket responses with shared snippets
        • Keeping project teams in the know with Zoho Cliq

          Project management is all about processes, data flow, and maintaining order. But communicating appropriate information at crucial times to stakeholders is as important as the moving parts of a project. Zoho Cliq can facilitate effective communication
        • Remove "Subject" as a required field on quotations

          Not sure why, but Zoho has made 'Subject' a system defined required field. I'm not entirely sure why subject would be required as a key field (i.e. you cannot deactivate it or change it from required). It doesn't make much sense on many product quotations,
        • Multi-currency and Products

          One of the main reasons I have gone down the Zoho route is because I need multi-currency support. However, I find that products can only be priced in the home currency, We sell to the US and UK. However, we maintain different price lists for each. There
        • Enable Credit Note creation for Sales Returns BEFORE receiving goods

          Currently, it is not possible to issue a Credit Note linked to a Sales Return until the goods have been officially marked as "received" in the system. In our business, we often need to issue a credit note to our clients immediately upon the initiation
        • Best way to setup Inventory bin tracking for products with multiple boxes/crates

          Hi - we need some advice from the community on setting up Items in the Inventory for products with multiple crates. We have large products in our warehouse where the product is delivered as two large (double pallet) crates. We've setup the Items for these
        • Getting Internal Server Error message when filing for MTD

          I am trying to file for the MTD submission, and after I filled in all the information and click (Fetch Obligation) this message "Internal Server Error [500]" pops up. I have been trying for awhile and its still the same. What shall I do as today is deadline
        • No access to change view permission for team members

          Hi, I want team members to be able to update the percentage progress on their goals at mid year. Currently they cannot edit this, they can only update the comments against the goals. The ability to add view permission to goal progress for team members
        • Turn your Zoho One Home into your workspace with Dashboard 2.0

          When you open Zoho One, you probably don't need to see everything. You need to see what matters to you. A sales manager may want to track pipeline and revenue. An HR manager may want to monitor employee information. A business leader may want a quick
        • Zoho Assist Feature Update: August 2026

          Web Forms Web Forms in Zoho Assist help you collect support requests directly from your website and route them to the right team. Embed a customizable form so customers can raise issue details or join an active remote session using a session ID. Depending
        • Tip #84 – A More Natural Remote Experience with Custom Cursor Support – 'Insider Insights'

          Hello Zoho Assist Community! Anyone who has spent time in a remote support session knows the feeling. You're guiding a customer through a task, moving the cursor across the screen, and something feels just slightly off. The cursor doesn't behave the way
        • 【無料/オンライン】8/20開催|Zoho ワークアウト|ユーザー同士で学び合うオンラインもくもく会

          ユーザーの皆さま、こんにちは。 コミュニティグループの中野です。 8月20日(木)開催の「Zoho ワークアウト」をご案内します。 Zoho ワークアウトは、参加者それぞれが取り組みたいテーマを持ち寄り、 ユーザー同士で交流しながら、設定・検証・運用改善を進めるオンラインの「もくもく会」です。 「作業を進めたいけれど、一人だと手が止まってしまう」 「他社がどのように活用しているのか知りたい」 「同じ課題を持つユーザーと情報交換したい」 そんな方は、ぜひお気軽にご参加ください。 ▶︎ 参加登録はこちら(無料)
        • Assign Price Book to Accounts (again!)

          I can see this topic has been bumping about for over 10 years and unfortunately Zoho hasn't seen the need (or use case) in CRM to be able to assign an account to a price book to automate quoting (amongst other things). Strange given they DO assign price
        • Custom Statuses - Can You Do Anything With Them?

          As far as I can tell, one really cannot do much with custom statuses. I created a new custom status for sales orders called "Customizing / Hold". This is for sales orders that have the Confirmed status. The use case here is that, as an e-commerce company,
        • Price Book in foreign currency

          We have many customers who buy in foreign currency (USD), where our base currency is our local currency (AUD). It would be normal (it is in Zoho Books, Zoho Inventory etc.) to assign a currency to a price book, but I cannot find this option in Zoho CRM
        • How to disable option to search (In Advanced Field > Matrix Choice > Dropdown)

          In Advanced Field > Matrix Choice > Dropdown I don’t want the option to search or type to fill in words. How can I disable or remove this function?
        • Layout rules in Zoho FSM

          As titled, is there an item in the pipeline or an ETA for the implementation of layout rules in Zoho FSM? Similar to how they work in Zoho CRM https://help.zoho.com/portal/en/kb/crm/customize-crm-account/customizing-page-layouts/articles/create-conditional-layouts
        • Marketing Tip #45: Use WhatsApp to engage customers and drive more sales

          Email is great. Social media is useful. But when it comes to getting a message actually read? WhatsApp wins. In general, open rates on WhatsApp messages are significantly higher than email, and the conversation feels personal rather than promotional.
        • Client Script also planned for Zoho Desk?

          Hello there, I modified something in Zoho CRM the other day and was amazed at the possibilities offered by the "Client Script" feature in conjunction with the ZDK. You can lock any fields on the screen, edit them, you can react to various events (field
        • View Answer Bot conversations?

          We are trialing Zia and are experimenting with Answer Bot on our knowledge base. So far so good! Management asks me if it is possible to view Answer Bot conversations, the purpose being to look over its shoulder and confirm that it is working as des
        • Add Comment workflow action delayed by 1–2 minutes in Zoho Desk

          Hello Zoho Support team, We are experiencing an issue with a workflow in Zoho Desk. The workflow is triggered when the Quote ID field is updated and performs two actions: A standard Field Update An Add Comment custom action When the Quote ID field is
        • Where do I edit the "Welcome to [portal name]" message

          I am looking for a way to edit the "Welcome to" part of the message that is seen on the landing page (ex: https://help.zoho.com/portal/en/home). When I use the French interface, it doesn't make sense... I want to change it from "Bienvenue chez" to" Bienvenue au". Thanks!
        • Zoho Books | Product updates | August 2026

          Hello users, July has been an exciting month for Zoho Books! This month, we're excited to introduce HTML PDF Templates, Placeholders as Pills, expanded approval workflows for Sales Returns and Journals, and significant compliance updates across the India,
        • Zoho CRM Layout Rules: Nine New Actions, Profile-Based Execution, and Interactive Preview

          Hello everyone, Availability: This feature is now available for customers in the JP and SA DCs. It is planned to be released for other customers in soon. We’re excited to announce powerful new enhancements to Layout Rules in Zoho CRM - a feature built
        • Zoho Books and TRAINING SALES receipt label for eTims?

          Hi, Can Zoho Books implement TRAINING SALES receipts and push them to eTims for test? In other words how can we send to Zoho or even create in Zoho training mode invoices and TEST the workflow POS>Zoho Books>eTims and back without actually registering
        • Reporting Tags and COGS

          Is there any way to get COGS recorded against reporting tags? The use cases seems very straightforward to me. If I'm running a P/L report against a specific reporting tag (I use mine for customer type, but it could be used for regions, etc.), the revenue
        • Hide Custom Fields for Customers or Vendors

          For whatever reason, all custom fields added to the Customer module also get added to the Vendor module. This leads to a clunky experience for users, as many custom fields we add only apply to one or the other. There should be a "hide" option to hide
        • Onboarding process

          I urgently need onboarding support. My account still shows trial period.
        • Detailed General Ledger - Display Transaction Description in Reports

          Hi Zoho Team, I'm currently using Zoho Books and have a question regarding the Detailed General Ledger report. When we enter a description or narration in transactions (Bills, Journal Entries, Expenses, etc.), the report does not display this description.
        • Which Zoho CRM tasks would you want an AI assistant to handle?

          I’ve started delegating my Zoho CRM work to AI – and many tasks now take me half the time. It has been so useful that we’re now working to make it available to everyone. Instead of clicking through records and tabs, I simply describe what needs to be
        • Zoho Mail Does Not Integrate with Analytics

          Hello everyone, Just wanted to make a quick post about the problem with zoho mail. Currently it does not connect to Zoho Analytics, which I think is crazy considering both of these applications have existed for a long period of time. Even zoho voice a
        • Net ##th Terms (e.g. due on the following 15th)

          I have a client who pays me twice monthly per our contract. It would be helpful to have terms on my invoices where the invoice is due on the 15th or the 30th of the same or the following month.
        • Project status update visibility within a project

          Currently the only place within Zoho projects to see status updates for a given project is actually not in the project it's self it's in the Collaboration section and then by searching for a given project and clicking on the status tab. It would be great
        • Using custom CRM fields

          I have created a series of fields in the Deals module that need to be linked to fields in a contract I have customized. I can only see how to map standard fields, not the custom ones. How do I do this?
        • Como limitar o Zia Agent?

          Geralmente quando estamos criando um agente de IA no ZIa Agent Studio, colocamos o que ele deve fazer, utilizando as instruções que colocamos no Knowledge Base. Mas como colocamos limites que não devem ser ultrapassados? Para isso utilizamos os Guardrails,
        • Next Page