npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jayik/node

v1.0.0

Published

Node.js client for the Jayik Merchant API v2: orders, warehouses, categories, reference data, API keys and signed webhooks.

Readme

@jayik/node

Node.js client for the Jayik Merchant API v2: create and track delivery orders, manage warehouses and categories, and receive signed webhooks.

  • Node.js 20+, TypeScript types included, ESM and CommonJS
  • No runtime dependencies (uses the built-in fetch)
  • Every endpoint of the Merchant API (39) is covered
  • Official package, maintained by Jayik

Using Laravel? See jayik/laravel.

Contents

Installation

npm install @jayik/node

Configuration

Create an API key in the Tajr dashboard (https://tajr.jayik.app/api-keys). A key acts as the merchant account that owns it, so keep it on the server and never ship it to a browser.

import { Jayik } from '@jayik/node';

const jayik = new Jayik({ apiKey: process.env.JAYIK_API_KEY });

Every option falls back to an environment variable, so with these set new Jayik() is enough:

JAYIK_API_KEY=jk_live_...
JAYIK_WEBHOOK_SECRET=whsec_...

| Option | Environment variable | Default | Purpose | |---|---|---|---| | apiKey | JAYIK_API_KEY | – | Sent as the X-API-KEY header | | baseUrl | JAYIK_BASE_URL | https://api.jayik.app/api/merchant | API root | | timeout | JAYIK_TIMEOUT | 30 | Request timeout, seconds (0 disables) | | rateLimit.retries | JAYIK_RATE_LIMIT_RETRIES | 2 | Retries after a 429 (0 disables) | | rateLimit.maxWait | JAYIK_RATE_LIMIT_MAX_WAIT | 30 | Longest wait per retry, seconds | | webhook.secret | JAYIK_WEBHOOK_SECRET | – | Secret used to verify incoming webhooks | | webhook.tolerance | JAYIK_WEBHOOK_TOLERANCE | 300 | Maximum webhook age, seconds (0 disables) | | fetch | – | global fetch | Custom fetch implementation |

Node does not read .env files by itself: start your app with node --env-file=.env or use your framework's loader.

Quick start

import { Jayik } from '@jayik/node';

const jayik = new Jayik();

// 1. Create the order (it starts as Pending)
let order = await jayik.orders.create({
  customer_name: 'Ali Hassan',
  customer_phone: '07809876543',
  customer_address: 'Baghdad, Karrada, near the bridge',
  amount: 25000, // IQD; 0 when already paid
  governorate_id: 1, // UUID or governorate number
  order_category_id: categoryId,
});

// 2. Tell Jayik it is ready for the driver
await jayik.orders.readyToPickup(order.tr);

// 3. Later: look it up by tracking number
order = await jayik.orders.findByTr(order.tr, ['status']);
console.log(order.status.name); // "AwaitingPickup"

CommonJS works too: const { Jayik } = require('@jayik/node');

How responses work

  • Methods return plain objects exactly as the API sends them, with the API's snake_case keys. The {status, message, data} wrapper is removed, so you get data directly.

  • List methods return a Page:

    const page = await jayik.orders.list({ take: 50 });
    
    page.items;        // array of orders
    page.total;        // number, or null when requested with simple: true
    page.currentPage;
    page.perPage;
    page.lastPage;
    page.hasMorePages;
    page.isEmpty;
    page.length;       // items on this page
    page.raw;          // raw page object
    
    for (const order of page) { ... }
  • lazy() methods return an async iterator that fetches page after page as you loop.

  • Amounts are Iraqi dinars. take is capped at 500 by the API.

  • Failed calls throw errors; see Error handling.

Orders

Create an order

const order = await jayik.orders.create({ ... });

| Field | Type | Required | Notes | |---|---|---|---| | customer_phone | string | yes | e.g. 07809876543 | | customer_address | string | yes | | | amount | number | yes | IQD to collect; 0 for prepaid | | order_category_id | uuid | yes | One of your categories | | governorate_id | uuid | number | yes | Governorate UUID or its number | | customer_name | string | no | | | tr | string | no | Your own tracking number; generated when omitted | | warehouse_id | uuid | no | Pickup point; must be yours | | district_id | uuid | no | Needed for fawri when the account has a fawri price list | | delivery_type | number | no | 0 normal (default), 1 fawri / express | | notes | string | no | | | business_name | string | no | | | destination_coordinate | string | no | "lat,lng", e.g. "33.312805,44.361488" | | total_products | number | no | | | scheduled_delivery_date_from | datetime | no | Date objects are formatted for you (see below) | | scheduled_delivery_date_to | datetime | no | Must be after _from | | invoice_url | string | no | | | order_items | array | no | Each: attribute_id, name, weight, unit, count |

Date objects anywhere in a request body are sent as YYYY-MM-DD HH:MM:SS in the local time zone of your Node process. Pass a string instead if your server does not run in the time zone you mean.

import { DeliveryType } from '@jayik/node';

await jayik.orders.create({
  customer_phone: '07809876543',
  customer_address: 'Erbil, 100m Street',
  amount: 0,
  governorate_id: governorateUuid,
  order_category_id: categoryId,
  delivery_type: DeliveryType.FAWRI,
  district_id: districtId,
  order_items: [{ attribute_id: attributeId, name: 'T-shirt', weight: 1, unit: 'kg', count: 2 }],
});

Create many orders

1 to 300 orders in one request. All are created or none are. The API returns no order data, so look them up by tr afterwards.

await jayik.orders.createBatch([
  { tr: 'A-1001', customer_name: 'Ali', customer_phone: '0780...', customer_address: '...', amount: 15000, order_category_id: cat, governorate_id: govUuid },
  { tr: 'A-1002', customer_name: 'Sara', customer_phone: '0770...', customer_address: '...', amount: 9000, order_category_id: cat, governorate_id: govUuid },
]);

Differences from single create: tr and customer_name are required, and governorate_id must be the UUID (the number is not accepted).

List and search

const page = await jayik.orders.list({
  take: 50, // default 15
  page: 1,
  sort: '-created_at', // "-" = descending
  from: '2026-11-01', // last-update range; send both
  to: '2026-11-30',
  simple: true, // skip the total count (faster)
  include: ['status', 'customer', 'warehouse'],
  filter: {
    status_id: [pendingId, awaitingId], // arrays become CSV
    warehouse_id: warehouseId,
    'customer.phone': '07809876543',
  },
});

| Filter | Matches | |---|---| | tr, uuid | Exact order | | status_id, not_status_id | One or more status ids | | governorate_id, warehouse_id, order_category_id | By relation | | delivery_type | 0 or 1 | | customer.phone | Phone | | customer.name, customer.address | Search | | amount | Amount |

Allowed include values: status, customer, governorate, district, warehouse, orderCategory, orderItems, orderItems.attribute, merchant, history.merchant, driverRate, amountChanges, financial. Nested objects only appear when included.

Walk through every match without handling pages yourself:

for await (const order of jayik.orders.lazy({ filter: { warehouse_id: id } })) {
  await syncOrder(order);
}

Get one order

await jayik.orders.get(123, ['status', 'history.merchant']); // by numeric id
await jayik.orders.findByTr('100006537', ['status']);        // by tracking number, null if none

An order has three identifiers: tr (tracking number, used by most actions), id (integer, used by get and delete) and uuid.

Change an order

await jayik.orders.readyToPickup(tr); // Pending -> AwaitingPickup
await jayik.orders.cancel(tr);        // while Pending, AwaitingPickup or PickupDelayed
await jayik.orders.delete(id);        // permanent; only while Pending

Tracking numbers

const tr = await jayik.orders.generateTr(); // "100006537"
await jayik.orders.trExists('A-1001');      // boolean

Warehouses

Warehouses are your pickup points. Pass a warehouse's id as warehouse_id when creating an order.

const warehouse = await jayik.warehouses.create({
  name: 'Main store',          // required
  address: 'Baghdad, Mansour', // required
  governorate_id: 1,           // UUID or number
  lat: 33.3128,
  long: 44.3615,
  phone: '07801234567',
  secondary_phone: null,
  availability_times_from: '09:00',
  availability_times_to: '18:00',
  site_id: 'vendor-42',        // your own reference
});

await jayik.warehouses.list(15, 1); // take, page
jayik.warehouses.lazy();            // async iterator
await jayik.warehouses.get(id);
await jayik.warehouses.update(id, { name: 'New name', governorate_id: 1 });
await jayik.warehouses.delete(id);
await jayik.warehouses.setDefault(id); // used when an order has no warehouse_id

Always send governorate_id when updating. Leaving it out clears the warehouse's governorate.

Business hours

await jayik.warehouses.businessHours(id);
// [{ day: 'sunday', opens_at: '09:00', closes_at: '17:00', is_closed: false }, ...]

await jayik.warehouses.updateBusinessHours(id, {
  sunday: { is_closed: false, opens_at: '09:00', closes_at: '17:00' },
  friday: { is_closed: true },
}); // days you leave out stay as they are

Order categories

Every order needs one of your categories.

const category = await jayik.orderCategories.create('Clothes');

await jayik.orderCategories.list(10, 1); // take, page
jayik.orderCategories.lazy();
await jayik.orderCategories.get(id);
await jayik.orderCategories.update(id, 'Fashion');
await jayik.orderCategories.delete(id);
await jayik.orderCategories.setDefault(id);

Reference data

These rarely change, so cache them on your side.

const governorates = await jayik.governorates.all();
// [{ id: '...', name: 'بغداد', number: 1 }, ...]

await jayik.statuses.all();   // id, name (stable code), ar_name, en_name, kr_name, color, ...
await jayik.attributes.all(); // product types for order_items[].attribute_id

// Paged and single lookups
await jayik.governorates.list(10, 1);
await jayik.governorates.get(id);
await jayik.statuses.list();
await jayik.statuses.get(id);
await jayik.attributes.list();

Status ids are UUIDs. To filter orders by status, map the stable name to its id once:

import { OrderStatus } from '@jayik/node';

const statusIds = Object.fromEntries((await jayik.statuses.all()).map((status) => [status.name, status.id]));

await jayik.orders.list({ filter: { status_id: statusIds[OrderStatus.DELIVERED] } });

Account

const details = await jayik.account.details();
// { user: {...}, roles: [...], permissions: [...] }

await jayik.account.permissions(); // ['merchant-get-order', 'merchant-store-order', ...]

Keys that belong to an employee only have that employee's permissions; a missing permission results in a PermissionDeniedError.

API keys

const key = await jayik.apiKeys.create('Production server');
key.key; // shown only this once — store it now

await jayik.apiKeys.list();
await jayik.apiKeys.get(id);                       // never includes the value
await jayik.apiKeys.update(id, false);             // switch off
await jayik.apiKeys.update(id, true, 'New label');
await jayik.apiKeys.regenerate(id);                // old value stops working immediately
await jayik.apiKeys.delete(id);

Marketplaces

One Jayik account, many vendors. Create a warehouse per vendor and keep its id:

const warehouse = await jayik.warehouses.create({
  name: vendor.name,
  address: vendor.address,
  site_id: String(vendor.id),
});

await saveVendor(vendor.id, { jayikWarehouseId: warehouse.id });

An order has one pickup point, so a basket with products from several vendors becomes one order per vendor:

// itemsByVendor: { [vendorId]: cartItem[] }
for (const [vendorId, items] of Object.entries(itemsByVendor)) {
  await jayik.orders.create({
    warehouse_id: vendors[vendorId].jayikWarehouseId,
    amount: items.reduce((sum, item) => sum + item.total, 0),
    total_products: items.reduce((sum, item) => sum + item.quantity, 0),
    // customer and destination fields...
  });
}

Then list a vendor's orders with filter: { warehouse_id: id }.

Each vendor has their own Jayik account. Switch keys per call; the default key is untouched:

await jayik.withKey(vendor.jayikApiKey).orders.create({ ... });

Webhooks

Jayik sends a POST to your URL whenever one of your orders is created or changes. The package verifies the signature and hands you a parsed event.

1. Register your URL

await jayik.webhook.set('https://your-app.com/jayik/webhook'); // must be https
await jayik.webhook.secret(); // "whsec_..." -> put it in JAYIK_WEBHOOK_SECRET

2. Listen

jayik.webhook.handler() returns a (req, res) handler for Express, Connect and node:http. It answers 401 to anything not signed by Jayik and {"received": true} once your callback has finished.

import express from 'express';
import { Jayik, OrderStatus } from '@jayik/node';

const jayik = new Jayik();
const app = express();

// Mount this BEFORE express.json(): the signature is checked against the raw body.
app.post(
  '/jayik/webhook',
  jayik.webhook.handler(async (event) => {
    if (event.status === OrderStatus.DELIVERED) {
      await markDelivered(event.tr);
    }
  }),
);

app.use(express.json());

If a JSON body parser must run first, keep the raw bytes for the handler: express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }).

