How to Get Started with Code (JavaScript) on Zapier#

Looking for Python instead of JavaScript? Visit our Code (Python) documentation.

Introduction#

With Zapier's Code action you can extend our platform to do just about anything using the most ubiquitous programming language on the web - JavaScript! Run code in response to any trigger that Zapier supports.

Some example use cases include:

  • Transform incorrect dates or convert between other data types.
  • Use custom regular expressions to extract extra data like emails or tracking numbers from large text blobs.
  • Make an extra API call to a different service with fetch without building a full dev app.
  • Augment data from a trigger with extra data from some other source (either generated or external API).
  • Anything else you can dream up!

Warning - this is advanced stuff! You probably need to be a programmer to use this - though you are welcome to play with it. Technical support for bugs in your code is not provided!

How does it work?#

The environment is vanilla node.js v4.3.2 which runs JavaScript. Your script is sandboxed and can only run for a limited amount of time and within a limited amount of memory. If you exceed those limits - your script will be killed (you can upgrade to a paid Zapier to increase your limits).

Since the amount of data that might feed into your script might be large or highly dynamic - you'll need to define an inputData mapping via our GUI. This is a really simple step - the screenshot below shows a very basic example:

Scroll to the examples section to see an assortment of starter scripts.

In your code you will have access to a few variables:

Data Variables#

  • inputData The mapping of data you did right above your code snippet (not available in triggers). All values will be strings.
  • output An object or array of objects that will be the "return value" of this code. You can explicitly return early if you like.

Setting the output to an array of objects will run the subsequent steps multiple times — once for each object in the array. If Code by Zapier is the Zap's trigger and an empty array is returned, nothing happens.

Utilities#

  • callback(err, output) (optional) A callback if you need to do async work - whatever you set to the output data variable is ignored since you provide it directly here. We inspect your code and make our best guess if you are using callback or not!
  • fetch An easy to use HTTP client - read the documentation here.
  • console.log Super helpful if you want to debug your function - you'll need to test your zap to see the values (the logs are returned to you in a runtime_meta added automatically to your output).

Testing/Debugging#

Running your zap via the dashboard is the canonical way to confirm the behavior you expect - your Task History will have all relevant details around the ran code's inputData, output and logs. The test step in the editor can be used for a tighter feedback loop.

Try asking for help by tagging questions as Zapier on Stackoverflow!

↑ Was this documentation useful? Yes No (Suggest Edits)

Code (Javascript) Examples#

Important! Every example depends on specific inputData - which is provided under the "Input Data" field when setting up your - this example screenshot shows three demonstration inputs you can use in your code like this: inputData.body, inputData.receivedDate, and inputData.subject. Be sure you read the code examples and provide the right inputs otherwise nothing will work as expected!

In this section we provide some examples - it is important to note that javascript is an advanced programming language - if you get lost it might make sense to ask a programmer friend or learn javascript yourself.

Introductory Examples#

Each of the four examples below expects a name in the "Input Data" field.

A synchronous example might be something as trivial as:

return {id: 1234, hello: 'world!', name: inputData.name};

You can also bind the result to output - the code above has exactly the same behavior as the code below:

output = {id: 1234, hello: 'world!', name: inputData.name};

You'll notice that when it comes to code - you can solve the same problems in hundreds of unique ways!

A synchronous example with an early empty return might be something as trivial as:

if (inputData.name === 'Larry') {
  return []; // we don't work for Larry!
}
return {id: 1234, hello: 'world!', name: inputData.name};

If Code by Zapier is the Zap's trigger and you return an empty array [], we will not trigger any actions downstream — it is as if you said "nevermind" in code.

An asynchronous example might be something as trivial as:

callback(null, {id: 1234, hello: 'world!', name: inputData.name});

Introductory HTTP Example#

A more complex asynchronous example (no "Input Data" needed):

fetch('http://example.com/')
  .then(function(res) {
    return res.text();
  })
  .then(function(body) {
    var output = {id: 1234, rawHTML: body};
    callback(null, output);
  })
  .catch(callback);

Very important - be sure to use callback in asynchronous examples!

Introductory Logging Example#

This example expects a name in the "Input Data" field:

if (inputData.name) {
  console.log('got name!', inputData.name);
}
return {id: 1234, hello: 'world!', name: inputData.name};

Test your action and look at the data to see the console.log result - great for debugging your code!

Simple Math - Divide by Two#

This example expects a rawNumber in the "Input Data" field:

return {
  calculatedNumber: Number(inputData.rawNumber) / 2
};

Simple Email Extraction#

This example expects a rawText in the "Input Data" field:

return {
  firstEmail: (inputData.rawText.match(/([\w._-]+@[\w._-]+\.[\w._-]+)/gi) || [])[0]
};

Complex Multiple Email Extraction#

This example expects a rawText in the "Input Data" field:

var emails = inputData.rawText.match(/([\w._-]+@[\w._-]+\.[\w._-]+)/gi) || [];
return emails.map(function(email) {
  return {email: email};
});

Because this returns an array like [] instead of a single object like {} - this will activate follow up actions multiple times - one for each email found! If no emails are found - nothing happens.

Weather JSON API Call#

This example expects a zipCode in the "Input Data" field:

