Go to main content

Request Kentico Cloud Delivery API in Node.js

I've already done a few websites with Kentico Cloud in Node.js and I would like to share my experience. In this article I will show you how to request Kentico Cloud Delivery API in Node.js and provide you with a fully functioning code example.

Request Kentico Cloud Delivery API in Node.js

See live demo on Runkit.

Step by step tutorial

We will use promises in this example. What we need first are npm packages that will help us with that:

  • request
  • request-promise
npm install request
npm install request-promise

Then require both packages in your code:

const request = require('request'),
    requestPromise = require("request-promise");

Now we define a class with Project ID and Preview API Key that represent your Kentico Cloud project:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
}

The class will contain the getContent method that requests the Kentico Cloud storage and gets content from your project:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    // Param represents Kentico Cloud filtering url parameters 
    // isPreview represents boolean flag that defines whether you want preview content or not
    getContent(param, isPreview) {
        // Set default state if parameters are not provided
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }
        
         // Create options that will represent your request to the Kentico Cloud storage
        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        // Request the Kentico Cloud storage and get content from it
        return Delivery.getRawData(options);
    }
}

We call 2 helper methods in the getContent method:

  • getRawData
  • getOptions

 Let's see what they do:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    getContent(param, isPreview) {
        // Set default state if parameters are not provided
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }
        
        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        return Delivery.getRawData(options);
    }

    // Return promise with object obtained from the Kentico Cloud storage
    static getRawData(options) {
        return requestPromise(options).catch(console.error);
    }

    // Return options for the request
    // Structure of the options object is defined by the request-promise package (https://www.npmjs.com/package/request-promise)
    static getOptions(param, projectID, previewKey, isPreview) {
        let options = {
            uri: Delivery.getDeliveryUrl(projectID, isPreview) + param,
            json: true,
            simple: false
        };

        // If we want to preview our content we need to send an authorization header as well
        if (isPreview && previewKey !== null) {
            options.headers = {
                Authorization: 'Bearer ' + previewKey
            }
        }

        return options;
    }
}

In the getOptions method we call one more helper method - getDeliveryUrl. Let's complete that:

class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    getContent(param, isPreview) {
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }
        
        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        return Delivery.getRawData(options);
    }

    static getRawData(options) {
        return requestPromise(options).catch(console.error);
    }

    static getOptions(param, projectID, previewKey, isPreview) {
        let options = {
            uri: Delivery.getDeliveryUrl(projectID, isPreview) + param,
            json: true,
            simple: false
        };

        if (isPreview && previewKey !== null) {
            options.headers = {
                Authorization: 'Bearer ' + previewKey
            }
        }

        return options;
    }

    // Return Kentico Cloud url that should be requested
    static getDeliveryUrl(projectID, isPreview) {
        let url = '';
        
        // If we want to preview our content we need request a slightly different url
        if (isPreview) {
            url = 'https://preview-deliver.kenticocloud.com/' + projectID + '/items';
        } else {
            url ='https://deliver.kenticocloud.com/' + projectID + '/items';
        }
        
        return url;
    }
}

At this stage we have the class and all methods in place. See the usage:

// Initialize Delivery with Project ID and Preview API Key
let kenticoCloudProject = new Delivery('2548121d-cad8-4458-a910-5e4b54cb0956', 'ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidWlkIjogInVzcl8wdlVJVzkwTnRQSVNxNm1GSDN2ZFhiIiwNCiAgImVtYWlsIjogImhlbGxvQG1pbGFubHVuZC5jb20iLA0KICAicHJvamVjdF9pZCI6ICIyNTQ4MTIxZC1jYWQ4LTQ0NTgtYTkxMC01ZTRiNTRjYjA5NTYiLA0KICAianRpIjogInhrU1BLUjlzbzgxSV9rel8iLA0KICAidmVyIjogIjEuMC4wIiwNCiAgImdpdmVuX25hbWUiOiAiTWlsYW4iLA0KICAiZmFtaWx5X25hbWUiOiAiTHVuZCIsDQogICJhdWQiOiAicHJldmlldy5kZWxpdmVyLmtlbnRpY29jbG91ZC5jb20iDQp9.PpBh6wTk57e1_tPHzROiqWPTpr3IjrEoGN8J4rtfPIg');

// Request the Kentico Cloud storage with filtering url parameters and a boolean flag defining whether you want preview content or not
kenticoCloudProject.getContent('?system.type=hello_world', true)
    .then(console.log) // Show results
    .catch(console.error); // Or error

Full code example

Just copy and paste it in your project.  Happy requesting! 

const request = require('request'),
    requestPromise = require("request-promise");

'use strict';