| On event | | |---|---| | .operation | created, updated, assigned, deleted, restored, forceDeleted | | .order | The order record (includes driver) | | .payload | The full decoded body | | .tr | Tracking number | | .status | Status code, e.g. Delivered | | .driver | id, name, phone (null unless enabled for your account) | | .isCreated, .isUpdated, .isAssigned, .isDeleted | Shortcuts | | .is(operation) | Compare against any WebhookOperation |

Jayik expects a 2xx answer within 5 seconds. Hand slow work to a queue and return quickly. If your callback throws, the handler answers 500; pass { onEvent, onError } instead of a function to receive the error.

Other frameworks

Anywhere you can read the raw body and the headers, use constructEvent. It throws InvalidSignatureError when the request is not from Jayik. For example in a Next.js route handler, Hono, or any fetch-style runtime:

import { InvalidSignatureError } from '@jayik/node';

export async function POST(request: Request) {
  try {
    const event = jayik.webhook.constructEvent(await request.text(), request.headers);
    // ...
    return Response.json({ received: true });
  } catch (error) {
    if (error instanceof InvalidSignatureError) {
      return Response.json({ message: 'Invalid signature.' }, { status: 401 });
    }
    throw error;
  }
}

Fastify, NestJS and others work the same way: enable their raw-body option and pass the raw body with request.headers.

