TypeScript Delivery SDK API Reference
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.
| Class | Role | Accessed via |
|---|---|---|
| Contentstack | The default export, which creates a stack from your credentials and options. | import contentstack from '@contentstack/delivery-sdk' |
| Stack | One stack and environment, and the start of every chain. | contentstack.stack({...}) |
Read content types, entries, and global fields.
| Class | Role | Accessed via |
|---|---|---|
| ContentType | One content type and its schema. | stack.contentType(uid) |
| ContentType Collection | The list of content types in a stack, as a ContentTypeQuery. | stack.contentType() |
| Entry | One entry as an Entry, or the entries of one content type as Entries. | contentType.entry(uid) |
| Query | A filtered list of entries or assets. | entries.query() |
| Global Fields | One global field as a GlobalField, or the list as a GlobalFieldQuery. | stack.globalField(uid) |
| Pagination | The paging methods that the list classes inherit. | query.paginate() |
Read assets and images.
| Class | Role | Accessed via |
|---|---|---|
| Asset | One published asset. | stack.asset(uid) |
| Asset Collection | The list of published assets, as an AssetQuery. | stack.asset() |
| ImageTransform | A builder of Image Delivery API parameters for an image URL. It sends no request. | new ImageTransform() |
Read taxonomies.
| Class | Role | Accessed via |
|---|---|---|
| Taxonomy | One published taxonomy, or the list of published taxonomies. | stack.taxonomy(uid) |
| Term | One published term of a taxonomy. | taxonomy.term(uid) |
| TermQuery | The 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
| Task | Start here | Class |
|---|---|---|
| Fetch one entry by UID | fetch | Entry |
| Filter entries by a field value | where | Query |
| Filter entries by a taxonomy term and the terms below it | where | Query |
| Return referenced entries in full | includeReference | Entry |
| Read an entry in another locale | locale | Entry |
| Read an entry variant | variants | Entry |
| Paginate a list of entries, assets, or taxonomies | Pagination | Pagination |
| List the published assets in the stack | find | Asset Collection |
| Read one asset with its image dimensions | includeDimension | Asset |
| Read the schema of a content type | fetch | ContentType |
| Sync all published content, then only what changed | sync | Stack |
| List the terms of a taxonomy | find | TermQuery |
| Set the region, retries, cache, or live preview | Contentstack | Contentstack |
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
| Concern | Behavior | Default when unset |
|---|---|---|
| Authentication | contentstack.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 surfacing | Every 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 endpoints | Pass 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. |
| Branches | Pass branch to contentstack.stack(). The SDK sends it as the branch header on every request. | No branch header, so the API applies its default. |
| Locales | Pass 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 retry | This 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. |
| Timeouts | Pass 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 configuration | Pass a proxy object to route requests through a proxy. With the default, the SDK ignores the HTTP_PROXY and HTTPS_PROXY environment variables. | false. |
| Caching | Set 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 preview | Set 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 UIDs | Known 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
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Query entries of several content types in one request | No | Each 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 call | No | Loop 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 instanceof | No | The package does not export the class. Read status, error_code, and error_message from the caught value. |
| Retry 5xx responses or timeouts by default | No | Pass a retryCondition to contentstack.stack() that returns true for them. |
| See the real status of a 401 while retries are on | No | Set retryOnError: false on the stack. |