Environment

View as Markdown

Environment

A publishing environment is a destination for published content, such as development, staging or production, with a base URL for each locale. The Environment class manages environments through the Content Management API (CMA). Use this class to

  • add an environment to a stack
  • list the environments of a stack, or read one by name
  • rename an environment or change its URLs
  • delete an environment

Call the environment method of the Stack class to get an object.

Instance State

  • Call stack.environment() without a name to work with the collection, for example create and query.
  • Call stack.environment('<ENVIRONMENT>') to work with one environment, for example fetch and update.
  • Each form has only its own methods. A method of the other form is undefined, and calling it throws TypeError.

The Method Index below lists the full set for each form.

Warning stack.environment('') returns the collection form, because the SDK treats an empty string as no name. Check the name before you build the object.

Class-Level Notes

The SDK identifies environments by name.

  • stack.environment() takes the environment name, not its UID. The SDK stores it as name and puts it in the URL path of fetch, update and delete, as the Environment requests expect.
  • The URL path keeps the name that the object held when the SDK built it. update relies on this to rename an environment.

Environment objects from responses.

  • create, fetch, update and the find() call of query resolve to Environment objects in the one-environment form, with fetch, update and delete.

Headers.

Rate limiting and retry.

  • This SDK automatically retries on 429 with configurable delay and attempt limits.

Additional Resource For more information on the retry options and their defaults, refer to the Contentstack documentation.

Capability Matrix

CapabilitySupportedNotes / Alternative
Read an environment by its UIDNoPass the environment name to stack.environment().
Update fields without fetching firstNoupdate sends the properties of the object. Call fetch, change the result, then call update.

Method Index

Work with the environment collection. Available on stack.environment().

Method NameReturnsDescription
createThe new environment.Adds an environment to the stack.
queryA query for environments, sent when you call find(), findOne() or count().Lists the environments of the stack.

Work with one environment. Available on stack.environment('<ENVIRONMENT>').

Method NameReturnsDescription
fetchThe requested environment.Reads one environment.
updateThe updated environment.Saves changes to the environment.
deleteThe API response with a notice.Deletes the environment.

Set request headers. Available on both forms.

Method NameReturnsDescription
addHeaderThe same environment object, for chaining.Adds one request header.
addHeaderDictThe same environment object, for chaining.Adds several request headers.
removeHeaderThe same environment object, for chaining.Removes one request header.

Class-Level Snippet

The snippet below lists the environments of a stack and prints the base URL of each locale.

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environments = await stack.environment().query().find()
  for (const environment of environments.items) {
    for (const entry of environment.urls || []) {
      console.log(environment.name, entry.locale, entry.url)
    }
  }
} 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 Environment class has its own section below, with its parameters, validation rules, behavior, and examples.

addHeader

addHeader adds one header to the requests that this environment object sends.

NameTypeDescription
key (required)string

Header name, for example x-request-id.

Default: Not applicable
value (required)string

Header value to send.

Default: Not applicable

Returns: Environment. The same environment object, for chaining.

Validation

  • There is no client-side validation. A null or undefined key leaves the headers unchanged, and addHeader returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeader sends no request.
  • The first header change on this object copies the headers that it inherited. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers.
  • The Environment objects that create, fetch and query return start with the headers of this object.
  • A key that the object already holds gets the new value.

Example

Basic usage: tag the requests of one environment object

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const target = stack.environment('<ENVIRONMENT>').addHeader('x-request-id', 'docs-123')
console.log(target.stackHeaders['x-request-id'])

addHeaderDict

addHeaderDict adds several headers at once to the requests that this environment object sends.

NameTypeDescription
headerDict (required)object

Header names and values to add.

Default: Not applicable

Returns: Environment. The same environment object, for chaining.

Validation

  • There is no client-side validation. A null value, or a value that is not an object, leaves the headers unchanged, and addHeaderDict returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. addHeaderDict sends no request.
  • addHeaderDict copies every key of headerDict into the header map of this object. A key that the object already holds gets the new value.
  • The first header change on this object copies the headers that it inherited. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers.
  • The Environment objects that create, fetch and query return start with the headers of this object.

Example

Basic usage: add a request ID and a trace ID

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const target = stack.environment('<ENVIRONMENT>').addHeaderDict({ 'x-request-id': 'docs-123', 'x-trace-id': 'trace-456' })
console.log(target.stackHeaders['x-request-id'], target.stackHeaders['x-trace-id'])

create

create adds a publishing environment to the stack.

