Contentstack

View as Markdown

Contentstack

Contentstack is the module that you import from @contentstack/management. Its client function creates the client that sends every Content Management API (CMA) request of the JavaScript Management SDK.

Use this module to

  • create a client for one region, host or custom endpoint
  • give the client an authtoken, an authorization header or extra headers
  • set the timeout, concurrency and retry behavior of every request
  • add plugins and a log handler

Class-Level Notes

Import.

  • Import the default export: import contentstack from '@contentstack/management'. Then call contentstack.client().

One client, one set of settings.

  • Each client() call builds its own HTTP client, with its own headers, credentials, request queue and retry settings. Clients do not share any state.
  • The options apply to every request of the client and of every object it creates, such as stacks, organizations and the Open Authorization (OAuth) handler.

Rate limiting and retry.

  • This SDK retries a request that receives 429 automatically, with configurable delay and attempt limits.
  • It also retries network failures and 5xx responses up to three times by default.
  • The client method lists every retry option with its default, and describes the two retry layers.

Method Index

Method NameReturnsDescription
clientA new client.Creates a client with your options.

Class-Level Snippet

The snippet below creates a client for the EU region with an authtoken, then lists the stacks the user can access.

import contentstack from '@contentstack/management'

const client = contentstack.client({ region: 'eu', authtoken: '<AUTHTOKEN>', timeout: 60000 })

