What is Cloud Code?

Parse's vision is to let developers build any mobile app without dealing with servers. For complex apps, sometimes you just need a bit of logic that isn't running on a mobile device. Cloud Code makes this possible.

Cloud Code is easy to use because it's built on the same JavaScript SDK that powers thousands of apps. The only difference is that this code runs in the Parse Cloud rather than running on a mobile device. When you update your Cloud Code, it becomes available to all mobile environments instantly. You don't have to wait for a new release of your application. This lets you change app behavior on the fly and add new features faster.

Even if you're only familiar with mobile development, we hope you'll find Cloud Code straightforward and easy to use.

Getting Started

On the computer you use for development, you will need to install Parse's command line tool. This will let you manage your code in the Parse Cloud.

Installing or Updating the Command Line Tool (Mac/Linux)

In Mac OS and Linux/Unix environments, you can get the parse tool by running this command:

This installs a tool named "parse" to /usr/local/bin/parse. There's no other junk, so to uninstall, just delete that file.
This will also update your command line tool
if you already have it installed.

Installing the Command Line Tool (Windows)

The Parse command line tool for Windows is available here. After downloading the zip file and unzipping it, you can launch a parse-aware powershell session by double clicking ParseConsole.exe. After the first run of the ParseConsole, you can also start the powershell session by hitting Win + R and typing "parse".

Setting Up Cloud Code

The next step is to create a directory to store the code that you will run in the cloud. The command parse new sets up this directory, and will prompt you to pick which app you are creating Cloud Code for:

Use the email address and password for your Parse account to log in. If you signed up via OAuth and never set a password, you should now set one by editing your account settings. This will create a directory called MyCloudCode in the current directory. Several files are automatically created for you:

-config/
global.json
-cloud/
main.js
-public/
index.html

The config directory contains a JSON configuration file
that you shouldn't normally need to deal with,
the cloud directory stores your Cloud Code,
and the public directory stores
any static content that you want to host on Parse.
In the cloud directory,
you'll typically just be editing main.js,
which stores all of your Cloud Code functions.
For now, just check that these files were created successfully.
If you're using source control, you can check all of these files in.

We recommend using source control to check in all of these files. If you're not already set up with source control, try this tutorial from GitHub. Keep in mind that these files will contain keys you want to keep private.

A Simple Function

Following ancient tradition, let's see how to run the simplest possible function in the cloud. If you take a look at cloud/main.js, you'll see an example function that just returns a string:

This is a good time to play around with the deployment cycle. Try changing "Hello world!" to a different string, then deploy and run the function again to get a different result. The whole JavaScript SDK is available in Cloud Code, so there's a lot you can do. We'll go over some examples in more detail below.

Cloud Functions

Let's look at a slightly more complex example where Cloud Code is useful. One reason to do computation in the cloud is so that you don't have to send a huge list of objects down to a device if you only want a little bit of information. For example, let's say you're writing an app that lets people review movies. A single Review object could look like:

{
"movie": "The Matrix",
"stars": 5,
"comment": "Too bad they never made any sequels."
}

If you wanted to find the average number of stars for The Matrix, you could query for all of the reviews, and average the stars on the device. However, this uses a lot of bandwidth when you only need a single number. With Cloud Code, we can just pass up the name of the movie, and return the average star rating.

Cloud functions accept a JSON parameters dictionary on the request object, so we can use that to pass up the movie name. The entire Parse JavaScript SDK is available in the cloud environment, so we can use that to query over Review objects. Together, the code to implement averageStars looks like:

The only difference between using averageStars and hello is that we have to provide the parameter that will be accessed in request.params.movie when we call the Cloud function. Read on to learn more about how Cloud functions can be called.

Calling a Cloud Function

Cloud functions can be called from any of the client SDKs, as well as through the REST API (use the drop-down in the example below to switch SDKs). For example, to call the Cloud function named averageStars with a parameter named movie:

request - The request object contains information about the request. The following fields are set:

params - The parameters object sent to the function by the client.

user - The Parse.User that is making the request. This will not be set if there was no logged-in user.

response - The response object contains two functions:

success - This function takes an optional parameter which is the data to send back to the client. This object can be any JSON object/array and can contain a Parse.Object.

