Contentstack

View as Markdown

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.

NameTypeRequiredDefaultDescription
apiKeystringYesNot applicableAPI key of the stack.
deliveryTokenstringYesNot applicableDelivery token for the environment.
environmentstringYesNot applicableEnvironment to read published content from.

Request location. Decides the base URL of every request.

NameTypeRequiredDefaultDescription
regionRegion | stringNoRegion.USRegion that hosts the stack. Selects the delivery host.
hoststringNoThe delivery host of regionCustom delivery host. Overrides region.
portnumberNo443Port in the request URL.
insecurebooleanNofalseSends requests over http instead of https.
versionstringNo'v3'API version segment of the URL.
basePathstringNo''Path between the port and the version.
endpointstringNoundefinedFull base URL. Overrides every option above.
baseURLstringNoundefinedFull base URL. Overrides endpoint.
defaultHostnamestringNoThe host the SDK resolvesInternal. Use host instead.

Request content. Sent with every request.

NameTypeRequiredDefaultDescription
branchstringNoAPI defaultBranch to read content from.
localestringNoAPI defaultLocale for every request.
early_accessstring[]NoundefinedEarly access features to turn on.
headersAxiosRequestHeadersNo{}Extra headers for every request.
paramsanyNo{}Extra query parameters for every request.

Retry and timeout. The Class-Level Notes below give the attempt counts.

NameTypeRequiredDefaultDescription
retryOnErrorbooleanNotrueTurns automatic retries on or off.
retryLimitnumberNo5Sets the retry budget for each request.
retryDelaynumberNo300Milliseconds between retries.
retryDelayOptions.basenumberYesNot applicableRequired by the type when you set retryDelayOptions. The SDK does not read it.
retryDelayOptions.customBackoff() => numberYesNot applicableReturns the delay in milliseconds. Replaces retryDelay.
retryCondition(error: any) => booleanNoundefinedRetries other failures when it returns true.
timeoutnumberNo30000Milliseconds before a request times out.

Caching. Off unless you set cacheOptions.

NameTypeRequiredDefaultDescription
cacheOptions.policyPolicyYesNot applicableCache strategy for every request.
cacheOptions.persistenceStorePersistenceStoreNoundefinedStore for cached responses. Required unless the policy is IGNORE_CACHE.
cacheOptions.maxAgenumberNoundefinedLifetime in milliseconds. The SDK passes it to the store.

Live preview. Off unless you set live_preview.

NameTypeRequiredDefaultDescription
live_preview.enablebooleanYesNot applicableTurns live preview on.
live_preview.hoststringNoundefinedPreview host. Required once the stack holds a preview hash.
live_preview.preview_tokenstringNoundefinedPreview token for the stack.
live_preview.live_previewstringNoundefinedPreview hash. The livePreviewQuery method sets it.
live_preview.management_tokenstringNoundefinedNo effect. Nothing in the SDK reads it.
live_preview.contentTypeUidstringNoundefinedNo effect on requests.
live_preview.entryUidanyNoundefinedNo effect on requests.
live_preview.include_applied_variantsbooleanNoundefinedNo effect on requests.

Plugins and logging.

NameTypeRequiredDefaultDescription
pluginsContentstackPlugin[]NoundefinedObjects that modify every request and response.
logHandler(level: string, data: any) => voidNoundefinedReceives the log records the SDK writes.
debugbooleanNoundefinedLogs every request and response through logHandler.

Transport. Axios settings inherited from @contentstack/core.

NameTypeRequiredDefaultDescription
proxyAxiosRequestConfig['proxy']NofalseProxy server for every request.
httpAgentAxiosRequestConfig['httpAgent']NoA keep-alive agent when the SDK loads through CommonJS require in Node.js, else falseAgent for http requests in Node.js.
httpsAgentAxiosRequestConfig['httpsAgent']NoA keep-alive agent when the SDK loads through CommonJS require in Node.js, else falseAgent for https requests in Node.js.
adapterAxiosRequestConfig['adapter']NoThe Axios default adapterFunction that sends each HTTP request.
onError(error: any) => anyNoundefinedRuns on every failed response, before retry handling.
accessTokenstringNoundefinedReplaces deliveryToken in the access_token header.

Inherited options with no effect. StackConfig accepts the options below without a compile error.

NameTypeRequiredDefaultDescription
maxContentLengthnumberNoInfinityNo effect. The SDK sends Infinity on every request.
maxBodyLengthnumberNoInfinityNo effect. The SDK sends Infinity on every request.
onRequest(value: AxiosRequestConfig) => AxiosRequestConfigNoundefinedNo effect. Use plugins instead.
requestLogger(request: AxiosRequestConfig | Error) => unknownNoundefinedNo effect. Use debug and logHandler instead.
responseLogger(response: AxiosResponse | Error) => unknownNoundefinedNo effect. Use debug and logHandler instead.

stack

stack creates a Stack from your credentials and options.

NameTypeDescription
config (required)StackConfig

Credentials and options for the stack.

Default: Not applicable
config.apiKey (required)string

API key of the stack.

Default: Not applicable
config.deliveryToken (required)string

Delivery token for the environment.

Default: Not applicable
config.environment (required)string

Environment to read published content from.

Default: Not applicable

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.com

Caching: 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);
}