3. Test it

await jayik.webhook.test();               // sample data, operation "created"
await jayik.webhook.test(tr, 'updated');  // a real order's data
await jayik.webhook.redeliver(tr);        // re-send "created" for an order
await jayik.webhook.get();                // current URL, secret and signature scheme
await jayik.webhook.remove();             // stop receiving events

How verification works

Each request carries X-Jayik-Timestamp (Unix seconds) and X-Jayik-Signature (sha256= + hex digest). The signature is HMAC-SHA256 of {timestamp}.{raw body} with your webhook secret. Requests with a wrong signature, missing headers, or a timestamp older than the tolerance are rejected, and so is everything when no secret is configured. The comparison is timing-safe.

To verify by hand:

import { SignatureVerifier } from '@jayik/node';

const verifier = new SignatureVerifier(process.env.JAYIK_WEBHOOK_SECRET, 300);

const valid = verifier.isValid(rawBody, req.headers['x-jayik-signature'], req.headers['x-jayik-timestamp']);

Error handling

Every failed call throws a subclass of RequestError, which itself extends JayikError.

| Status | Error | Meaning | |---|---|---| | 400 | ValidationError | Invalid or refused input | | 401 | AuthenticationError | Missing or invalid key | | 403 | PermissionDeniedError | Inactive account, missing permission, or action not allowed | | 404 | NotFoundError | Nothing with that id on your account | | 409 | ConflictError | Not possible in the order's current state | | 422 | UnprocessableError | Valid request that cannot be carried out | | 429 | RateLimitError | Too many requests | | other | RequestError | Anything else, e.g. 5xx |

