Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

contentstack

contentstack263.4kMIT3.25.3TypeScript support: included

Contentstack Javascript SDK

readme

Contentstack

JavaScript Content Delivery SDK for Contentstack

Contentstack is a headless CMS with an API-first approach. It is a CMS that developers can use to build powerful cross-platform applications in their favorite languages. Build your application frontend, and Contentstack will take care of the rest. Read More.

Contentstack provides JavaScript SDK to build application on top of JavaScript. Given below is the detailed guide and helpful resources to get started with our JavaScript SDK.

The JavaScript SDK can also be used to create Node.js and React native applications.

Prerequisite

You need Node.js version 4.4.7 or later installed to use the Contentstack JavaScript SDK.

Setup and Installation

For JavaScript (Browser)

For browsers, we recommend to download the library via npm or yarn to ensure 100% availability.

If you'd like to use a standalone built file you can use the following script tag or download it from jsDelivr, under the dist directory:

<script src="https://cdn.jsdelivr.net/npm/contentstack@latest/dist/web/contentstack.min.js" integrity="12nVcFP1kBh/0Q5rLUvKE34exDRK2DpHUFkGkhRSXTcwGC2PI1D9h64C5arpt5OY" crossorigin="anonymous"></script>

You can also specify a specific version number.

<script src="https://cdn.jsdelivr.net/npm/contentstack@3.25.2/dist/web/contentstack.min.js" integrity="fXmq+b/kd2EenBR7APjzzy0hLTOhAhrir3C6HZYZKuF9O+g+HuSIU7Usi8Ccy9I5" crossorigin="anonymous"></script>

To initialize the SDK, you will need to specify the API Key, Delivery Token, and Environment Name of your stack.

    const Stack = Contentstack.Stack({ "api_key": "api_key", "delivery_token": "delivery_token", "environment": "environment" });

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

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

For Node.js

Node.js uses the Javascript SDK to create apps. To use the JavaScript SDK, install it via npm:

npm i contentstack

To import the SDK in your project, use the following command:

import Contentstack from ‘contentstack’

To initialize the SDK, you will need to specify the API Key, Delivery Token, and Environment Name of your stack.

    const Stack = Contentstack.Stack({ "api_key": "api_key", "delivery_token": "delivery_token", "environment": "environment" });

For Setting the European Region:

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

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

For React Native

React Native uses the Javascript SDK to create apps. To use the JavaScript SDK, install it via npm:

npm i contentstack

To import the SDK in your project, use the following command:

import Contentstack from `contentstack`

To initialize the SDK, you will need to specify the API Key, Delivery Token, and Environment Name of your stack.

    const Stack = Contentstack.Stack({ "api_key": "api_key", "delivery_token": "delivery_token", "environment": "environment" });

For Setting the European Region:

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

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

Key Concepts for using Contentstack

Stack

A stack is like a container that holds the content of your app. Learn more about Stacks.

Content Type

Content type lets you define the structure or blueprint of a page or a section of your digital property. It is a form-like page that gives Content Managers an interface to input and upload content. Read more.

Entry

An entry is the actual piece of content created using one of the defined content types. Learn more about Entries.

Asset

Assets refer to all the media files (images, videos, PDFs, audio files, and so on) uploaded to Contentstack. These files can be used in multiple entries. Read more about Assets.

Environment

A publishing environment corresponds to one or more deployment servers or a content delivery destination where the entries need to be published. Learn how to work with Environments.

Contentstack JavaScript SDK: 5-minute Quickstart

Initializing your SDK

You will need to specify the API key, Delivery Token, and Environment Name of your stack to initialize the SDK:

    const Stack = Contentstack.Stack({ "api_key": "api_key", "delivery_token": "delivery_token", "environment": "environment" });

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

Querying content from your stack

To get a single entry, you need to specify the content type as well as the ID of the entry.

const Query = Stack.ContentType('blog').Entry("<entry_uid>");

