TypeScript Delivery SDK API Reference

View as Markdown

Overview

This reference covers the public API of the @contentstack/delivery-sdk package, one page per class. Use it to look up parameters, return types, validation behavior, and worked examples for every method you reach from import contentstack from '@contentstack/delivery-sdk'.

Before you begin This reference assumes you have installed and initialized the SDK. If you have not, complete the TypeScript Delivery SDK Get Started guide first. This SDK requires Node.js 18 or later. This reference documents version 5.6.2, and the changelog lists behavior changes between releases.

Minimum Working Example

This snippet creates a stack, reads one entry of a content type, and prints its title.

import contentstack from '@contentstack/delivery-sdk';
import type { BaseEntry } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const result = await stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch<BaseEntry>();
  console.log(result.title);
} catch (error: any) {
  // Thrown for API rejections and network failures
  console.error('Request failed:', error.status, error.error_code, error.error_message);
}

SDK Structure

The SDK uses a builder pattern. contentstack.stack() accepts your credentials and returns a Stack, and each call from it returns an object for a narrower scope or with an added modifier. A terminal call sends the request: fetch for a single item, find for a list, and sync for bulk retrieval. Every chain starts at the Stack, and every object a stack creates shares that stack's HTTP client and settings.

Chainable methods store a value and return an object, so an invalid argument does not fail where you pass it. It fails on the terminal call, which throws an APIError when the request fails. Each method page therefore identifies the terminal call its errors surface on.

Pass an interface to the generic terminal calls, fetch<T>() and find<T>(), to type the result. The SDK does not check the response against it.

Known issue In 5.x, TypeScript types the sort and page methods of Entries, AssetQuery, ContentTypeQuery, and GlobalFieldQuery as returning Query, so call the class's own methods before them. Each class page's Class-Level Notes give the order.

Class Overview

Set up the SDK.

ClassRoleAccessed via
ContentstackThe default export, which creates a stack from your credentials and options.import contentstack from '@contentstack/delivery-sdk'
StackOne stack and environment, and the start of every chain.contentstack.stack({...})

Read content types, entries, and global fields.

ClassRoleAccessed via
ContentTypeOne content type and its schema.stack.contentType(uid)
ContentType CollectionThe list of content types in a stack, as a ContentTypeQuery.stack.contentType()
EntryOne entry as an Entry, or the entries of one content type as Entries.contentType.entry(uid)
QueryA filtered list of entries or assets.entries.query()
Global FieldsOne global field as a GlobalField, or the list as a GlobalFieldQuery.stack.globalField(uid)
PaginationThe paging methods that the list classes inherit.query.paginate()

Read assets and images.

ClassRoleAccessed via
AssetOne published asset.stack.asset(uid)
Asset CollectionThe list of published assets, as an AssetQuery.stack.asset()
ImageTransformA builder of Image Delivery API parameters for an image URL. It sends no request.new ImageTransform()

Read taxonomies.

ClassRoleAccessed via
TaxonomyOne published taxonomy, or the list of published taxonomies.stack.taxonomy(uid)
TermOne published term of a taxonomy.taxonomy.term(uid)
TermQueryThe list of published terms of one taxonomy.taxonomy.term()

Known issue Since version 5.0.0, the SDK exports ImageTransform as a type only, so new ImageTransform() neither compiles nor runs. The ImageTransform class page names the URL parameter each method writes, so you can append them yourself.

Task Index

TaskStart hereClass
Fetch one entry by UIDfetchEntry
Filter entries by a field valuewhereQuery
Filter entries by a taxonomy term and the terms below itwhereQuery
Return referenced entries in fullincludeReferenceEntry
Read an entry in another localelocaleEntry
Read an entry variantvariantsEntry
Paginate a list of entries, assets, or taxonomiesPaginationPagination
List the published assets in the stackfindAsset Collection
Read one asset with its image dimensionsincludeDimensionAsset
Read the schema of a content typefetchContentType
Sync all published content, then only what changedsyncStack
List the terms of a taxonomyfindTermQuery
Set the region, retries, cache, or live previewContentstackContentstack

Key Usage Patterns

Each example below is complete, with its own import and stack, so you can run it as an ES module.

Filter entries by a field and sort the matches

import contentstack, { QueryOperation } from '@contentstack/delivery-sdk';
import type { BaseEntry } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  // query() opens the filter, then sort, page size, and count follow.
  const result = await stack
    .contentType('<CONTENT_TYPE_UID>')
    .entry()
    .query()
    .where('title', QueryOperation.EXISTS, true)
    .orderByDescending('updated_at')
    .limit(5)
    .includeCount()
    .find<BaseEntry>();
  console.log('showing', result.entries?.length, 'of', result.count);
  for (const entry of result.entries ?? []) {
    console.log(entry.uid, entry.title);
  }
} catch (error: any) {
  console.error(error);
}

Page through every entry of a content type

The SDK sends one request per find call and does not iterate pages. Combine skip and limit, and stop when you reach the count that includeCount adds.

import contentstack from '@contentstack/delivery-sdk';
import type { BaseEntry } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

const pageSize = 25;
const all: BaseEntry[] = [];

