Node.js SDK
Install the official Node.js SDK and connect your backend to the Raims public API.
Use the @raimshq/raims package in your Node.js backend. The SDK includes ESM and CommonJS modules, TypeScript declarations, resource services, cursor pagination, and webhook authentication.
Install the package
The SDK requires Node.js 22 or later and includes ESM and CommonJS modules and TypeScript types. From your application directory:
npm install @raimshq/raimsThe @raimshq/raims package includes the runtime
and type declarations. Keep your application's lockfile to reproduce the
installed versions.
Download the TGZ package
and SHA256SUMS
to a raims-node-release directory. Compare the file's SHA-256 with its entry
in SHA256SUMS before installing:
npm install ./raims-node-release/raims-node.tgzConfigure the client
Prepare the credential
Get a key from API keys and store it in a vault or protected application environment variable. Keep the credential in the backend, out of browsers, applications distributed to customers, and logs.
The validated API key determines company, environment, and permissions. Sandbox and Production use
https://api.raims.com.For this first read, use a Sandbox key with View customers permission. The request only reads one page; it does not create customers or request emails.
Save the read example
The
.mjsextension enables ESM without changing your application’spackage.json.read-customers.mjs JavaScriptimport Raims, { ApiError, ConnectionError } from '@raimshq/raims'; const apiKey = process.env.RAIMS_API_KEY; if (!apiKey) throw new Error('Set RAIMS_API_KEY on the server.'); const raims = new Raims(apiKey, { maxNetworkRetries: 0 }); try { const customers = await raims.customers.list({ page_size: 10 }); console.log( 'HTTP status: ' + customers.lastResponse.statusCode + '; items: ' + customers.list.length, ); } catch (error) { if (error instanceof ApiError) { console.error( 'HTTP status:', error.statusCode, 'code:', error.code, 'Request-Id:', error.requestId, ); process.exitCode = 1; } else if (error instanceof ConnectionError) { console.error( 'Read failed before a conclusive response. Check the connection.', ); process.exitCode = 1; } else { throw error; } }Run and check the result
From the project directory, with
RAIMS_API_KEYavailable to the process, run:Shellnode read-customers.mjsA successful read prints
HTTP status: 200and the number of items in this page.items: 0is a valid empty result for the key’s company and environment. It is not an authentication failure.
What to check
The SDK reads the list and page envelope below. In an empty page, has_next: false means there is no next page. A nonempty page also returns customer records; the program prints only their count.
No customers found
{
"list": [],
"page": {
"page_size": 10,
"has_next": false,
"has_previous": false,
"next_after": null,
"previous_before": null
}
}Reuse the instance to reuse HTTP connections. In CommonJS, import it with const Raims = require('@raimshq/raims'). The following snippets assume an application-configured raims instance.
Create a customer and a charge
This is a backend snippet, after loading the order from your application’s storage. Keep the customer key separate from the charge key. Save the entire request payload, including the amount and title, before sending; read it again on retries instead of generating new values.
| Input from the saved order | Source and purpose |
|---|---|
customerTaxId | Customer tax ID already authorized and saved by your application. |
customerIdempotencyKey | Idempotency key for creating this customer; saved before the first request. |
chargeIdempotencyKey | A different idempotency key for this charge; saved with the order. |
chargeDueDate | Chosen due date, saved in UTC Unix seconds. |
const customer = await raims.customers.create(
{
tax_id: customerTaxId,
},
{ idempotencyKey: customerIdempotencyKey },
);
const charge = await raims.charges.create(
{
customer_id: customer.id,
amount_cents: 15000,
due_date: chargeDueDate,
title: 'Pedido 1234',
},
{ idempotencyKey: chargeIdempotencyKey },
);
const chargeId = charge.id;
const { statusCode, requestId } = charge.lastResponse;
const pending = statusCode === 202;Persist the returned customer ID and charge ID on the order before returning success to your caller. The charge ID is the value used to resume the read below; the SDK variables are not durable storage.
| Result | What to do next |
|---|---|
HTTP 201 | The charge was created. Save its ID; creation does not confirm payment. This snippet does not request email or payment issuance. |
HTTP 202 in a creation that requests payment issuance | Save the same returned ID and keep the order pending. Retrieve that charge; do not create another one to resolve the pending result. |
| Error or missing response | Handle the structured error. If execution is uncertain, keep the intent and reconcile before retrying with the original key and payload. |
The canonical creation example below shows only the ID and status fields:
Charge without a link or email request
{
"id": "ch_1Q2W3E4R5T6Y7U8I9O0P",
"status": 0
}If the CPF or CNPJ already exists in the same company and environment, the customer is updated and keeps its identifier. 15000 represents BRL 150.00. Keep the key and every parameter, including the due date, when recovering the same intent after losing a response. See Create a charge.
undefined omits a property; null is sent as null. Check the contract before clearing a field. Integers must fit within Number.MAX_SAFE_INTEGER, without conversion through fractional numbers.
Pagination and pending results
await list() fetches one page in list; nextPage() and previousPage() preserve filters and return null when there is no continuation. for await loads subsequent pages as you consume them; leaving the loop prevents further fetches.
The following backend snippet counts at most 100 customers across pages, without logging their records. Keep the configured client open during iteration.
let visited = 0;
for await (const customer of raims.customers.list({ page_size: 50 })) {
visited++;
if (visited === 100) break;
}
console.log('Items visited:', visited);Items visited: 0 means the query found no customers. 100 means the chosen limit was reached; it does not prove there are no more records. A page error interrupts the count. Save progress only after processing a complete page if your job must resume later.
Copy the received cursors and keep the filters; do not send after and before together. See Listing and pagination.
HTTP 202 keeps the result pending. It does not confirm payment and the SDK does not start polling. When resuming the saved order, load chargeId from storage and retrieve that same charge once:
const current = await raims.charges.retrieve(chargeId);
console.log(
'HTTP status:',
current.lastResponse.statusCode,
'charge status:',
current.status,
);HTTP 200 here confirms that the read succeeded. Interpret the returned status and payment_information using the charge reference; a successful GET does not mean the charge was paid or that issuance completed. If issuance is still pending, keep the same ID. Repeated reads do not speed up processing or issue another payment; contact support if the condition persists.
Idempotency and errors
HTTP errors expose statusCode, code, and requestId. ConnectionError indicates a transport failure and can leave a write inconclusive. maxNetworkRetries configures retries for GET only; the default is zero.
The SDK sends an idempotency key only when your application supplies it to an endpoint that accepts Idempotency-Key. It does not generate keys or retry writes automatically. A timeout does not prove that a write was rejected.
Make decisions using the HTTP status and structured code; error.message is a human diagnostic that can change. Do not log complete responses, credentials, personal documents, or temporary URLs. See Idempotency and the SDK error guide.
For example, if the read above returns HTTP 403 with API_KEY_PERMISSION_DENIED, the key lacks access to list customers. Enable View customers on the appropriate key and retry the read. Repeating it with the same permissions will not resolve that error.
For field validation failures, use error.details[].field and error.details[].code to locate the input to correct. Check HTTP response codes for other failures.
For an uncertain write, recover the saved key and the entire original payload. If the charge ID was received, retrieve that ID first. Within the idempotency retention period, a compatible retry can return the preserved result, including a pending 202. A key with different parameters can be rejected; do not change the due date or create a new key to bypass the uncertainty. After retention expires, reconcile before another write.
Use Sandbox
Use a Sandbox key for simulations in raims.simulations.charges and raims.simulations.refunds. A Production key does not become a Sandbox key when these services are used. Check the conditions in the Simulations reference.
Requests that ask for email or webhook deliveries can reach external destinations even in Sandbox. Use only destinations authorized for the integration.
Receive webhooks
rawBody contains the original bytes, such as a Buffer or Uint8Array. receivedHeaders contains the received headers. persistEvent and rejectDelivery represent your application logic; a persistence failure must return an HTTP error to allow redelivery.
import { SignatureVerificationError, Webhook } from '@raimshq/raims';
try {
const event = Webhook.constructEvent(rawBody, receivedHeaders, webhookSecret);
await persistEvent(event);
} catch (error) {
if (error instanceof SignatureVerificationError) rejectDelivery();
else throw error;
}Use the secret_key returned when creating or rotating the webhook, which differs from the API Bearer key. Read the body before the JSON parser and preserve its bytes: do not reserialize the content before authentication.
After authentication, check the type and environment, deduplicate by the event id, and store the work durably before responding with success. The webhook-id header identifies the delivery, not the event. See Receive events.
Update the SDK
To install the current stable version, run from your application directory:
npm install @raimshq/raims@latestReview the release notes and test the flows used by your integration. Future updates are not installed automatically. If you use the TGZ, download the files from the current stable release again, verify the hash, and install the new archive.
When migrating from an earlier TGZ, replace the raims dependency with
@raimshq/raims and update your imports and require calls.
The SDK version is independent of the API HTTP version /v1. Full guides and the method reference are in the SDK repository.