Contentstack
Contentstack
contentstack is the default export of @contentstack/delivery-sdk and the entry point to the SDK. Its stack() function turns your credentials and options into a Stack, and every other class in the SDK comes from that Stack. Use this module to
- create a Stack for one stack, environment, and region
- set the retry, timeout, cache, live preview, and plugin behavior of every request that stack sends
- reach the @contentstack/utils helpers through contentstack.Utils
The following statement imports the module:
import contentstack from '@contentstack/delivery-sdk';
stack() takes one StackConfig object. The tables below group every option by what it controls. StackConfig extends the HttpClientParams type of @contentstack/core, so the last two tables cover the transport options it inherits from that package.
Credentials. Required on every stack.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| apiKey | string | Yes | Not applicable | API key of the stack. |
| deliveryToken | string | Yes | Not applicable | Delivery token for the environment. |
| environment | string | Yes | Not applicable | Environment to read published content from. |
Request location. Decides the base URL of every request.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| region | Region | string | No | Region.US | Region that hosts the stack. Selects the delivery host. |
| host | string | No | The delivery host of region | Custom delivery host. Overrides region. |
| port | number | No | 443 | Port in the request URL. |
| insecure | boolean | No | false | Sends requests over http instead of https. |
| version | string | No | 'v3' | API version segment of the URL. |
| basePath | string | No | '' | Path between the port and the version. |
| endpoint | string | No | undefined | Full base URL. Overrides every option above. |
| baseURL | string | No | undefined | Full base URL. Overrides endpoint. |
| defaultHostname | string | No | The host the SDK resolves | Internal. Use host instead. |
Request content. Sent with every request.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| branch | string | No | API default | Branch to read content from. |
| locale | string | No | API default | Locale for every request. |
| early_access | string[] | No | undefined | Early access features to turn on. |
| headers | AxiosRequestHeaders | No | {} | Extra headers for every request. |
| params | any | No | {} | Extra query parameters for every request. |
Retry and timeout. The Class-Level Notes below give the attempt counts.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| retryOnError | boolean | No | true | Turns automatic retries on or off. |
| retryLimit | number | No | 5 | Sets the retry budget for each request. |
| retryDelay | number | No | 300 | Milliseconds between retries. |
| retryDelayOptions.base | number | Yes | Not applicable | Required by the type when you set retryDelayOptions. The SDK does not read it. |
| retryDelayOptions.customBackoff | () => number | Yes | Not applicable | Returns the delay in milliseconds. Replaces retryDelay. |
| retryCondition | (error: any) => boolean | No | undefined | Retries other failures when it returns true. |
| timeout | number | No | 30000 | Milliseconds before a request times out. |
Caching. Off unless you set cacheOptions.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| cacheOptions.policy | Policy | Yes | Not applicable | Cache strategy for every request. |
| cacheOptions.persistenceStore | PersistenceStore | No | undefined | Store for cached responses. Required unless the policy is IGNORE_CACHE. |
| cacheOptions.maxAge | number | No | undefined | Lifetime in milliseconds. The SDK passes it to the store. |
Live preview. Off unless you set live_preview.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| live_preview.enable | boolean | Yes | Not applicable | Turns live preview on. |
| live_preview.host | string | No | undefined | Preview host. Required once the stack holds a preview hash. |
| live_preview.preview_token | string | No | undefined | Preview token for the stack. |
| live_preview.live_preview | string | No | undefined | Preview hash. The livePreviewQuery method sets it. |
| live_preview.management_token | string | No | undefined | No effect. Nothing in the SDK reads it. |
| live_preview.contentTypeUid | string | No | undefined | No effect on requests. |
| live_preview.entryUid | any | No | undefined | No effect on requests. |
| live_preview.include_applied_variants | boolean | No | undefined | No effect on requests. |
Plugins and logging.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| plugins | ContentstackPlugin[] | No | undefined | Objects that modify every request and response. |
| logHandler | (level: string, data: any) => void | No | undefined | Receives the log records the SDK writes. |
| debug | boolean | No | undefined | Logs every request and response through logHandler. |
Transport. Axios settings inherited from @contentstack/core.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| proxy | AxiosRequestConfig['proxy'] | No | false | Proxy server for every request. |
| httpAgent | AxiosRequestConfig['httpAgent'] | No | A keep-alive agent when the SDK loads through CommonJS require in Node.js, else false | Agent for http requests in Node.js. |
| httpsAgent | AxiosRequestConfig['httpsAgent'] | No | A keep-alive agent when the SDK loads through CommonJS require in Node.js, else false | Agent for https requests in Node.js. |
| adapter | AxiosRequestConfig['adapter'] | No | The Axios default adapter | Function that sends each HTTP request. |
| onError | (error: any) => any | No | undefined | Runs on every failed response, before retry handling. |
| accessToken | string | No | undefined | Replaces deliveryToken in the access_token header. |
Inherited options with no effect. StackConfig accepts the options below without a compile error.
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| maxContentLength | number | No | Infinity | No effect. The SDK sends Infinity on every request. |
| maxBodyLength | number | No | Infinity | No effect. The SDK sends Infinity on every request. |
| onRequest | (value: AxiosRequestConfig) => AxiosRequestConfig | No | undefined | No effect. Use plugins instead. |
| requestLogger | (request: AxiosRequestConfig | Error) => unknown | No | undefined | No effect. Use debug and logHandler instead. |
| responseLogger | (response: AxiosResponse | Error) => unknown | No | undefined | No effect. Use debug and logHandler instead. |
stack
stack creates a Stack from your credentials and options.
| Name | Type | Description |
|---|---|---|
| config (required) | StackConfig | Credentials and options for the stack. |
| config.apiKey (required) | string | API key of the stack. |
| config.deliveryToken (required) | string | Delivery token for the environment. |
| config.environment (required) | string | Environment to read published content from. |
Returns: Stack. The configured stack.
Validation
- stack throws an Error when apiKey, deliveryToken, or environment is missing or an empty string, because every request carries all three. It checks them in that order and stops at the first one that fails.
- Leaving out one of the three is a compile error, because StackConfig marks them required. An empty string compiles and throws at runtime.
- stack throws an Error when region names no known region and you set no host, because the SDK cannot resolve a delivery host.
- stack throws an Error when cacheOptions.policy is not Policy.IGNORE_CACHE and cacheOptions.persistenceStore is absent, because the cache has nowhere to store responses.
- stack runs no other check and sends no request. A wrong API key or delivery token surfaces on the first request. That request throws an APIError containing the HTTP status, the API error_code, and the error_message.
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. stack builds the HTTP client and makes no request.
- Each call builds an independent stack with its own HTTP client. Two stacks never share headers, cache settings, or live preview state.
- stack keeps a reference to the config object you pass and exposes it as stack.config. It writes the resolved delivery host into config.host, so the object holds eu-cdn.contentstack.com after a call with region: Region.EU.
- stack is available only through the default export. Call contentstack.stack(), because the package has no named stack export.
Example
Basic usage: create a stack and read one entry
import contentstack 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();
console.log(result);
} catch (error: any) {
// Thrown for API rejections and network failures
console.error('Request failed:', error.status, error.error_code, error.error_message);
}Region: point the stack at another data center
import contentstack, { Region } from '@contentstack/delivery-sdk';
const stack = contentstack.stack({
apiKey: '<API_KEY>',
deliveryToken: '<DELIVERY_TOKEN>',
environment: '<ENVIRONMENT>',
region: Region.EU,
});
// stack() resolves the host without sending a request.
console.log(stack.config.host); // eu-cdn.contentstack.comCaching: keep responses in an in-memory store
import contentstack, { Policy } from '@contentstack/delivery-sdk';
import type { PersistenceStore } from '@contentstack/delivery-sdk';
// A minimal store. @contentstack/persistence-plugin provides a full one.
class MemoryStore implements PersistenceStore {
private items = new Map<string, any>();
setItem(key: string, value: any): void {
this.items.set(key, value);
}
getItem(key: string): any {
return this.items.get(key);
}
}
const stack = contentstack.stack({
apiKey: '<API_KEY>',
deliveryToken: '<DELIVERY_TOKEN>',
environment: '<ENVIRONMENT>',
cacheOptions: {
policy: Policy.CACHE_ELSE_NETWORK,
persistenceStore: new MemoryStore(),
maxAge: 60000,
},
});
try {
const first = await stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch();
// The second call returns the cached entry without a request.
const second = await stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch();
console.log(JSON.stringify(first) === JSON.stringify(second));
} catch (error: any) {
console.error(error);
}Error handling: a missing credential
import contentstack from '@contentstack/delivery-sdk';
// An unset environment variable yields an empty string.
const environment = process.env.CONTENTSTACK_ENVIRONMENT ?? '';
try {
const stack = contentstack.stack({
apiKey: '<API_KEY>',
deliveryToken: '<DELIVERY_TOKEN>',
environment,
});
console.log('stack ready for', stack.config.environment);
} catch (error: any) {
// Fires when apiKey, deliveryToken, or environment is empty
console.error('Check the stack configuration:', error.message);
}