Skip to content

Global Namespaces

When your code executes, the loader (loader.js) defines several globals:

  • Nimbu – The JS SDK entrypoint (same API as the published nimbu-js-sdk).
  • Nimbu.Cloud – Cloud Code harness providing registration methods (before, after, define, job, get, route, extend, schedule, unschedule) and helper namespaces.
  • Nimbu.Cloud.modules – Bridge to Ruby modules (HTTP, Mail, Pdf, etc.). You normally access them through Nimbu.Cloud.http, Nimbu.Cloud.mail, etc. but modules is available for advanced scenarios.
  • Nimbu.Site – Lightweight object with id, subdomain, and an env accessor for site variables.

Module Loader

Use the built-in require to load files from your project archive. The loader supports relative and absolute paths within the Cloud Code package and caches results per context.

js
const currency = require('lib/currency');

The fs module mirrors this behaviour (Nimbu.Cloud.fs.readFileSync('lib/currency.js')).

Request Object Shapes

Depending on the handler type, the request object provides different helpers.

Routes

PropertyDescription
paramsMerged query params, route params, and body (for JSON/URL-encoded payloads).
bodyRaw body string (when available).
pathMatched path.
headersRequest headers (case-insensitive keys).
methodHTTP verb.
sessionSession data (read/write).
user / customerAuthenticated customer (if signed in).
siteConvenience alias to the site context.

Callbacks

PropertyDescription
objectThe domain object being created/updated/deleted.
actorCustomer or backend user initiating the change.
changesObject keyed by field name with [oldValue, newValue] arrays. Present for updates/deletes.

Cloud Functions

PropertyDescription
paramsArguments supplied when invoking the function (REST or SDK).
userAuthenticated customer (if called in a user context).
installationIdInstallation ID when invoked from SDK environments that support analytics.

Background Jobs

PropertyDescription
paramsPayload supplied when the job was scheduled.

Backend Extensions

PropertyDescription
objectThe entity in context (order, product, channel entry, etc.)—only present for show/edit.
actorBackend staff user performing the action.
paramsForm data (reserved for future use).

Response Helpers

All handlers receive a response object with methods suited for their context:

  • success(dataOrMessage) – Signals success. For routes/functions you can pass JSON; for extensions pass a message.
  • error(messageOrDetails) – Indicates failure. In before callbacks you can supply (field, message) to attach validation errors.
  • render(template, locals) – Routes only; render a Liquid template within the site theme.
  • redirect(url) / redirect_to(url, flash) – Routes and extensions; redirect with optional flash messages.
  • setHeader(name, value) – Routes only; set HTTP headers before responding.

Site Variables & Secrets

Nimbu.Site.env is powered by the SiteVariables module. It supports:

js
const key = Nimbu.Site.env.API_KEY;
const exists = Nimbu.Site.env.has('STRIPE_SECRET');
const names = Nimbu.Site.env.keys();

Values are cached per request using RequestStore to avoid repeated lookups.

Logging & Error Propagation

  • console.debug/log/info/warn/error delegate to Ruby (Console class) with request metadata.
  • When a helper module raises an exception, it saves the message via context.store_last_error_message. JavaScript catches a generic error but rethrows using the stored message so you see meaningful feedback.

Security Considerations

The helper modules enforce strict validations:

  • Nimbu.Cloud.http rejects requests to disallowed URLs (UrlSecurityService#allowed_uri?). Use the skipUrlNormalization extra only when you must retain encoded characters.
  • Nimbu.Cloud.pdf.render validates HTML references and remote URLs before rendering.
  • Nimbu.Cloud.mail.send requires specific parameters (to, optionally subject, text, or template). Missing required fields trigger console errors and no email is sent.

Sessions & Authentication

Routes run with storefront sessions. You can:

  • Check auth: if (request.user) { ... }.
  • Read/write session keys: request.session.set('key', value) and request.session.get('key') (API mirrors Express-like semantics). Ensure values are JSON-serializable.
  • Use response.error(401, 'Unauthorized') to block unauthenticated access.

Working with the SDK

The embedded JS SDK mirrors the public nimbu-js-sdk package. Common patterns:

js
const Orders = Nimbu.Object.extend('orders');
const query = new Nimbu.Query(Orders).equalTo('status', 'paid');
const results = await query.find();

The SDK auto-injects session tokens from the current context. When acting as a backend job, the SDK authenticates with the application credentials.

Storage & Files

  • Nimbu.Cloud.fs.readFileSync(path) – Read bundled source files (useful for templates or configuration JSON).
  • Nimbu.Cloud.zip.create(entries) – Create ZIP archives from base64-encoded file parts.
  • Nimbu.Cloud.s3, Nimbu.Cloud.azure – See modules for interacting with storage providers.

Scheduler Bridge

Nimbu.Cloud.schedule and unschedule proxy to the Ruby scheduler. Cron expressions are parsed server-side; invalid expressions raise an error before scheduling.

Handling Errors Gracefully

Wrap external calls in try/catch and call response.error with clear messages. Because Cloud Code maintains context reuse, unhandled exceptions propagate to the caller and may leave the context alive for subsequent requests. Always:

js
try {
  await Nimbu.Cloud.http.post(url, payload, headers);
  response.success();
} catch (error) {
  console.error('Webhook failed', error);
  response.error('Webhook call failed');
}

Tips for Efficient Handlers

  • Avoid heavy synchronous loops. Use await with the SDK to prevent blocking the event loop.
  • Store IDs (object.id) rather than entire objects when passing data into scheduled jobs.
  • Use site variables for API keys rather than committing them to the code archive.
  • Prefer Cloud functions for business logic that must be reused across routes and extensions.

With the runtime basics in place, explore the Modules & Integrations reference for the full list of helper modules ready to use inside Cloud Code.