/**
 * Initilizes class with Project ID and Preview API Key that represent a Kentico Cloud project.
 * @constructor Delivery
 * @param {string} projectID Project ID, see details in the Kentico Cloud Developers Hub: https://developer.kenticocloud.com/docs/using-delivery-api#section-getting-project-id.
 * @param {string} previewKey Preview API Key, see details in the Kentico Cloud Developers Hub: https://developer.kenticocloud.com/docs/preview-content-via-api.
 * @example
 * var project = new Delivery('82594550-e25c-8219-aee9-677f600bad53', 'ew0KICAiYWxnIjo...QvV8puicXQ');
 */
class Delivery {
    constructor(projectID, previewKey) {
        this.projectID = projectID;
        this.previewKey = typeof previewKey === 'undefined' ? null : previewKey;
    }
    
    /**
     * Returns promise with data from the Kentico Cloud storage specified by the passed query string.
     * @method getContent
     * @param {string} params string that contains filtering url parameters that are used for requesting Kentico Cloud storage. See details about filtering url parameters: https://developer.kenticocloud.com/v1/reference#delivery-api
     * @param {boolean} isPreview Flag that controls whether only published or all items should be requested.
     * @return {promise} with object obtained from the Kentico Cloud storage.
     * @example
     * // returns
     * // {items: [...], modular_content: {...}, pagination: {...}}
     * project.getContent('?system.type=homepage')
     */
    getContent(param, isPreview) {
        if (typeof param === 'undefined') {
            param = '';
        }

        if (typeof isPreview === 'undefined') {
            isPreview = false;
        }

        let options = Delivery.getOptions(param, this.projectID, this.previewKey, isPreview);

        return Delivery.getRawData(options);
    }
    
    
    /*
     * Helper methods section
     */
    
    // Returns promise with object obtained from the Kentico Cloud storage.
    static getRawData(options) {
        return requestPromise(options).catch(console.error);
    }
    
    // Returns url that should be requested.
    static getDeliveryUrl(projectID, isPreview) {
        let url = '';
        
        if (isPreview) {
            url = 'https://preview-deliver.kenticocloud.com/' + projectID + '/items';
        } else {
            url ='https://deliver.kenticocloud.com/' + projectID + '/items';
        }
        
        return url;
    }
    
    //Returns options for the request.
    static getOptions(param, projectID, previewKey, isPreview) {
        let options = {
            uri: Delivery.getDeliveryUrl(projectID, isPreview) + param,
            json: true,
            simple: false
        };

        if (isPreview && previewKey !== null) {
            options.headers = {
                Authorization: 'Bearer ' + previewKey
            }
        }

        return options;
    }
};


/*
 * Usage
 */
     
// Initialize Delivery with Project ID and Preview API Key
let kenticoCloudProject = new Delivery('2548121d-cad8-4458-a910-5e4b54cb0956', 'ew0KICAiYWxnIjogIkhTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAidWlkIjogInVzcl8wdlVJVzkwTnRQSVNxNm1GSDN2ZFhiIiwNCiAgImVtYWlsIjogImhlbGxvQG1pbGFubHVuZC5jb20iLA0KICAicHJvamVjdF9pZCI6ICIyNTQ4MTIxZC1jYWQ4LTQ0NTgtYTkxMC01ZTRiNTRjYjA5NTYiLA0KICAianRpIjogInhrU1BLUjlzbzgxSV9rel8iLA0KICAidmVyIjogIjEuMC4wIiwNCiAgImdpdmVuX25hbWUiOiAiTWlsYW4iLA0KICAiZmFtaWx5X25hbWUiOiAiTHVuZCIsDQogICJhdWQiOiAicHJldmlldy5kZWxpdmVyLmtlbnRpY29jbG91ZC5jb20iDQp9.PpBh6wTk57e1_tPHzROiqWPTpr3IjrEoGN8J4rtfPIg');

// Request the Kentico Cloud storage with filtering url parameters and a boolean flag defining whether you want preview content or not
kenticoCloudProject.getContent('?system.type=hello_world', true)
    .then(console.log) // Show results
    .catch(console.error); // Or error

Or see live demo on Runkit.

If you are looking for code that is able to make multiple requests at a time read the following article: Multiple requests to Kentico Cloud Delivery API in Node.js

Milan Lund

is a freelance web developer and a proud Basenji owner. His specialties are Kentico CMS/EMS and Kentico Cloud.

Further reading

all posts
  • Kentico Cloud

    Multiple requests to Kentico Cloud Delivery API in Node.js

    In this article I will give you a code example that demonstrates how to make multiple endpoint requests and get one response object. 

  • Front-end & JavaScript

    Simple cookie bar

    EU cookie legislation requires website owners to inform visitors about the use of cookies. In this article, I will provide you with a simple solution of an informative cookie bar.

  • Kentico CMS & EMS

    Social media share urls enhanced by Kentico macros

    Requirements of nearly every website ask us to incorporate links for sharing content on social media. There are tools out there which generates these links for us. But wh…