import { RequestError, ValidationError } from '@jayik/node';

try {
  await jayik.orders.create(data);
} catch (error) {
  if (error instanceof ValidationError) {
    error.errors;   // { customer_phone: ['The customer phone field is required.'] }
    error.message;  // first message
  } else if (error instanceof RequestError) {
    error.status;   // HTTP status
    error.response; // { status, headers, body, text }
  } else {
    throw error;
  }
}

A missing API key throws a JayikError before any request is sent. Network failures and timeouts throw a ConnectionError (also a JayikError) with the original error in cause.

Rate limits

The API allows 120 requests per minute per account. When it answers 429, the client waits the number of seconds in Retry-After and tries again, up to rateLimit.retries times. If the wait would be longer than rateLimit.maxWait, or retries run out, you get a RateLimitError:

if (error instanceof RateLimitError) {
  await requeue(job, { delaySeconds: error.retryAfter ?? 60 });
}

For bulk work, prefer createBatch() and a larger take over many small calls.

Constants

import { CANCELLABLE_STATUSES, DeliveryType, OrderStatus, WebhookOperation } from '@jayik/node';

DeliveryType.NORMAL; // 0
DeliveryType.FAWRI;  // 1
WebhookOperation;    // CREATED, UPDATED, ASSIGNED, DELETED, RESTORED, FORCE_DELETED