error - If called, signals that there was an error. It takes an optional parameter which will be passed to the client to provide a helpful error message.

If the function is successful, the response in the client looks like:

{
"result": 4.8
}

If there is an error, the response in the client looks like:

{
"code": 141,
"error": "movie lookup failed"
}

Running Code On Save

Another reason to run code in the cloud is to enforce a particular data format. For example, you might have both an Android and an iOS app, and you want to validate data for each of those. Rather than writing code once for each client environment, you can write it just once with Cloud Code.

Let's take a look at our movie review example. When you're choosing how many stars to give something, you can typically only give 1, 2, 3, 4, or 5 stars. You can't give -6 stars or 1337 stars in a review. If we want to reject reviews that are out of bounds, we can do this with the beforeSave method:

If response.error is called, the Review object will not be saved, and the client will get an error. If response.success is called, the object will be saved normally. Your code should call one of these two callbacks.

One useful tip is that even if your mobile app has many different versions, the same version of Cloud Code applies to all of them. Thus, if you launch an application that doesn't correctly check the validity of input data, you can still fix this problem by adding a validation with beforeSave.

If you want to use beforeSave for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself:

Modifying Objects On Save

In some cases, you don't want to throw out invalid data. You just want to tweak it a bit before saving it. beforeSave can handle this case, too. You just call response.success on the altered object.

In our movie review example, we might want to ensure that comments aren't too long. A single long comment might be tricky to display. We can use beforeSave to truncate the comment field to 140 characters:

Performing Actions After a Save

In some cases, you may want to perform some action, such as a push, after an object has been saved. You can do this by registering a handler with the afterSave method. For example, suppose you want to keep track of the number of comments on a blog post. You can do that by writing a function like this:

The client will receive a successful response to the save request after the handler terminates, regardless of how it terminates. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the Cloud Code log.

If you want to use afterSave for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself.

Running Code On Delete

You can run custom Cloud Code before an object is deleted. You can do this with the beforeDelete method. For instance, this can be used to implement a restricted delete policy that is more sophisticated than what can be expressed through ACLs. For example, suppose you have a photo album app, where many photos are associated with each album, and you want to prevent the user from deleting an album if it still has a photo in it. You can do that by writing a function like this:

If response.error is called, the Album object will not be deleted, and the client will get an error. If response.success is called, the object will be deleted normally. Your code should call one of these two callbacks.

If you want to use beforeDelete for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself.

Performing Actions After a Delete

In some cases, you may want to perform some action, such as a push, after an object has been deleted. You can do this by registering a handler with the afterDelete method. For example, suppose that after deleting a blog post, you also want to delete all associated comments. You can do that by writing a function like this:

The afterDelete handler can access the object that was deleted through request.object. This object is fully fetched, but cannot be refetched or resaved.

The client will receive a successful response to the delete request after the handler terminates, regardless of how it terminates. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the Cloud Code log.

If you want to use afterDelete for a predefined class in the Parse JavaScript SDK (e.g. Parse.User), you should not pass a String for the first argument. Instead, you should pass the class itself.

Resource Limits

Timeouts

Cloud functions will be killed after 15 seconds of wall clock time.
beforeSave, afterSave, beforeDelete, and afterDelete functions will be killed after 3 seconds of run time.
If a Cloud function or a beforeSave/afterSave/beforeDelete/afterDelete function is called from another Cloud Code call,
it will be further limited by the time left in the calling function.
For example, if a beforeSave function is triggered by a cloud function after it has run for 13 seconds,
the beforeSave function will only have 2 seconds to run, rather than the normal 3 seconds.
If you need additional time to perform operations in Cloud Code, consider using a background job.

Network requests

Network requests that are still in progress after success or error are called will be canceled.
In general, you should wait for all network requests to finish before calling success.
For afterSave functions and afterDelete functions, which don't call success/error,
Cloud Code will wait for all network requests to finish.

Background Jobs

Parse allows you to set up jobs that run in the background. Background Jobs are useful for long running tasks such as integrating with external sites where the response time could be slow, or sending out batched push notifications. If you commonly encounter timeout errors running Cloud functions then you should consider using a Background Job.

There are a few constraints that you need to keep in mind when using Background Jobs:

Jobs will be terminated after 15 minutes of run time.