fetch('http://api.openweathermap.org/data/2.5/weather?zip=' + inputData.zipCode + ',us')
  .then(function(res) {
    return res.json();
  })
  .then(function(json) {
    callback(null, json);
  })
  .catch(callback);

Store State#

It isn't uncommon to want to stash some data away for the next run, our StoreClient can do exactly that. For example - this is a counter that counts how many times it is ran:

var store = StoreClient('your secret here');
var outCount;
store
  .get('some counter')
  .then(function(count) {
    count = (count || 0) + 1;
    outCount = count;
    return store.set('some counter', count);
  })
  .then(function() {
    callback(null, {'the count': outCount});
  })
  .catch(callback);

Read more about StoreClient here.

↑ Was this documentation useful? Yes No (Suggest Edits)

StoreClient (Javascript)#

Storing and retrieving data with StoreClient is very simple.

There is no need to require it - it comes pre-imported in your Code environment.

You will need to provide a secret that will protect your data. I recommend using Random.org's excellent password generator. Be very sure you pick a complex secret - if anyone guesses it they'll be able to read and write your data!

Instantiating a client is very simple:

var store = StoreClient('your secret here');

StoreClient is a promise based library - get ready for some then() and catch() action.

Most likely you just want to get and set some values - this is the simplest possible example:

var store = StoreClient('your secret here');
store
  .set('hello', 'world')
  .then(function() {
    return store.get('hello');
  })
  .then(function(value) {
    // value === 'world'
    return store.delete('hello');
  })
  .then(function() {
    callback();
  })
  .catch(callback);

If the value doesn't exist during your get() call - it will return a null value.

Bulk Operations#

You can also save and retrieve multiple keys and values - a slightly more complex example:

var store = StoreClient('your secret here');
store
  .setMany({hello: 'world', foo: 'bar'})
  .then(function() {
    return store.getMany('hello', 'foo');
  })
  .then(function(values) {
    // value === {hello: 'world', foo: 'bar'}
    return store.deleteMany('hello', 'foo');
  })
  .then(function() {
    // or, if you want to wipe everything
    return store.clear();
  })
  .then(function() {
    callback();
  })
  .catch(callback);

Note, you can call getMany and deleteMany in a few different ways:

store.getMany('hello', 'foo'); // as arguments
store.getMany(['hello', 'foo']); // as array
store.getMany({hello: null, foo: null}); // as object

Limitations#

  • Any JSON serializable value can be saved.
  • The secret must be under 32 chars in length.
  • Every key must be under 32 chars in length.
  • Every value must be under 2500 bytes.
  • Only 500 keys may be saved per secret.
  • Keys will expire if you do not touch them in 3 months.
↑ Was this documentation useful? Yes No (Suggest Edits)

Common Problems with Code (Javascript) on Zapier#

I need help!#

Try asking for help by tagging questions as Zapier on Stack Overflow!

I keep getting "Process exited before completing request" - what gives?#

9 times out of 10 this happens if your script completes without calling the callback - the most common case is if your fetch().then() doesn't have a .catch() for errors. A simple .catch(callback) will suffice because the error will be passed as the first argument.

'NoneType' object does not support item assignment#

This shows up when you redefine some of the important variables in the function, namely callback. Lambda expects callback to be there to complete an async function, so if you've redefined it you'll get some strange errors.

Requiring or Using External Libraries#

Unfortunately you cannot require external libraries or install or import libraries commonly referred to as "npm modules". Only the standard node.js library and the fetch package are available in the Code app. fetch is already included in the namespace.

Time & Memory Limits#

Free users are limited to 1 second and 128mb of RAM. Paid users get well over double that at 10 seconds and 256mb of RAM. Your Zap will hit an error if you exceed these limits.

I am getting various SyntaxError's and other weird bugs.#

Javascript is a fairly complex language and you should probably be a programmer or willing to dedicate some serious time to learn to code - while we can't help you fix your code (try asking for by tagging questions as Zapier on Stackoverflow) - here are some helpful tools:

Use a Linter#

Linters do an amazing job of letting you know when things are broken - for example - we love http://jshint.com/ and you can paste your code directly there! For example, let's say our code looks like this and we keep getting an error about response not being defined:

// this is bad code - but we don't know why...
fetch('http://example.com/')
  .then(function(res) {
    return res.text();
  }).then(function(body) {
    callback(null, {id: 1234, rawHTML: response});
  }).catch(function(error) {
    callback(error);
  });

The error is driving us crazy! Now in http://jshint.com/ we paste this (note the extra globals definition so jshint knows about Zapier's provided variables):

/* globals inputData, output: true, fetch, callback */

// this is bad code - but we don't know why...
fetch('http://example.com/')
  .then(function(res) {
    return res.text();
  }).then(function(body) {
    callback(null, {id: 1234, rawHTML: response});
  }).catch(function(error) {
    callback(error);
  });

If we look at the results we see that response is indeed incorrect! We should have used body:

You can safely ignore any warnings about "unused variables" of inputData, output, fetch or callback! We provide those for your convenience - you don't need to use them. But if you see something else listed there - it might be a sign that you have a bug!

↑ Was this documentation useful? Yes No (Suggest Edits)

Popular things to do with Code (Javascript) on Zapier#

Check out the Code Examples section of this article!

Get Help