Global Namespaces
When your code executes, the loader (loader.js) defines several globals:
Nimbu– The JS SDK entrypoint (same API as the publishednimbu-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 throughNimbu.Cloud.http,Nimbu.Cloud.mail, etc. butmodulesis available for advanced scenarios.Nimbu.Site– Lightweight object withid,subdomain, and anenvaccessor 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.
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
| Property | Description |
|---|---|
params | Merged query params, route params, and body (for JSON/URL-encoded payloads). |
body | Raw body string (when available). |
path | Matched path. |
headers | Request headers (case-insensitive keys). |
method | HTTP verb. |
session | Session data (read/write). |
user / customer | Authenticated customer (if signed in). |
site | Convenience alias to the site context. |
Callbacks
| Property | Description |
|---|---|
object | The domain object being created/updated/deleted. |
actor | Customer or backend user initiating the change. |
changes | Object keyed by field name with [oldValue, newValue] arrays. Present for updates/deletes. |
Cloud Functions
| Property | Description |
|---|---|
params | Arguments supplied when invoking the function (REST or SDK). |
user | Authenticated customer (if called in a user context). |
installationId | Installation ID when invoked from SDK environments that support analytics. |
Background Jobs
| Property | Description |
|---|---|
params | Payload supplied when the job was scheduled. |
Backend Extensions
| Property | Description |
|---|---|
object | The entity in context (order, product, channel entry, etc.)—only present for show/edit. |
actor | Backend staff user performing the action. |
params | Form 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. Inbeforecallbacks 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:
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/errordelegate to Ruby (Consoleclass) 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.httprejects requests to disallowed URLs (UrlSecurityService#allowed_uri?). Use theskipUrlNormalizationextra only when you must retain encoded characters.Nimbu.Cloud.pdf.rendervalidates HTML references and remote URLs before rendering.Nimbu.Cloud.mail.sendrequires specific parameters (to, optionallysubject,text, ortemplate). 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)andrequest.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:
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:
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
awaitwith 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.