NameTypeDescription
data (required){ environment: EnvironmentData }

Request body, with the environment under the environment key.

Default: Not applicable
data.environment.name (required)string

Name of the environment. Requests for one environment use it in the URL.

Default: Not applicable
data.environment.urlsServerDetail[]

Base URL of the site for each locale.

Default: API default
data.environment.urls[].locale (required)string

Locale code, for example en-us.

Default: Not applicable
data.environment.urls[].url (required)string

Base URL for that locale.

Default: Not applicable
data.environment.serversServer[]

Deployment servers, each with a name.

Default: API default
data.environment.deploy_contentboolean

Deploys published content to the servers.

Default: API default
paramobject

Query parameters, sent as given.

Default: undefined (sends no extra query parameters)

Returns: Promise<Environment>. The new environment.

Validation

  • There is no client-side validation. create sends data as given and does not check its keys.
  • create exists only on stack.environment(). On stack.environment('<ENVIRONMENT>') it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends POST /v3/environments with data as the JSON body and param as query parameters, as Add an environment describes.
  • The SDK does not wrap data. Put the environment under the environment key yourself.
  • Resolves to an Environment object that the SDK builds from the environment key of the response, with fetch, update and delete.

Example

Basic usage: add a staging environment with one URL

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const data = {
  environment: {
    name: 'docs-test-staging',
    urls: [{ locale: '<LOCALE>', url: 'https://staging.example.com' }],
    servers: [],
    deploy_content: false
  }
}

try {
  const environment = await stack.environment().create(data)
  console.log(environment.name, environment.uid)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: add an environment with two locales and a deployment server

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const data = {
  environment: {
    name: 'docs-test-production',
    urls: [
      { locale: 'en-us', url: 'https://www.example.com' },
      { locale: 'fr-fr', url: 'https://www.example.com/fr' }
    ],
    servers: [{ name: 'default' }],
    deploy_content: true
  }
}

try {
  // The second argument holds query parameters. The API lists none for this request.
  const environment = await stack.environment().create(data, {})
  console.log(environment.name, environment.urls)
} catch (error) {
  console.error(error.errorMessage)
}

delete

delete deletes the environment whose name you passed to stack.environment('<ENVIRONMENT>').

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<Response>. The API response with a notice.

Warning Deleting an environment removes it from the stack permanently. You cannot undo this. Create it again with the create method if you need it.

Validation

  • There is no client-side validation.
  • delete exists only on stack.environment('<ENVIRONMENT>') and on the Environment objects that requests return. On stack.environment() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends DELETE /v3/environments/{environment_name} with every key of param as a query parameter, as Delete environment describes. The API reference lists no query parameters for this request.
  • Resolves to the response body as a plain object, with the API message in notice.

Example

Basic usage: delete an environment

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const response = await stack.environment('<ENVIRONMENT>').delete()
  console.log(response.notice)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: pass query parameters

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  // delete sends every key of the object as a query parameter. The API lists none for this request.
  const response = await stack.environment('<ENVIRONMENT>').delete({})
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

fetch

fetch retrieves the environment whose name you passed to stack.environment('<ENVIRONMENT>').

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<Environment>. The requested environment.

Validation

  • There is no client-side validation.
  • fetch exists only on stack.environment('<ENVIRONMENT>'). On stack.environment() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends GET /v3/environments/{environment_name} with every key of param as a query parameter, as Get a single environment describes. The API reference lists no query parameters for this request.
  • The SDK puts the environment name in the URL path, so the name you pass must match the name of the environment.
  • Resolves to a new Environment object that the SDK builds from the environment key of the response, with fetch, update and delete.

Example

Basic usage: read one environment

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environment = await stack.environment('<ENVIRONMENT>').fetch()
  console.log(environment.name, environment.uid, environment.urls)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: pass query parameters

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  // fetch sends every key of the object as a query parameter. The API lists none for this request.
  const environment = await stack.environment('<ENVIRONMENT>').fetch({})
  console.log(environment.name)
} catch (error) {
  console.error(error.errorMessage)
}

query

query builds a request that lists the environments of the stack. It sends nothing until you call find(), findOne() or count() on the result.

NameTypeDescription
paramsobject

Query parameters for the list request.

Default: {}
params.queryobject

Filter condition, sent as JSON.

Default: API default
params.include_countboolean

Adds the total environment count to the response.

Default: API default
params.ascstring

Field UID to sort by, ascending.

Default: API default
params.descstring