| OrderStatus | Value | Meaning | |---|---|---| | PENDING | Pending | Created, waiting for you to mark it ready | | AWAITING_PICKUP | AwaitingPickup | Ready for the driver | | PICKUP_DELAYED | PickupDelayed | | | CANCELLED_BY_MERCHANT | CancelledByMerchant | | | IN_TRANSIT | InTransit | | | IN_DELIVERY_COMPANY_WAREHOUSE | InDeliveryCompanyWarehouse | | | RECEIVED | Received | With the driver, out for delivery | | HAND_OVER | HandOver | | | DELAYED | Delayed | | | RE_DELIVERY | ReDelivery | | | DELIVERED | Delivered | | | RETURNED | Returned | | | RETURNED_TO_COMPANY | ReturnedToCompany | | | ON_THE_WAY_TO_MERCHANT_WAREHOUSE | OnTheWayToMerchantWarehouse | | | RETURNED_TO_MAIN_WAREHOUSE | ReturnedToMainWarehouse | | | CANCELLED | Cancelled | |

CANCELLABLE_STATUSES lists the statuses in which cancel() is allowed.

Testing your app

Pass your own fetch to answer requests without touching the network:

const calls = [];

const jayik = new Jayik({
  apiKey: 'jk_test',
  fetch: async (url, init) => {
    calls.push({ url, body: JSON.parse(init.body) });

    return Response.json({
      status: true,
      message: 'Order Created Successfully',
      data: { id: 1, tr: '100006537' },
    });
  },
});

await checkout(jayik);

assert.equal(calls[0].url, 'https://api.jayik.app/api/merchant/v2/orders');
assert.equal(calls[0].body.amount, 25000);

To fake an incoming webhook, sign it with the verifier:

const body = JSON.stringify({ opration: 'updated', data: { tr: '100', status: { name: 'Delivered' } } });
const time = Math.floor(Date.now() / 1000);

await fetch('http://localhost:3000/jayik/webhook', {
  method: 'POST',
  body,
  headers: {
    'Content-Type': 'application/json',
    'X-Jayik-Timestamp': String(time),
    'X-Jayik-Signature': jayik.webhook.verifier.sign(body, time),
  },
});