try {
  let total = 0;
  do {
    // A fresh entry() per page, so each request carries its own skip value.
    const page = await stack
      .contentType('<CONTENT_TYPE_UID>')
      .entry()
      .skip(all.length)
      .limit(pageSize)
      .includeCount()
      .find<BaseEntry>();
    const entries = page.entries ?? [];
    all.push(...entries);
    total = page.count ?? 0;
    if (entries.length === 0) break;
  } while (all.length < total);
  console.log('read', all.length, 'of', total, 'entries');
} catch (error: any) {
  console.error(error);
}

Sync all published content, then only what changed

import contentstack from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  // true follows every pagination token and returns all items at once.
  const initial = await stack.sync({}, true);
  console.log('published items:', initial.items.length);

  // Store sync_token, then pass it on the next run to receive only the changes.
  if (initial.sync_token) {
    const changes = await stack.sync({ syncToken: initial.sync_token });
    console.log('changed since the first sync:', changes.items.length);
  }
} catch (error: any) {
  console.error(error);
}

Tell a network failure from an API rejection

import contentstack from '@contentstack/delivery-sdk';
import type { BaseEntry } from '@contentstack/delivery-sdk';

const stack = contentstack.stack({
  apiKey: '<API_KEY>',
  deliveryToken: '<DELIVERY_TOKEN>',
  environment: '<ENVIRONMENT>',
});

try {
  const entry = await stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch<BaseEntry>();
  console.log(entry.title);
} catch (error: any) {
  if (error.status === 0 && error.error_code === 'UNKNOWN_ERROR') {
    // A 401 or 429 that outlasted the retries: check the delivery token and the rate limit.
    console.error('Rejected after retries:', error.error_message);
  } else if (error.status === 0) {
    // No response arrived: error_code holds the Node.js code, or 408 for a timeout.
    console.error('Network failure:', error.error_code);
  } else {
    // The API answered and rejected the request, for example 422 for an unknown UID.
    console.error('API error:', error.status, error.error_code, error.error_message);
  }
}

SDK-Wide Notes

ConcernBehaviorDefault when unset
Authenticationcontentstack.stack() takes apiKey, deliveryToken, and environment, and every class reads them from the stack. No other method takes credentials.Not applicable. stack() throws an Error when any of the three is missing or empty.
Error surfacingEvery terminal call throws an APIError on failure, carrying status, error_code, and error_message. The package does not export APIError, so read those fields rather than testing instanceof.Not applicable. A network failure throws status 0 with the Node.js error code in error_code.
Regions and endpointsPass region to contentstack.stack(): us, eu, au, azure-na, azure-eu, gcp-na, or gcp-eu. A host overrides it, and an unknown region makes stack() throw.Region.US, which resolves to cdn.contentstack.io.
BranchesPass branch to contentstack.stack(). The SDK sends it as the branch header on every request.No branch header, so the API applies its default.
LocalesPass locale to contentstack.stack(), or call setLocale, to send locale on every request. A request-level locale() overrides it for that request.No locale parameter, so the API applies its default.
Rate limiting and retryThis SDK automatically retries 429 and 401 responses and transient network errors, with configurable delay and attempt limits. The Contentstack class page lists the attempt counts and options.On, with retryLimit 5 and retryDelay 300 ms.
TimeoutsPass timeout in milliseconds. The SDK does not retry a request that times out, and the call throws an APIError with status 0 and error_code 408.30000 ms.
Proxy configurationPass a proxy object to route requests through a proxy. With the default, the SDK ignores the HTTP_PROXY and HTTPS_PROXY environment variables.false.
CachingSet cacheOptions with a policy and a persistence store. Known issue: In 5.x, a cached response can answer a different request, and a failed request never settles. See the Contentstack class page.Off.
Live previewSet live_preview on the stack, then call livePreviewQuery for each preview request. While the stack holds a preview hash, every request from that stack goes to the preview host.Off.
Empty UIDsKnown issue: In 5.x, an empty string UID passed to asset, contentType, globalField, taxonomy, entry, or term returns the list object typed as the single item, so a later fetch throws a TypeError.Not applicable. Check a UID variable before you pass it.

Warning This SDK requires a delivery token. stack() checks only that deliveryToken is present, so a management token or a preview token passes it and fails on the first request instead. Pass a preview token in live_preview.preview_token.

Known issue In 5.x, a 401 that outlasts the retries, for example from an invalid delivery token, throws status 0 with error_code UNKNOWN_ERROR. Set retryOnError: false while you debug to see the real 401 status.

SDK Limitations

CapabilitySupportedNotes / Alternative
Query entries of several content types in one requestNoEach entry query belongs to one content type. Run one query per content type and merge the results in your code.
Read every page of a list in one callNoLoop over find with skip and limit, as in Key Usage Patterns above. sync is the exception: pass true as its second argument.
Catch APIError with instanceofNoThe package does not export the class. Read status, error_code, and error_message from the caught value.
Retry 5xx responses or timeouts by defaultNoPass a retryCondition to contentstack.stack() that returns true for them.
See the real status of a 401 while retries are onNoSet retryOnError: false on the stack.