Apps may have one job running concurrently per 20 req/s in their request limit.

Jobs that are initiated after the maximum concurrent limit has been reached will be terminated immediately.

Writing a Background Job

Writing a Background Job is similar to writing a Cloud function. Say you want to run a user migration job after adding a plan field to the Parse.User object. Your code would look like this:

As with other Cloud Functions, you should handle success and error conditions. For Background Jobs, you do this by calling either status.success() or status.error() when your function completes. Your job execution status will then be set to completed. If you don't call either of these methods, your job will time out in 15 minutes. You can optionally set a progress message while the job is executing by calling status.message(). If you call status.message() after status.success(), your progress message will be ignored.

Once you've deployed your code, you can test the job by running the following command, with your master key:

Setting up a Schedule

Once you've deployed your Background Job code, it can be scheduled in the Dashboard under the Cloud Code tab. The Scheduled Jobs pane lists all currently scheduled jobs and allows you to schedule a new one. To add an entry to the job schedule, select a currently deployed job then specify a description, any required parameters, the start time, and the frequency. Once a job has been scheduled you can run it on demand by clicking Run Now. You may also delete an entry in the job schedule. The Job Status pane lists the results of your job executions. You can see when a job started, its most recent status message, and whether it has completed.

Custom Webhooks

You can use Express
in Cloud Code to build custom webhooks that
receive data in flexible formats. This could be useful if you are writing
a webhook that is called by another web service. You should use this
instead of Cloud Functions if you need to receive
non-JSON data, or if the web service that's calling your endpoint doesn't
support sending Parse's REST API headers. Because your logic still
running within Cloud Code, you'll have full access to the Parse JavaScript SDK
while writing your custom webhook.

In a custom webhook, you can access the request headers and body directly.
You can receive data as JSON, form-encoded, or raw bytes that
you can parse with your favorite parser. You can protect your webhook with
HTTP basic authentication. The following is an example webhook that saves
messages to the Parse Cloud.

The above code uses the express.bodyParser middleware to read request body and
populate req.body.text. Note that we didn't write
app.use(express.basicAuth(…)) in the global app configuration
section because we want HTTP basic auth for this endpoint only, instead of for
all endpoints globally. This way, we could have other endpoints in this app that are
publicly accessible.

To test the custom endpoint, you could run the following command to send
an request containing a form-encoded body.

If you want to access the request body's raw bytes, you should use the
parseExpressRawBody middleware
in your code instead of express.bodyParser.
It's also okay to include both middleware components if some of your request
handlers need JSON or www-form-encoded parsing, while others need the request body bytes.

The example above links the PiecesOfEightCounterProd app to your Cloud Code project. It also creates an alias to new app called production that provides a shorthand way to reference the app.

Developing Cloud Code

While developing new code, you can use the develop command to have the Parse command line tool continuously check for updates to your project and upload changes to Cloud Code. The command looks like:

$ parse develop development
E2013-03-19:20:17:01.423Z] beforeSave handler in release 'v1' ran for GameScore with the input:
{"original": null, "update":{"score": 1337}}
and failed validation with Each GamesScore must have a playerName
New release is named v58
I2013-03-19T20:17:10.343Z] Deployed v58 with triggers:
GameScore:
before_save

Note that for the develop command you need to be explicit about the app that you are going to push new changes to. This avoids accidentally running develop on your production app, potentially deploying untested code to it. The command line tool will upload code changes and display new log messages, until you hit Ctrl-C.

Deploying Code to Production

After you are done testing and updating your code, you can deploy the code to production by passing the production app to the the deploy command, like so:

$ parse deploy production
New release is named v2

Logging from Cloud Code

If you want to log a message to the log files displayed by parse log, you can use console.log, console.error, or console.warn. Both console.error and console.warn will write to the error log.

Cloud functions may log up to 100 messages per request. Any additional logs will be ignored silently.

Networking

Cloud Code allows sending HTTP requests to any HTTP Server using Parse.Cloud.httpRequest. This function takes an options object to configure the call. There is a limit of 8 concurrent httpRequests per Cloud Code request, and additional requests will be queued up.

Modules

Learn how to create your own modules!