Query
    .toJSON()
    .fetch()
    .then(function success(entry) {
        console.log(entry.get('title')); // Retrieve field value by providing a field's uid
    }, function error(err) {
        // err object
    })

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")
    .includeContentType()
    .includeCount()
    .toJSON()
    .find()
    .then(function success(result) {
        // result is array where -
        // result[0] =&gt; entry objects
        // result[result.length-1] =&gt; entry objects count included only when .includeCount() is queried.
        // result[1] =&gt; schema of the content type is included when .includeContentType() is queried.
    }, function error(err) {
        // err object
    })

Cache Policies

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

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 queryobject
Query.setCachePolicy(Contentstack.CachePolicy.CACHE_THEN_NETWORK)

Advanced Queries

You can query for content types, entries, assets and more using our JavaScript API Reference.

JavaScript API Reference Doc

Working with Images

We have introduced Image Delivery APIs that let you retrieve images and then manipulate and optimize them for your digital properties. It lets you perform a host of other actions such as crop, trim, resize, rotate, overlay, and so on.

For example, if you want to crop an image (with width as 300 and height as 400), you simply need to append query parameters at the end of the image URL, such as, https://images.contentstack.io/owl.jpg?crop=300,400. There are several more parameters that you can use for your images.

Read Image Delivery API documentation.

Following are Image Delivery API examples.

// set the quality 100 
imageUrl = Stack.imageTransform(imageUrl, {
    'quality': 100
})

// set the quality to 100, auto optimization, width and height
imageUrl = Stack.imageTransform(imageUrl, {
    'quality': 100,
    'auto': 'webp',
    'width': 100,
    'height': 100
})

Using the Sync API with JavaScript SDK

The Sync API takes care of syncing your Contentstack data with your app and ensures that the data is always up-to-date by providing delta updates. Contentstack’s JavaScript SDK supports Sync API, which you can use to build powerful apps. Read through to understand how to use the Sync API with Contentstack JavaScript SDK. Read Sync API documentation.

Note: Sync function does not support cache policy. When using the Sync function, we recommend you to set the cache policy to IGNORE_CACHE.

Initial sync

The Initial Sync process performs a complete sync of your app data. It returns all the published entries and assets of the specified stack in response.

To start the Initial Sync process, use the syncStack method.

let data = Stack.sync({"init": true})
data.then(function(sync_data, err) {
    //error for any error description
    //sync_data.items: contains sync data
    //sync_data.paginationToken: for fetching the next batch of entries using pagination token
    //sync_token.syncToken: for performing subsequent sync after initial sync
    if (err) throw err
})

Note: Sync function does not support cache policy. When using the Sync function, we recommend you to set the cache policy to IGNORE_CACHE.

The response also contains a sync token, which you need to store, since this token is used to get subsequent delta updates later, as shown in the Subsequent Sync section below.

You can also fetch custom results in initial sync by using advanced sync queries.

Sync pagination

If the result of the initial sync (or subsequent sync) contains more than 100 records, the response would be paginated. It provides pagination token in the response. You will need to use this token to get the next batch of data.

let data = Stack.sync({"pagination_token" : "<pagination_token>"})
data.then(function(result,  err) {
    //error for any error description
    //result.items: contains sync data
    //result.paginationToken: For fetching the next batch of entries using pagination token
    //result.syncToken: For performing subsequent sync after initial sync
    if(err) throw err
})
Subsequent sync

You can use the sync token (that you receive after initial sync) to get the updated content next time. The sync token fetches only the content that was added after your last sync, and the details of the content that was deleted or updated.

let data = Stack.sync({"sync_token" :  “<sync_token>”})
data.then(function(sync_data,  err) {
    //error for any error description
    //sync_data.items: contains sync data
    //sync_data.paginationToken: for fetching the next batch of entries using pagination token
    //sync_token.syncToken: for performing subsequent sync after initial sync
    if(err) throw err
})
Advanced sync queries

