javascriptmarketo

How do you make a REST API call to Marketo using ONLY Javascript?


We are trying to read value of Marketo tracking cookie to help prefill gated asset forms on our website.

This link explains, first, how to read the value of the cookie using Javascript (simple enough):

//Function to read value of a cookie
function readCookie(name) {
    var cookiename = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(cookiename) == 0) return c.substring(cookiename.length,c.length);
    }
    return null;
}

//Call readCookie function to get value of user's Marketo cookie
var value = readCookie('_mkto_trk');

And then it explains how to take the value of the cookie and make the call to Marketo using REST API via Ruby:

#NOTE: The _mkto_trk cookie value includes an ampersand and needs to be URL encoded to '%26' in order to be properly accepted by the Marketo endpoint.  

require 'rest_client'
require 'json'

#Build request URL
#Replace AAA-BBB-CCC with your Marketo instance
marketo_instance = "https://AAA-BBB-CCC.mktorest.com"
endpoint = "/rest/v1/leads.json"
#Replace with your access token
auth_token =  "?access_token=" + "cde42eff-aca0-48cf-a1ac-576ffec65a84:ab"
#Replace with filter type and values
filter_type_and_values = "&filterType=cookies&filterValues=id:AAA-BBB-CCC%26token:_mch-marketo.com-1418418733122-51548&fields=cookies,email"
request_url = marketo_instance + endpoint + auth_token + filter_type_and_values

#Make request
response = RestClient.get request_url

#Returns Marketo API response
puts response

We don't use Ruby (we use Sitecore CMS). So is there a way to take the value of the cookie, build the Marketo API URL and then make the REST API call to Marketo using only Javascript?


Solution

  • In short, you should NOT access the REST API via client side javascript. (If you talk about server side javascript, node.js, that is another case).

    First of all, while technically it might be possible to make API calls from client side javascript by using ajax requests, you would have to expose your secret API keys (Client Id and Client Secret. That means that anybody could have read/write access to your precious data, what you definitely don't want.

    Second, as ajax calls are subject to Cross-Origin Resource Sharing (CORS) mechanism it would only work from the client side if you would run these requests from the host of your REST API Endpoint (e.g.: https://123-ABC-456.mktorest.com).