Field UID to sort by, descending.

Default: API default

Returns: Query. A query for environments, sent when you call find(), findOne() or count().

Validation

  • There is no client-side validation.
  • query exists only on stack.environment(). On stack.environment('<ENVIRONMENT>') it is undefined, and calling it throws TypeError.
  • 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

  • query sends no request. find(), findOne() and count() on the returned object each send GET /v3/environments, as Get all environments describes.
  • The SDK sends params.query as a JSON string in the query parameter, and every other key of params as its own query parameter.
  • find() resolves to a collection whose items are Environment objects, each with fetch, update and delete. With include_count: true, the collection also has count.
  • See the Query class for find(), findOne() and count().

Example

Basic usage: list the environments of a stack

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environments = await stack.environment().query().find()
  for (const environment of environments.items) {
    console.log(environment.name, environment.uid)
  }
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: find one environment by name, sorted, with the total count

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environments = await stack.environment()
    .query({ query: { name: '<ENVIRONMENT>' }, include_count: true, asc: 'name' })
    .find()
  console.log(environments.count, environments.items.map((environment) => environment.name))
} catch (error) {
  console.error(error.errorMessage)
}

Edge case: sort the environments by name, descending

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environments = await stack.environment().query({ desc: 'name' }).find()
  console.log(environments.items.map((environment) => environment.name))
} catch (error) {
  console.error(error.errorMessage)
}

removeHeader

removeHeader removes one header from the requests that this environment object sends.

NameTypeDescription
key (required)string

Name of the header to remove.

Default: Not applicable

Returns: Environment. The same environment object, for chaining.

Validation

  • There is no client-side validation. A null or undefined key, or a key that the object does not hold, leaves the headers unchanged, and removeHeader returns the same object.
  • An invalid value surfaces as a rejected promise from the request method you call next.

Behavior

  • Client-side only. removeHeader sends no request.
  • The first header change on this object copies the headers that it inherited. The change then applies to this object only, not to the stack or to other objects that the same stack creates.
  • Every request method of this object sends its headers.
  • The Environment objects that create, fetch and query return start with the headers of this object.
  • removeHeader can remove a header that the object inherited from the stack, such as branch. The stack and its other objects keep that header.
  • Do not remove api_key. Without it, the API cannot tell which stack the request is for.

Example

Basic usage: drop a header that you added earlier

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

const target = stack.environment('<ENVIRONMENT>')
  .addHeaderDict({ 'x-request-id': 'docs-123', 'x-trace-id': 'trace-456' })
  .removeHeader('x-trace-id')
console.log('x-trace-id' in target.stackHeaders) // false

update

update saves the changes that you made to the properties of this environment object, such as its name or URLs.

NameTypeDescription
paramobject

Query parameters, sent as given.

Default: {}

Returns: Promise<Environment>. The updated environment.

Validation

  • There is no client-side validation.
  • update exists only on stack.environment('<ENVIRONMENT>') and on the Environment objects that requests return. On stack.environment() it is undefined, and calling it throws TypeError.
  • The returned promise rejects with an Error when the API rejects the request. The error carries status, statusText, errorMessage, errorCode and errors from the API response.

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

Behavior

  • Sends PUT /v3/environments/{environment_name} with every key of param as a query parameter, as Update environment describes.
  • The body is { environment: { ... } }, built from the properties of this object. The SDK leaves out uid, created_at, created_by, updated_at, updated_by, deleted_at, org_uid, api_key and its own internal properties.
  • The URL path uses the name that the object held when the SDK built it. To rename an environment, set name on the object and call update. The request goes to the old name and sends the new one in the body.
  • Call fetch first and change the result. An object from stack.environment('<ENVIRONMENT>') holds only the name, so update on it sends only the name.
  • Resolves to a new Environment object that the SDK builds from the environment key of the response.

Example

Basic usage: rename an environment

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environment = await stack.environment('<ENVIRONMENT>').fetch()
  environment.name = 'docs-test-preview'
  const updated = await environment.update()
  console.log(updated.name)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

All parameters: change the URLs and pass query parameters

import contentstack from '@contentstack/management'

const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })

try {
  const environment = await stack.environment('<ENVIRONMENT>').fetch()
  environment.urls = [{ locale: 'en-us', url: 'https://preview.example.com' }]
  // update sends every key of the object as a query parameter. The API lists none for this request.
  const updated = await environment.update({})
  console.log(updated.urls)
} catch (error) {
  console.error(error.errorMessage)
}