Contentstack

View as Markdown

Contentstack

Creates an instance of `Contentstack`.

NameTypeDescription
CachePolicy Contentstack.CachePolicy

CachePolicy contains different cache policies constants.

Stack

Initialize an instance of ‘Stack’

NameTypeDescription
api_key (required)string

Stack API key

delivery_tokenstring

Stack Delivery token.

environmentstring

Stack Environment name.

regionContentstackRegion | string

DB region for Stack. You can choose from six regions namely, NA, EU, Azure NA, Azure EU, GCP NA, GCP EU, and AWS AU.

branchstring

Name of the branch you want to fetch data from

live_previewobject

Live preview configuration.

fetchOptions.debugboolean

Optional, to enable debug logs set to true.

Default: false
fetchOptions.logHandlerfunction

A log handler function to process given log messages & errors.

fetchOptions.agentHttpProxyAgent
fetchOptions.timeoutnumber

Set timeout for the request.

fetchOptions.retryLimitnumber

The number of retries before failure.

Default: 5
fetchOptions.retryDelaynumber

The number of ms to use for operation retries.

Default: 300ms
fetchOptions.retryConditionfunction

A function to determine if the error can be retried.

Default: Retry is on status codes 408, 429
fetchOptions.retryDelayOptions.basenumber

The base number of milliseconds to use in the exponential backoff for operation retries.

fetchOptions.retryDelayOptions.customBackoffnumber

A custom function that accepts a retry count and error and returns the amount of time to delay in milliseconds.

Initialize Stack:

import Contentstack from 'contentstack';

const Stack = Contentstack.Stack({ api_key: 'api_key', delivery_token: 'delivery_token', environment: 'environment' });

To set the European, Azure North American, Azure European, GCP North America region or GCP Europe, refer to the code below:

import Contentstack from 'contentstack';

const Stack = new Contentstack({ 'api_key': "api_key", 'delivery_token': "delivery_token", 'environment': "environment", "region": Contentstack.Region.<<add_your_region>>})

For Setting the Branch for a Region.

import Contentstack from 'contentstack';

const Stack = Contentstack.Stack({ api_key: 'api_key', delivery_token: 'delivery_token', environment: 'environment', region: Contentstack.Region.<<add_your_region>>, host: '<<add_your_host_URL>>', branch: 'branch')

Proxy Configuration

const HttpProxyAgent = require("http-proxy-agent");

const proxyAgent = new HttpProxyAgent("http://proxyurl/");

const Stack = Contentstack.Stack({ 

    api_key: 'api_key', 

    delivery_token: 'delivery_token', 

    environment: 'environment',

    fetchOptions: {

       agent: proxyAgent

    }

});

Here are a few examples of how you can add a username and password to HttpProxyAgent.

  • You can pass it in the URL:
var proxyAgent = new HttpsProxyAgent('https://username:[email protected]');
  • You can set it in the auth option:
var proxyOpts = url.parse('https://your-proxy.com');

proxyOpts.auth = 'username:password';

var proxyAgent = new HttpsProxyAgent(proxyOpts);
  • You can even set the HTTP header manually:
var proxyOpts = url.parse('https://your-proxy.com');

proxyOpts.headers = {

  'Proxy-Authentication': 'Basic ' + new Buffer('username:password').toString('base64')

};

var proxyAgent = new HttpsProxyAgent(proxyOpts);

FetchOptions Retry Parameters

This section explains how the Contentstack JavaScript SDK uses the fetchOptions parameter to retry failed requests based on configurable rules.

This improves reliability by retrying failed requests caused by network issues, timeouts, or temporary server errors.

Click to enlarge

Retry Logic Flow:

  1. Initial Request: The SDK sends the HTTP request.
  2. Evaluate Response: If status is 200 and response.ok is true, resolve with data.
  3. Check Retry Conditions: If the request fails, check if the error meets retry conditions.
  4. Decide to Retry: Evaluate retryCondition function (default: status 408, 429).
  5. Check Retry Limit: Verify if retry attempts remain (retryLimit > 0).
  6. Calculate Retry Delay: Calculate wait time using one of the following methods:
    1. retryDelay (fixed delay)
    2. retryDelayOptions.base * retryCount (linear backoff)
    3. retryDelayOptions.customBackoff (retryCount, error) (custom logic)
  7. Wait Before Retry: Pause execution for the calculated delay.
  8. Attempt Retry: Recursively call fetchRetry with a decremented limit.
  9. Exit with Final Error: If all retries are exhausted, reject with final error.

Code Snippet:

const stack = Contentstack.Stack({
  api_key: 'your_api_key',
  delivery_token: 'your_delivery_token',
  environment: 'your_environment',
  fetchOptions: {
    retryLimit: 5, // Number of retries before failing the request.
    retryDelay: 100,  // Fallback delay (in ms) if retryDelayOptions are not configured.

    // A custom function to determine whether the error qualifies for a retry.
    retryCondition: (error) => { 
      // Retry on network errors, timeouts, rate limits, and server errors.
      return [408, 429, 500, 502, 503, 504].includes(error.status);
    },
    retryDelayOptions: {
      // Base multiplier for exponential backoff. The delay becomes base * retryCount.
      base: 1000,  // 1st retry: 1000ms, 2nd retry: 2000ms, 3rd retry: 3000ms, etc.

      // Use either base or customBackoff.
      // Defines a custom function that calculates delay for each retry attempt.
      customBackoff: (retryCount, error) => {
        // Exponential backoff with jitter.
        const baseDelay = Math.pow(2, retryCount) * 1000;
        const jitter = Math.random() * 1000;
        return baseDelay + jitter;
      }
    }
  }
});

Plugins

When creating custom plugins, through this request, you can pass the details of your custom plugins. This facilitates their utilization in subsequent requests when retrieving details.

// custom class for plugin

class CrossStackPlugin {

  onRequest (stack, request) {

    // request modifications

    return request

  }

  async onResponse (stack, request, response, data) {

    // response modifications here

    return response

  }

}


const Stack = Contentstack.Stack({

  api_key,

  delivery_token,

  environment,

  plugins: [

    new CrossStackPlugin(),

    new Livepreview()

  ]

});