Cloud Code supports breaking up JavaScript code into modules. In order to avoid unwanted side effects from loading modules, Cloud Code's modules work similarly to CommonJS modules. When a module is loaded, the JavaScript file is loaded, the source executed and the global exports object is returned. For example, if cloud/name.js has the following source:

name contains a function called isACoolName. The path used by require is relative to the root directory of your Parse project. Only modules in the cloud/ directory can be loaded.

Cloud Modules

Cloud Modules are the easiest way to integrate your Parse app with third-party services and libraries. They work just like JavaScript modules but they are readily available to everyone. Visit our Cloud Modules guide for more details.

Command Line Tool

We've already seen how Parse's command line tool lets you deploy new code to the cloud. It has several other useful bits of functionality. For installation instructions, read Installing the Tool.

Introduction

The same code can be deployed to multiple different applications. This is useful so that you can have separate "development" and "production" applications. Then you test the code on a development application before launching it in production.

The first application that is added (by the new command) will be the default application for all command line operations. All commands except for new take an optional application that the command will be performed on.

Deploying

To deploy a new release, run parse deploy from the command line:

$ parse deploy
New release is named v1

This pushes the new code (in cloud/main.js) to the Parse Cloud and deploys this code for the default target which is the first app that was added or the one you set using parse default. You can choose to deploy to a different target by adding the target as an argument to deploy like so:

$ parse deploy "My Other App"
New release is named v2

You can add release notes to the deploy with the -d or --description= option

When embedding parse deploy within other scripts (such as in an automated testing/deploy environment) you can rely on the exit code from the Parse command line tool to indicate whether the command succeded. It will have an exit code of 0 on success and a non-zero exit code when the deploy failed.

Developing Cloud Code

You can also run the Parse command line tool in development mode using the develop command. This will make the tool watch the source directory for any updates and deploy them to Parse, as well as providing a live stream of the logs.

$ parse develop development
E2013-03-19:20:17:01.423Z] beforeSave handler in release 'v1' ran for GameScore with the input:
{"original": null, "update":{"score": 1337}}
and failed validation with Each GamesScore must have a playerName
New release is named v58
I2013-03-19T20:17:10.343Z] Deployed v58 with triggers:
GameScore:
before_save

Unlike the other commands, for develop you must specify the Parse App to push updates to. This is to avoid accidentally running develop on your production app causing you to run untested code in your production app.

Adding a New Target

You can add a new parse application as a target by running the add command. This prompts you for your Parse.com email and password and provides you a list of applications to choose from:

The add command takes an optional argument which is an alias to assign to the application that can be used instead of the app name.

Typically, all of this configuration data gets stored in the global.json. However, you might have an app that you use for development that you do not want to share with the rest of your team. You can use the --local flag to add this configuration instead to a separate local.json file. This way, you can check global.json into source control, while keeping local.json just on your own machine.

Setting the Default App

parse deploy, parse log, parse rollback, and parse releases use the default app to be run against the commands. parse default allows you to change this default app.

Rolling Back

You can roll back a release using parse rollback. Just like with parse deploy, you can specify an optional target argument.

$ parse rollback
Rolled back to v1

This rolls back to the previous version of the code. You can also specify the release name to roll back to by using the -r or --release= option.

Reading the Logs

Every deploy, rollback, and activation of Cloud Code is logged. You can retrieve the end of logs using the parse log command. There are two types of logs:

INFO - contains everything.

ERROR - contains only the errors.

The log command takes an optional target as well as two options:

-n - The number of log lines to display (defaults to 10)

--level/-l - The log level to use (defaults to INFO)

-f - Emulates tail -f

$ parse log -n 1
I2012-07-10:13:37:00] beforeSave handler in release 'v1' ran for GameScore with the input:
{"original": null, "update":{"score": 1337}}
and failed validation with Each GamesScore must have a playerName

Listing Releases

You can list the known set of releases on the Parse Cloud with the releases command. Parse only tracks the last 10 releases.

Setting the SDK version

The default Parse JavaScript SDK version that is used for the Cloud Code in this directory is the latest version at the time the new command was run for this directory. If you want to change this use parse jssdk. You can see all available Parse JavaScript SDKs using parse jssdk -a. You can also use parse jssdk to check which Parse JavaScript SDK version is currently being used.