Run the package's own tests with npm test.

Method reference

| Call | Endpoint | Permission | |---|---|---| | account.details() | GET /auth/details | – | | orders.list(query) / lazy(query) | GET /v2/orders | merchant-get-order | | orders.get(id, include) | GET /v2/orders/{id} | merchant-show-order | | orders.findByTr(tr, include) | GET /v2/orders?filter[tr]= | merchant-get-order | | orders.create(order) | POST /v2/orders | merchant-store-order | | orders.createBatch(orders) | POST /v2/orders/batch | merchant-store-order | | orders.generateTr() | GET /v2/orders/generate-tr | – | | orders.trExists(tr) | GET /v2/orders/tr-exists/{tr} | – | | orders.cancel(tr) | PUT /v2/orders/cancel | merchant-cancel-order | | orders.readyToPickup(tr) | PUT /v2/orders/ready-to-pickup | merchant-update-order | | orders.delete(id) | DELETE /v2/orders/{id} | merchant-delete-order | | warehouses.list() / lazy() | GET /v2/warehouses | merchant-get-warehouse | | warehouses.get(id) | GET /v2/warehouses/{id} | merchant-show-warehouse | | warehouses.create(data) | POST /v2/warehouses | merchant-store-warehouse | | warehouses.update(id, data) | PUT /v2/warehouses/{id} | merchant-update-warehouse | | warehouses.delete(id) | DELETE /v2/warehouses/{id} | merchant-delete-warehouse | | warehouses.setDefault(id) | PUT /v2/warehouses/default | merchant-update-DefaultWarehouse | | warehouses.businessHours(id) | GET /v2/warehouses/{id}/business-hours | – | | warehouses.updateBusinessHours(id, hours) | PUT /v2/warehouses/{id}/business-hours | merchant-update-warehouse | | orderCategories.list() / lazy() | GET /v2/order-categories | merchant-get-orderCategory | | orderCategories.get(id) | GET /v2/order-categories/{id} | merchant-show-orderCategory | | orderCategories.create(name) | POST /v2/order-categories | merchant-store-orderCategory | | orderCategories.update(id, name) | PUT /v2/order-categories/{id} | merchant-update-orderCategory | | orderCategories.delete(id) | DELETE /v2/order-categories/{id} | merchant-delete-orderCategory | | orderCategories.setDefault(id) | PUT /v2/order-categories/default | merchant-update-DefaultCategory | | governorates.list() / all() | GET /v2/governorates | – | | governorates.get(id) | GET /v2/governorates/{id} | – | | statuses.list() / all() | GET /v2/statuses | – | | statuses.get(id) | GET /v2/statuses/{id} | – | | attributes.list() / all() | GET /v2/attributes | – | | webhook.get() / secret() | GET /v2/webhook | merchant-get-webhook | | webhook.set(url) / remove() | PUT /v2/webhook | merchant-store-webhook | | webhook.test(tr, operation) | POST /v2/webhook/test | merchant-send-webhook | | webhook.redeliver(tr) | POST /v2/webhook/deliveries/{tr} | merchant-send-webhook | | apiKeys.list() | GET /v2/api-keys | merchant-get-apiKey | | apiKeys.get(id) | GET /v2/api-keys/{id} | merchant-show-apiKey | | apiKeys.create(description) | POST /v2/api-keys | merchant-store-apiKey | | apiKeys.regenerate(id) | POST /v2/api-keys/regenerate | merchant-re-generate-apiKey | | apiKeys.update(id, active, description) | PUT /v2/api-keys/{id} | merchant-update-apiKey | | apiKeys.delete(id) | DELETE /v2/api-keys/{id} | merchant-delete-apiKey |

For an endpoint the package does not wrap yet, use the client directly:

await jayik.client.get('v2/something', { take: 10 });
await jayik.client.post('v2/something', { field: 'value' });

License

MIT. See LICENSE.