# Cloud Code Overview (/docs/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? [#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 [#key-use-cases]

### Data Validation and Transformation [#data-validation-and-transformation]

Enforce business rules and data integrity:

```js
// 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 [#external-api-integrations]

Connect Nimbu with third-party services:

```js
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 [#custom-http-endpoints]

Build webhooks and custom API endpoints:

```js
// 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 [#background-job-processing]

Automate repetitive tasks and scheduled operations:

```js
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.models) {
    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 [#admin-ui-extensions]

Add custom actions to the Nimbu admin interface:

```js
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 [#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, filter, sort, count, and batch-read data
* **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 is already configured and ready to use.

```js
// No initialization needed - just start using it!
const query = new Nimbu.Query('products');
query.equalTo('active', true);
const products = await query.collection().fetch();
```

For the full SDK guide, see [Nimbu JS SDK](/docs/sdk/overview).

## Cloud Code Features [#cloud-code-features]

Cloud Code provides five main types of functionality:

### 1. Callbacks [#1-callbacks]

Execute code before or after data operations (create, update, delete):

```js
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 [#2-cloud-functions]

Define custom server-side functions that can be called from themes or external applications:

```js
Nimbu.Cloud.define('calculateShipping', (req, res) => {
  const cost = calculateShippingCost(req.params);
  res.success({ shippingCost: cost });
});
```

### 3. Routes [#3-routes]

Create custom HTTP endpoints for webhooks, APIs, and integrations:

```js
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 [#4-extensions]

Add custom actions and views to the Nimbu admin interface:

```js
Nimbu.Cloud.extend('channel.entries.list', 'products',
  { name: 'Export to CSV' },
  async (req, res) => {
    // Custom bulk export logic
  }
);
```

### 5. Background Jobs [#5-background-jobs]

Run scheduled tasks and long-running operations:

```js
Nimbu.Cloud.job('cleanup_old_data', async () => {
  // Cleanup logic
});

Nimbu.Cloud.schedule('cleanup_old_data', {}, {
  every: '0 2 * * *' // Daily at 2 AM
});
```

## Getting Started [#getting-started]

### 1. Create Your Cloud Code File [#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 [#2-write-your-code]

Start adding callbacks, functions, routes, or jobs:

```js
// 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 [#3-deploy-your-code]

Deploy your Cloud Code using the Nimbu CLI:

```bash
nimbu apps:code:push
```

### 4. Test Your Code [#4-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 [#development-workflow]

1. **Write code locally** in your preferred editor
2. **Test locally** using the Nimbu CLI development server
3. **Deploy** to Nimbu using `nimbu apps:code:push`
4. **Monitor** execution using the Cloud Code logs in the admin interface
5. **Debug** using `console.log()` statements

## Runtime Environment [#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 [#next-steps]

* Learn about [Key Concepts](./key-concepts) - File structure and modules
* Explore [Callbacks](./callbacks) - Data lifecycle hooks
* Create [Cloud Functions](./functions) - Custom server-side logic
* Build [Routes](./routes) - HTTP endpoints and webhooks
* Schedule [Background Jobs](./jobs) - Automated tasks
* Browse the [Nimbu JS SDK](/docs/sdk/overview) - Data access, queries, field types, and recipes
* Review [Available Modules](./modules) - HTTP, mail, crypto, and more
