Skip to content

Instantly share code, notes, and snippets.

@steenk steenk/
Last active Jul 5, 2016

What would you like to do?
How to use CORS with a Cloudant account.

Browser CORS Request to Cloudant

CORS is now available at This is a snippet to show how it works. It presumes a modern browser, and a Cloudant account.

You need to activate CORS for your Cloudant account first. One way to do it is with curl.

curl -i -u USERNAME -X PUT \
-H content-type:application/json \
-d '{"enable_cors":true,"allow_credentials":true,"origins":["*"]}'

The first request will give you a session cookie, called "AuthSession". It is not visible in the browser because it is marked "httpOnly". The cookie will be used for authentication in the second request. To make it work, the withCredentials = true has to come after the XMLHttpRequest is open. The cookie is valid 24 hours, so the request for the session cookie doesn't need to be done more than once for a session.

<!doctype html>
<html lang="en">
    <meta charset="utf-8" />
    <pre class="out"></pre>

    const ACCOUNTNAME = 'your_account_name';
    const APIKEY = 'your_api_key';
    const APIPASSWORD = 'your_api_password';
    const DATABASE = 'database_with_api_access';

    var out = document.querySelector('.out');
    // the code comes from another server than, so CORS is needed
    // the first request gets the AuthSession cookie (hidden in the browser)
    function firstRequest (uri, done) {
        var xhr = new XMLHttpRequest();'POST', uri, true);
        xhr.withCredentials = true;
        xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded');
        xhr.onload = function() {
          out.textContent += 'First response: ' + xhr.responseText;

    // the second request can now work without username and password 
    function secondRequest (uri) {
        var xhr = new XMLHttpRequest();'GET', uri, true);
        xhr.withCredentials = true;
        xhr.onload = function() {
          out.textContent += '\n\nSecond response: ' + xhr.responseText;

    firstRequest('https://'+ACCOUNTNAME+'', function () {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.