You can use advanced sync queries to fetch custom results while performing initial sync. Read advanced sync queries documentation

The MIT License (MIT)

Copyright © 2012-2025 Contentstack. All Rights Reserved

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

Change log

Version: 3.25.3

Date: April-21-2025

Fix:
  • Handle the sanity tests when ENVs are not provided.

Version: 3.25.2

Date: April-02-2025

Fix:
  • allow number, string, object, boolean, and RegExp as valid query parameters in sync method

Version: 3.25.1

Date: April-01-2025

Fix:
  • Update dependencies
  • Update slack notification

Version: 3.25.0

Date: March-10-2025

Fix:
  • Added GCP-EU support

Version: 3.24.3

Date: March-03-2025

Fix:
  • Using Node v22
  • Fixed license and Semgrep issues

Version: 3.24.2

Date: Feb-25-2025

Fix:
  • Reset Timeline Preview variables

Version: 3.24.1

Date: February-03-2025

Fix:
  • Added HTTP error codes in the findOne method

Version: 3.24.0

Date: January-27-2025

Enhancement:
  • updateasseturl for handling jrte within blocks
  • version bumps
  • Fixed testcases

Version: 3.23.0

Date: December-05-2024

Enhancement:
  • Added HTTP error codes in the findOne method

Version: 3.22.2

Date: November-18-2024

Fix:
  • Handle empty entries

Version: 3.22.1

Date: October-28-2024

Fix:
  • Node version bump

Version: 3.22.0

Date: October-17-2024

Fix:
  • Fixed updateAssetUrl issue
  • Fixed the Github workflow issue
  • Updated the qs version

Version: 3.21.0

Date: September-09-2024

Fix:
  • Feat Variants support added

Version: 3.20.4

Date: August-14-2024

Fix:
  • Fix file upload function in sanity report file

Version: 3.20.3

Date: August-02-2024

HotFix:
  • Removed encode for query params

Version: 3.20.1

Date: July-09-2024

Fix:
  • Type support for LivePreviewQuery method params

Version: 3.20.0

Date: May-31-2024

Enhanncement:
  • Adds Timeline Preview changes

Version: 3.19.3

Date: May-17-2024

Enhanncement:
  • Update Asset URL method added

Version: 3.19.2

Date: April-17-2024

Dependency:
  • Hotfix moving slack/bolt to devDependency

Version: 3.19.1

Date: March-06-2024

Dependency:
  • Update Utils SDK dependency version

Version: 3.19.0

Date: February-02-2024

New Features:
  • live preview support both 1.0 and 2.0
  • fix for ESM module cannot use module.exports issue react-native and nativescript builds

    Version: 3.18.1

    Date: January-30-2024

    New Features:
  • added fix for ESM module cannot use module.exports issue

    Version: 3.18.0

    Date: January-15-2024

    New Features:
  • added taxonomy support
  • X-User-Agent updated
  • added region gcp_na

    Version: 3.17.2

    Date: November-15-2023

    Bug fix:
  • Same management token in Live Preview in different stack object fixed
  • X-User-Agent updated
    New Features
  • Early Access added to stack config

Version: 3.17.1

Date: April-18-2023

Bug fix:
  • Access token for header issue resolved

Version: 3.17.0

Date: March-30-2023

Bug fix:
  • Cache set issue resolved
  • Type-definition for SyncResult updated

Version: 3.16.1

Date: February-28-2023

  • Package dependency updated

    Version: 3.16.0

    Date: February-10-2023

    New Features:
  • Plugin Support Added

Version: 3.15.3

Date: July-26-2022

New Features:
  • Live preview with reference in entry on SSR web app issue resolved

Version: 3.15.2

Date: May-03-2022

New Features:
  • Live preview with reference entry issue resolved

Version: 3.15.1

Date: Apr-21-2022

New Features:
  • Azure Na region and packages updates

Version: 3.15.0

Date: Oct-29-2021

