Looking for Python instead of Javascript? Visit our Code (Python) documentation.
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:
fetch without building a full dev app.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!
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:
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
outputto 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.
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).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 by tagging questions as Zapier on Stackoverflow!
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, andinputData.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.
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});
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
callbackin asynchronous examples!
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.logresult - great for debugging your code!
This example expects a rawNumber in the "Input Data" field:
return {
calculatedNumber: Number(inputData.rawNumber) / 2
};
This example expects a rawText in the "Input Data" field:
return {
firstEmail: (inputData.rawText.match(/([\w._-]+@[\w._-]+\.[\w._-]+)/gi) || [])[0]
};
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.
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);
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.
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');
StoreClientis a promise based library - get ready for somethen()andcatch()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.
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
Try asking for help by tagging questions as Zapier on Stack Overflow!
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.
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.
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.
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.
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:
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,fetchorcallback! 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!
Check out the Code Examples section of this article!