Get Started with JavaScript Delivery SDK

This guide will help you get started with Contentstack JavaScript Delivery SDK to build apps powered by Contentstack.

Prerequisites

To get started with JavaScript, you will need the following:

  • NodeJS 4.4.7 or later

SDK Installation and Setup

To use the JavaScript Delivery SDK, download and include it in the <script> tag:

<script type="text/javascript" src="/path/to/contentstack.min.js"></script>

Initialize SDK

Contentstack offers two regions (US and European) as data centers to store customers' account details and data. Both regions are independent of each other and therefore have a dedicated set of instructions to use SDKs offered by Contentstack.

To use SDKs for the European region, you will have to make certain changes in the configuration of the SDK, as detailed below, and the rest of the instructions remain the same.

To initialize the SDK, you will need to specify the stack’s API keydelivery token, and name of the environment name where you will publish the content:

const Stack = Contentstack.Stack("api_key", "delivery_token", "environment_name");

For Setting the European Region:

If you want to set and use European region, refer to the code below:

const Stack = new Contentstack({ 'api_key': "", 'delivery_token': "", 'environment': "", "region": Contentstack.Region.EU})

Once you have initialized the SDK, you can start getting content in your app.

Cache Policies

The cache policies allow you to define the source from where the SDK will retrieve the content. Based on the selected policy, the SDK can get the data from cache, network, or both.

Let’s look at the various cache policies available for use:

POLICIESDESCRIPTION
IGNORE_CACHE (default)When the IGNORE_CACHE policy is set, the SDK always retrieves data by making a network call, without maintaining any cache. This is set as the default policy.
ONLY_NETWORKIf you set ONLY_NETWORK as the cache policy, the SDK retrieves data through a network call, and saves the retrieved data in the cache.
CACHE_ELSE_NETWORKWhen the CACHE_ELSE_NETWORK policy is set, the SDK gets data from the cache. However, if it fails to retrieve data from the cache, it makes a network call.
NETWORK_ELSE_CACHEWhen the NETWORK_ELSE_CACHE policy is set, the SDK gets data using a network call. However, if the call fails, it retrieves data from cache.
CACHE_THEN_NETWORKIf CACHE_THEN_NETWORK is set as the cache policy, the SDK gets data from cache, and then makes a network call. (A success callback will be invoked twice.)

You can set a cache policy on a stack and/or query object.

Note: Caching in SDK is performed through the SDK's local storage instead of CDN.

Setting a cache policy on a stack

This option allows you to globalize a cache policy. This means the cache policy you set will be applied to all the query objects of the stack.

// setting a cache policy on a stack
Stack.setCachePolicy(Contentstack.CachePolicy.NETWORK_ELSE_CACHE)

Setting a cache policy on a query object

This option allows you to set/override a cache policy on a specific query object.

// setting a cache policy on a query object
Query.setCachePolicy(Contentstack.CachePolicy.CACHE_THEN_NETWORK)

Basic Queries

Contentstack SDKs let you interact with the Content Delivery APIs and retrieve content from Contentstack. They are read-only in nature. The SDKs fetch and deliver content from the nearest server via Fastly, our powerful and robust CDN.

Get a Single Entry

To get a single entry, you need to specify the content type and the id of the entry.

const Query = Stack.ContentType('blog').Entry("blta464e9fbd048668c")
Query.fetch()
   .then(function success(entry) {
       console.log(entry.get('title')); // Retrieve field value by providing a field's uid
       console.log(entry.toJSON()); // Convert the entry result object to JSON
   }, function error(err) {
       // err object
   });

Note: We have a method on query for a specific language. For example, consider the following query:

Stack.ContentType(type).Query().language('fr-fr').toJSON().find()

It will provide all entries of a content type published on the French locale.

Get Multiple Entries

To retrieve multiple entries of a content type, you need to specify the content type uid. You can also specify search parameters to filter results.

const Query = Stack.ContentType('blog').Query();
Query
   .where("title", "welcome")
   .includeSchema()
   .includeCount()
   .toJSON()
   .find()
   .then(function success(result) {
      // result is array where -
      // result[0] => entry objects
      // result[result.length-1] => entry objects count included only when .includeCount() is queried.
      // result[1] => schema of the content type is included when .includeSchema() is queried.
  }, function error(err) {
     // err object
 });

These were examples of some of the basic queries of the SDK. For advanced queries, refer to the Contentstack JavaScript Delivery SDK API reference.

Note: Currently, the JavaScript SDK does not support multiple content types referencing in a single query. For more information on how to query entries and assets, refer the Queries section of our Content Delivery API documentation.

Paginating Responses

In a single instance, the Get Multiple Entries query will retrieve only the first 100 items of the specified content type. You can paginate and retrieve the rest of the items in batches using the skip and limit parameters in subsequent requests.

const Stack = Contentstack.Stack("stack_api_key", "delivery_token", "environment_name");
let blogQuery = Stack.ContentType('example').Query();
         let data = blogQuery.skip(20).limit(20).find()
         data.then(function(result) {
      },function (error) {
         // error function
     })

Limitations

  • We have a URL size limitation of 8KB on API Requests that hit our CDN services. Any Request URL that goes above this size limit will receive the 400 - Bad request error response. Please make sure you limit the size of your API Requests.
  • The JavaScript Delivery SDK does not support multiple content types referencing in a single query.
  • Currently, the JavaScript Delivery SDK does not support retrieving details of Global Fields.

More Resources

Was this article helpful?

Thanks for your feedbackSmile-icon

On This Page

top-arrow