New Features:
  • Content branching feature support added

Version: 3.14.0

Date: Oct-19-2021

New Features:
  • Live preview feature support added

Version: 3.13.2

Date: May-26-2021

Dependency:
  • Update Utils SDK dependency version

Version: 3.13.1

Date: Apr-16-2021

Bug fix:
  • IE 11 request method issue resolved

Version: 3.13.0

Date: Apr-05-2021

Update API:
  • [Query]: Added support for method includeEmbeddedItems
  • [Entry]: Added support for method includeEmbeddedItems

Version: 3.12.2

Date: Feb-19-2021

API timeout:
  • updated timeout to min 30 sec
    Enhancement Typescript:
  • boolean value support added:
    • [Query] - where, equalTo, notEqualTo

Version: 3.12.1

Date: Jan-22-2021

Bug fix:
  • Fixed Unhandled promise rejection on HTML response body.

    Version: 3.12.0

    Date: Dec-05-2020

New Features:
  • [Entry] - Publish fallback method added
  • [Query] - Publish fallback method added
  • [Asset] - Publish fallback method added
  • [Assets] - Publish fallback method added

Version: 3.11.0

Date: Sept-25-2020

Update API:
  • Retry limit for fetch request
  • Retry delay options for fetch request
  • Retry on error occur for fetch request
  • Typescript definition added
Enhancement Documentation
  • Documentation update for Only and Except

Version: 3.10.1

Date: Jun-29-2020

Update API:
  • Include Content-Type in Entry

Version: 3.10.0

Date: Jun-19-2020

API timeout:
  • Removed default timeout for request

Version: 3.9.0

Date: Jun-17-2020

Update API:
  • Allowing support to add a timeout for request.
  • Fetch option added for request.

Version: 3.8.1

Date: Nov-19-2019

Update API:
  • [Entry] - Updated in entry module.

Version: 3.8.0

Date: Nov-15-2019

New Features:
  • [Stack]: Added support for method getContentType()
    Update API:
  • [ContentType]: updated method fetch()

Version: 3.7.1

Date: Sept-05-2019

New Features:
  • [Stack]: Region support added

Version: 3.7.0

Date: Jul-29-2019

New Features:
  • [Query]: Added support for method includeReferenceContentTypeUID
  • [Entry]: Added support for method includeReferenceContentTypeUID

Version: 3.6.0

Date: Apr-12-2019

New Features:
  • [Stack]: Added support for method getContentTypes
  • [ContentType]: Added support for method fetch

Version: 3.5.2

Date: Mar-20-2019

Hotfix:
  • Locale storage issue resolved

Version: 3.5.1

Date: Feb-18-2019

Hotfix:
  • Cache policy issue resolved
  • JS reference doc update

Version: 3.5.0

Date: Oct-26-2018

Sync API:
  • [Stack] Added Sync API support

Version: 3.4.0

Date: Jan-10-2018

Update API:
  • New addParam() method added.
  • Added support for NativeScript

Version: 3.3.0

Date: Nov-06-2017

New API:
  • [Stack] Imagetransform API added
  • Added support for NativeScript
Deprecate API:
  • [Query]:
    • findOne
    • includeSchema

Version: 3.2.0

Date: Oct-14-2017

New API:
  • [Asset] Image delivery support
    • find
    • fetch

Version: 3.1.1

Date: Oct-13-2017

Hotfix:
  • Boolean value not working in "where" query
  • only() and includeReference() query not working in reactnative ios

Version: 3.1.0

Date: Apr-28-2017

Update API:
  • Code Revamp: ECMA6
  • React Native support added
  • Webpack upgraded
Bug fix:
  • Fixed unwanted authtoken appending in embedded assets url in RTE field

Version: 3.0.1

Date: Feb-10-2017

Update API:
  • Multiple stacks can be configured rather than a singleton Stack Object
Bug fix:
  • Issue with the support for import attribute on client side