Cloud Code Overview
Cloud Code allows you to run custom JavaScript code on Nimbu's servers. This enables you to add server-side logic to your Nimbu site without managing your own infrastructure.
What is Cloud Code?
Cloud Code is a server-side JavaScript execution environment that extends Nimbu's functionality with custom logic. Your code runs in a V8 JavaScript engine (the same engine that powers Node.js and Chrome) on Nimbu's servers, giving you the power to:
- Validate and transform data before it's saved
- Integrate with external APIs and services
- Create custom HTTP endpoints for webhooks and integrations
- Run background jobs for scheduled tasks and data processing
- Extend the admin interface with custom actions
Key Use Cases
Data Validation and Transformation
Enforce business rules and data integrity:
// Validate email addresses before creating customers
Nimbu.Cloud.before('created', 'customers', (req, res) => {
const email = req.object.get('email');
if (!email || !email.includes('@')) {
res.error('email', 'Please provide a valid email address');
return;
}
res.success();
});External API Integrations
Connect Nimbu with third-party services:
const HTTP = require('http');
// Sync newsletter subscriptions to external service
Nimbu.Cloud.after('created', 'newsletter', (req, res) => {
const email = req.object.get('email');
const apiUrl = `https://api.mailprovider.com/subscribers?email=${email}`;
HTTP.post(apiUrl);
res.success();
});Custom HTTP Endpoints
Build webhooks and custom API endpoints:
// Handle form submissions from external sources
Nimbu.Cloud.post('/webhooks/contact-form', async (req, res) => {
const entry = new Nimbu.Object('contact_requests');
entry.set('name', req.params.name);
entry.set('email', req.params.email);
entry.set('message', req.params.message);
await entry.save();
res.json({ success: true });
});Background Job Processing
Automate repetitive tasks and scheduled operations:
const Mail = require('mail');
// Send weekly newsletter
Nimbu.Cloud.job('send_weekly_newsletter', async () => {
const query = new Nimbu.Query('customers');
query.equalTo('newsletter_subscribed', true);
const subscribers = await query.collection().fetch();
for (const customer of subscribers) {
await Mail.send({
to: customer.get('email'),
template: 'weekly_newsletter',
variables: { name: customer.get('name') }
});
}
});
// Schedule every Monday at 9 AM
Nimbu.Cloud.schedule('send_weekly_newsletter', {}, {
every: '0 9 * * 1'
});Admin UI Extensions
Add custom actions to the Nimbu admin interface:
const Mail = require('mail');
// Add "Send Welcome Email" action to customers list
Nimbu.Cloud.extend(
'channel.entries.list',
'customers',
{ name: 'Send Welcome Email' },
async (req, res) => {
const selectedIds = req.params.selected_ids;
for (const id of selectedIds) {
const customer = await new Nimbu.Query('customers').get(id);
await Mail.send({
to: customer.get('email'),
template: 'welcome_email'
});
}
res.success(`Welcome email sent to ${selectedIds.length} customers`);
}
);The Nimbu JavaScript SDK
Cloud Code has full access to the Nimbu JavaScript SDK through the global Nimbu namespace. The SDK provides:
- Nimbu.Object - Create, read, update, and delete data
- Nimbu.Query - Query and filter data with powerful search capabilities
- Nimbu.Collection - Work with custom content types
- Nimbu.Customer - Manage customer accounts and authentication
- Nimbu.File - Handle file uploads and downloads
- Nimbu.API - Make authenticated API requests
- And many more classes for products, orders, galleries, etc.
Unlike when using the SDK in themes or external applications, you don't need to initialize or authenticate the SDK in Cloud Code - it's already configured and ready to use.
// No initialization needed - just start using it!
const query = new Nimbu.Query('products');
query.equalTo('active', true);
const products = await query.collection().fetch();Cloud Code Features
Cloud Code provides five main types of functionality:
1. Callbacks
Execute code before or after data operations (create, update, delete):
Nimbu.Cloud.before('created', 'orders', (req, res) => {
// Validate order data before saving
});
Nimbu.Cloud.after('updated', 'customers', (req, res) => {
// Trigger side effects after customer updates
});2. Cloud Functions
Define custom server-side functions that can be called from themes or external applications:
Nimbu.Cloud.define('calculateShipping', (req, res) => {
const cost = calculateShippingCost(req.params);
res.success({ shippingCost: cost });
});3. Routes
Create custom HTTP endpoints for webhooks, APIs, and integrations:
Nimbu.Cloud.get('/api/products/:id', async (req, res) => {
const product = await new Nimbu.Query('products').get(req.params.id);
res.json(product);
});4. Extensions
Add custom actions and views to the Nimbu admin interface:
Nimbu.Cloud.extend('channel.entries.list', 'products',
{ name: 'Export to CSV' },
async (req, res) => {
// Custom bulk export logic
}
);5. Background Jobs
Run scheduled tasks and long-running operations:
Nimbu.Cloud.job('cleanup_old_data', async () => {
// Cleanup logic
});
Nimbu.Cloud.schedule('cleanup_old_data', {}, {
every: '0 2 * * *' // Daily at 2 AM
});Getting Started
1. Create Your Cloud Code File
Create a file named main.js in your site's cloud code directory. This is the entry point for your Cloud Code.
2. Write Your Code
Start adding callbacks, functions, routes, or jobs:
// main.js
// Example: Validate email on customer creation
Nimbu.Cloud.before('created', 'customers', (req, res) => {
const email = req.object.get('email');
if (!email || !email.includes('@')) {
res.error('email', 'Invalid email address');
return;
}
res.success();
});
// Example: Custom API endpoint
Nimbu.Cloud.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from Cloud Code!' });
});3. Deploy Your Code
Deploy your Cloud Code using the Nimbu CLI:
nimbu apps:code:push4. Test Your Code
- Callbacks are triggered automatically when data is created/updated/deleted
- Functions can be called from themes using
Nimbu.Cloud.run() - Routes are accessible at
https://yoursite.nimbu.io/cloud/routes/your-path - Jobs can be triggered manually or run on schedule
Development Workflow
- Write code locally in your preferred editor
- Test locally using the Nimbu CLI development server
- Deploy to Nimbu using
nimbu apps:code:push - Monitor execution using the Cloud Code logs in the admin interface
- Debug using
console.log()statements
Runtime Environment
Cloud Code runs in a secure V8 JavaScript environment with:
- Modern JavaScript - Full ES6+ support including async/await
- Native Modules - Built-in modules for HTTP, mail, crypto, and more
- Nimbu SDK - Pre-configured and ready to use
- Execution Limits - Timeouts to prevent runaway code
- Console Logging - Debug with
console.log(),console.error(), etc.
Next Steps
- Learn about Key Concepts - File structure and modules
- Explore Callbacks - Data lifecycle hooks
- Create Cloud Functions - Custom server-side logic
- Build Routes - HTTP endpoints and webhooks
- Schedule Background Jobs - Automated tasks
- Browse the Nimbu JS SDK - Complete API reference
- Review Available Modules - HTTP, mail, crypto, and more