try {
  const result = await client.stack().query().find()
  result.items.forEach((stack) => console.log(stack.name, stack.api_key))
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Methods

Each method of the Contentstack module has its own section below, with its parameters, validation rules, behavior, and examples.

client

client creates a ContentstackClient with the host, credentials, timeout and retry settings that you pass. The following table lists its parameters.

NameTypeDescription
paramsContentstackConfig

Options for the client.

Default: {}
params.regionstring

Region whose API host the client uses.

Default: 'na'
params.hoststring

API host name, optionally with :port.

Default: Host of region
params.endpointstring

Full base URL for every request.

Default: undefined (built from host, port and version)
params.portnumber

Port of the API host.

Default: 443
params.versionstring

API version in the request path.

Default: 'v3'
params.basePathstring

Path between the host and the API version.

Default: ''
params.insecureboolean

Sends requests over HTTP instead of HTTPS.

Default: false
params.authtokenstring

User authtoken sent with every request.

Default: undefined
params.authorizationstring

authorization header, such as an Open Authorization (OAuth) bearer token.

Default: undefined
params.early_accessstring[]

Early access features to turn on.

Default: undefined
params.headersobject

Extra headers sent with every request.

Default: {}
params.applicationstring

App name and version for User-Agent.

Default: undefined
params.integrationstring

Integration name and version for User-Agent.

Default: undefined
params.featurestring

Feature name for User-Agent.

Default: undefined
params.timeoutnumber

Request timeout in milliseconds.

Default: 30000
params.maxRequestsnumber

Maximum number of requests that run at once.

Default: 5
params.delayMsnumber

Wait in milliseconds before each request starts.

Default: null (no wait)
params.retryOnErrorboolean

Retries failed requests that retryCondition accepts.

Default: true
params.retryConditionfunction

Returns true to retry a failed request.

Default: Retries a 429 response
params.retryLimitnumber

Maximum number of error retries per request.

Default: 5
params.retryDelaynumber

Wait in milliseconds between error retries.

Default: 300
params.retryDelayOptions.basenumber

Base wait that the SDK multiplies by the retry count.

Default: undefined
params.retryDelayOptions.customBackofffunction

Returns the wait for each error retry.

Default: undefined
params.refreshTokenfunction

Returns new credentials after a 401 response.

Default: undefined
params.retryOnNetworkFailureboolean

Turns the network retry layer on or off.

Default: true
params.retryOnDnsFailureboolean

Retries a failed DNS lookup.

Default: true
params.retryOnSocketFailureboolean

Retries a dropped or refused connection.

Default: true
params.retryOnHttpServerErrorboolean

Retries a 5xx response.

Default: true
params.maxNetworkRetriesnumber

Maximum number of network retries per request.

Default: 3
params.networkRetryDelaynumber

Base wait in milliseconds for network retries.

Default: 100
params.networkBackoffStrategystring

'exponential' or 'fixed' wait between network retries.

Default: 'exponential'
params.logHandlerfunction

Receives retry messages and errors.

Default: Prints to the console
params.pluginsPlugin[]

Hooks that change requests and responses.

Default: undefined (no plugins)
params.proxyProxyConfig | false

Proxy server for every request.

Default: false (no proxy from environment variables)
params.maxContentLengthnumber

Maximum response size in bytes.

Default: -1 (no limit)
params.maxBodyLengthnumber

Maximum request body size in bytes.

Default: -1 (no limit)

Returns: ContentstackClient. A new client.

Validation

  • There is no credential check. client accepts a missing or wrong token, and the error surfaces on the first request as an API rejection.
  • Throws Error if region is not a known region ID or alias, because client looks up the host when it builds the client.
  • Throws TypeError if region is not a string, or early_access is not an array, because client calls string and array methods on them.
  • Throws Error for the out-of-range values below, because the request queue checks its limits when the client starts:
    • maxRequests, retryLimit or maxNetworkRetries below 0.
    • retryDelay from 1 to 299.
    • networkRetryDelay from 1 to 49.
  • The checks skip 0. The client accepts retryLimit: 0 and retryDelay: 0. It also accepts maxRequests: 0, and then no request of the client ever starts.
  • host takes a bare host name, such as eu-api.contentstack.com. A value with a protocol, such as https://eu-api.contentstack.com, builds an invalid base URL without an error, and every request fails.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Additional Resource Refer to Content Management API Errors for the full error code list.

Behavior

  • Client-side only. client sends no request.

Host and URL.

  • client resolves region with the region list of the @contentstack/utils package. The lookup is case-insensitive and accepts the aliases in the table below.
RegionAliasesHost
na (default)us, aws-na, aws_naapi.contentstack.io
euaws-eu, aws_eueu-api.contentstack.com
auaws-au, aws_auau-api.contentstack.com
azure-naazure_naazure-na-api.contentstack.com
azure-euazure_euazure-eu-api.contentstack.com
gcp-nagcp_nagcp-na-api.contentstack.com
gcp-eugcp_eugcp-eu-api.contentstack.com
  • The base URL is https://<host>:<port><basePath>/<version>, for example https://api.contentstack.io:443/v3.
  • host replaces the region host, also when you pass region. A port in host replaces port.
  • endpoint replaces the whole base URL. The SDK adds no version to it, so include the version path, for example https://eu-api.contentstack.com/v3.
  • The OAuthHandler class derives its sign-in and token hosts from the API host.

Headers and credentials.

  • Every request sends X-User-Agent: contentstack-management-javascript/1.32.0 and a User-Agent header. User-Agent lists application, integration and feature when you set them, then the SDK version, the platform and the operating system.
  • authtoken, authorization and early_access become default headers of the client. They, and the two agent headers, replace keys with the same name in headers.
  • early_access sends the names joined by commas in the early_access header. The SDK also sends them in an x-header-ea header.
  • When you set both authorization and authtoken, requests send only authorization.
  • Other request options of the axios HTTP library, such as httpsAgent, pass through to every request.

Error retry.

  • When retryOnError is true and retryCondition(error) returns true, the SDK sends the request again. The default condition accepts only a 429 response.
  • The SDK retries up to retryLimit times, so a request runs at most retryLimit + 1 times.
  • The wait before each retry comes from the first setting below that applies:
    • retryDelayOptions.customBackoff(retryCount, error). A negative return value stops the retries, and 0 retries without waiting.
    • retryDelayOptions.base multiplied by the retry count, so the wait grows by the same amount each time.
    • retryDelay.
  • retryOnError: false turns off this layer, and the refreshToken handling below.

Network retry.

  • This layer runs before the error retry. It retries a failed DNS lookup (EAI_AGAIN), the socket errors ECONNRESET, ETIMEDOUT, ECONNREFUSED, ENOTFOUND and EHOSTUNREACH, a timeout, and any 5xx response.
  • It retries up to maxNetworkRetries times. The wait starts at networkRetryDelay, and 'exponential' doubles it for each retry. The SDK adds up to 100 ms of random jitter.
  • retryOnNetworkFailure: false turns off the whole layer. The other three retryOn options turn off one kind of failure each.
  • After the last network retry, the promise rejects with an Error that carries code, originalError and retryAttempts, not the API error fields.
  • A request that times out counts as a network failure. With retryOnNetworkFailure: false, it rejects with status 408 instead.

Token refresh.

  • With refreshToken, a 401 response pauses the request queue and calls refreshToken(). The function returns a promise that resolves to { authorization } or { authtoken }.
  • It stores the new value as the client default and sends the request again, up to retryLimit times.
  • It does not refresh for the API error codes 294 (two-factor authentication required) and 161.

Logs and plugins.

  • logHandler(level, data) receives 'warning' with each retry message and 'error' with final network failures and plugin errors. Your function replaces the default, which prints to the console.
  • Each plugin needs both an onRequest and an onResponse function. The SDK drops a plugin that lacks one of them.
  • onRequest(request) runs before each request and returns the request to send. onResponse(response) receives each response, or the error of a failed request, and returns the value to pass on. A hook that returns undefined keeps the original value.
  • An exception inside a hook goes to logHandler, and the request continues.

Sizes and proxy.

  • maxContentLength and maxBodyLength have no SDK default. The axios default -1 sets no limit.
  • With proxy: false, the default, the client does not read the HTTP_PROXY and HTTPS_PROXY environment variables. Pass a ProxyConfig object with host and port to use a proxy.

Example

Basic usage: create a client with an authtoken and read the signed-in user

import contentstack from '@contentstack/management'

const client = contentstack.client({ authtoken: '<AUTHTOKEN>' })

try {
  const user = await client.getUser()
  console.log(user.email)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Choose the region, host or endpoint

import contentstack from '@contentstack/management'

// A region ID or alias
const euClient = contentstack.client({ region: 'eu' })
// Prints https://eu-api.contentstack.com:443/{api-version}. Each request replaces {api-version} with the version.
console.log(euClient.axiosInstance.defaults.baseURL)

// A host with every URL part spelled out
const hostClient = contentstack.client({
  host: 'azure-na-api.contentstack.com',
  port: 443,
  basePath: '',
  version: 'v3',
  insecure: false
})
console.log(hostClient.axiosInstance.defaults.baseURL)

// A complete base URL, including the version
const endpointClient = contentstack.client({ endpoint: 'https://gcp-eu-api.contentstack.com/v3' })
console.log(endpointClient.axiosInstance.defaults.baseURL)

Credentials, headers and the User-Agent

import contentstack from '@contentstack/management'

const client = contentstack.client({
  authorization: 'Bearer <ACCESS_TOKEN>',
  early_access: ['taxonomy', 'variants'],
  headers: { 'x-request-source': 'docs-test-script' },
  application: 'docs-test-app/1.0.0',
  integration: 'node-script/1.0.0',
  feature: 'content-sync'
})

try {
  const result = await client.organization().fetchAll()
  console.log(result.items.length)
} catch (error) {
  console.error(error.errorMessage)
}

Timeout, concurrency and retry settings

import contentstack from '@contentstack/management'

const client = contentstack.client({
  authtoken: '<AUTHTOKEN>',
  timeout: 60000,
  maxRequests: 3,
  delayMs: 200,
  retryOnError: true,
  // Retry rate-limited and conflicting requests
  retryCondition: (error) => Boolean(error.response && [409, 429].includes(error.response.status)),
  retryLimit: 3,
  retryDelay: 500,
  retryDelayOptions: { base: 1000 },
  retryOnNetworkFailure: true,
  retryOnDnsFailure: true,
  retryOnSocketFailure: true,
  retryOnHttpServerError: false,
  maxNetworkRetries: 2,
  networkRetryDelay: 250,
  networkBackoffStrategy: 'fixed'
})

try {
  const user = await client.getUser()
  console.log(user.uid)
} catch (error) {
  console.error(error.errorMessage)
}

Stop retrying with a custom backoff

import contentstack from '@contentstack/management'

const client = contentstack.client({
  authtoken: '<AUTHTOKEN>',
  retryDelayOptions: {
    // Wait 500 ms for the first two retries, then stop
    customBackoff: (retryCount, error) => (retryCount <= 2 ? 500 : -1)
  }
})

try {
  const user = await client.getUser()
  console.log(user.uid)
} catch (error) {
  console.error(error.errorMessage)
}

Refresh an expired authtoken

import contentstack from '@contentstack/management'

const sessionClient = contentstack.client()

const client = contentstack.client({
  authtoken: '<AUTHTOKEN>',
  // Called after a 401 response. Resolve to { authtoken } or { authorization }.
  refreshToken: async () => {
    const response = await sessionClient.login({ email: '<EMAIL>', password: '<PASSWORD>' })
    return { authtoken: response.user.authtoken }
  }
})

try {
  const user = await client.getUser()
  console.log(user.email)
} catch (error) {
  console.error(error.errorMessage)
}

Log handler, plugins, proxy and size limits

import contentstack from '@contentstack/management'

const client = contentstack.client({
  authtoken: '<AUTHTOKEN>',
  logHandler: (level, data) => {
    const text = typeof data === 'string' ? data : (data && data.message) || ''
    console.log(`[${level}] ${text}`)
  },
  plugins: [
    {
      onRequest: (request) => {
        request.headers['x-request-id'] = 'docs-123'
        return request
      },
      onResponse: (response) => response
    }
  ],
  proxy: { host: '127.0.0.1', port: 8080, protocol: 'http' },
  maxContentLength: 1024 ** 3,
  maxBodyLength: 10 * 1024 ** 2
})

try {
  const user = await client.getUser()
  console.log(user.uid)
} catch (error) {
  console.error(error.errorMessage)
}