ContentstackClient

View as Markdown

ContentstackClient

ContentstackClient is the object that client returns. It holds the HTTP connection and the credentials of the JavaScript Management SDK, and every other object starts from it.

Use this class to

  • sign in with an email and password, and sign out
  • read the details of the signed-in user
  • open a stack, all your stacks, or an organization
  • start an Open Authorization (OAuth) sign-in

Class-Level Notes

Credentials belong to the client.

  • login stores the authtoken it receives as a default header of the client. Every later request of the client, and of every object it creates, sends that authtoken.
  • logout without an argument removes the authtoken from the client again.
  • client.stack({ api_key, management_token }) also stores the management token as a client default. The Stack page describes the effect.
  • To work as two users, or with two management tokens, create one client for each.

Rate limiting and retry.

  • This SDK retries a request that receives 429 automatically, with configurable delay and attempt limits.

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

Capability Matrix

CapabilitySupportedNotes / Alternative
Create or activate a user accountNoThe SDK has no method for these requests
Hold two authtokens on one clientNoCreate a separate client for each user

Class-Level Properties

PropertyTypeAccessDefaultDescription
axiosInstanceAxiosInstanceRead and writeThe instance that client() createsThe axios instance that sends every request of the client.
  • axiosInstance.defaults.headers contains the default headers, such as authtoken, authorization and the user agent. A change applies to every later request of the client.
  • axiosInstance.defaults.baseURL holds the base URL. client() builds it from the region, host or endpoint.
  • axiosInstance.oauth stores the tokens of the OAuthHandler objects of the client.

Method Index

Sign in and read the user. Available on every client.

Method NameReturnsDescription
loginThe API response with a notice and the signed-in user.Signs in and stores the authtoken.
logoutThe API response with a notice.Ends a session.
getUserThe signed-in user.Retrieves the signed-in user.

Open stacks, organizations and OAuth. Available on every client. These methods send no request.

Method NameReturnsDescription
stackA new stack object.Opens one stack, or all your stacks.
organizationA new organization object.Opens one organization, or all of them.
oauthA new OAuth handler.Starts an OAuth sign-in.

Class-Level Snippet

The snippet below signs in, prints the organizations of the user, and signs out.

import contentstack from '@contentstack/management'

const client = contentstack.client()

try {
  const session = await client.login({ email: '<EMAIL>', password: '<PASSWORD>' })
  console.log(session.notice)

  const result = await client.organization().fetchAll()
  result.items.forEach((organization) => console.log(organization.name))

  const response = await client.logout()
  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)
}

Methods

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

getUser

getUser retrieves the account details of the signed-in user, including the stacks the user owns and the stacks shared with the user. The following table lists its parameters.

NameTypeDescription
paramsobject

Query parameters, sent as given.

Default: {}

Returns: Promise<User>. The signed-in user.

Validation

  • There is no client-side validation.
  • The client needs an authtoken, from the authtoken option of client() or from login. Without one, the API rejects the request.
  • 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 one Get user request, GET /v3/user, with every key of params as a query parameter.
  • Resolves to a User object. The keys of the user object in the response, such as uid, email and first_name, are properties of the new object.
  • The User methods, such as update and getTasks, exist only when the user object of the response holds an authtoken. The User page describes the forms.

Example

Basic usage: 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.uid, user.email, user.first_name)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

Pass query parameters

import contentstack from '@contentstack/management'

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

try {
  const user = await client.getUser({ include_orgs: true })
  console.log(user.organizations)
} catch (error) {
  console.error(error.errorMessage)
}

login

login signs in to Contentstack with an email and password, and stores the authtoken it receives on the client. The following table lists its parameters.

NameTypeDescription
requestBody (required)LoginDetails

Sign-in details of the user.

Default: Not applicable
requestBody.email (required)string

Email address of the account.

Default: Not applicable
requestBody.password (required)string

Password of the account.

Default: Not applicable
requestBody.tfa_tokenstring

Current two-factor authentication code.

Default: undefined
requestBody.mfaSecretstring

Authenticator secret that the SDK turns into a code.

Default: undefined
paramsobject

Query parameters, sent as given.

Default: {}

Returns: Promise<LoginResponse>. The API response with a notice and the signed-in user.

Validation

  • There is no client-side validation of email or password. The API rejects a wrong or missing value.
  • 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.
  • For an account with two-factor authentication, a request without a code rejects with error code 294. The error also carries tfa_type.
  • login rejects with TypeError on a client where an Open Authorization (OAuth) token request already ran. The API creates the session first, but the token request removed the default header group that login writes to. Use a separate client for login.

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

Behavior

  • Sends one Log in to your account request, POST /v3/user-session, with the body { user: { email, password, tfa_token } } and params as query parameters.
  • With mfaSecret and no tfa_token, login generates the current time-based code from the secret with the otplib package and sends it as tfa_token. tfa_token wins when you pass both. The SDK never sends mfaSecret.
  • When the response holds an authtoken, login stores it as the client's default authtoken header. Every later request of the client sends it, until logout removes it.
  • On a client that you created with the authtoken option, requests keep sending that original token after login. Create the client without authtoken when you plan to call login.
  • Resolves to the response body. notice holds the message of the API, and user is a User object with the account details, the authtoken and methods such as update.

Example

Basic usage: sign in with an email and password

import contentstack from '@contentstack/management'

const client = contentstack.client()

try {
  const response = await client.login({ email: '<EMAIL>', password: '<PASSWORD>' })
  console.log(response.notice, response.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)
}

Sign in with a two-factor authentication code and include the organizations

import contentstack from '@contentstack/management'

const client = contentstack.client()

try {
  const response = await client.login(
    { email: '<EMAIL>', password: '<PASSWORD>', tfa_token: '<TFA_TOKEN>' },
    { include_orgs: true }
  )
  console.log(response.user.organizations.map((organization) => organization.name))
} catch (error) {
  console.error(error.errorMessage)
}

Sign in with an authenticator secret

import contentstack from '@contentstack/management'

const client = contentstack.client()

try {
  // The SDK generates the current code from the secret
  const response = await client.login({ email: '<EMAIL>', password: '<PASSWORD>', mfaSecret: '<MFA_SECRET>' })
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

logout

logout ends a Contentstack session, either the session of the client or the session of the authtoken you pass. The following table lists its parameters.

NameTypeDescription
authtokenstring

Authtoken of the session to end.

Default: undefined (ends the session of the client)

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

Validation

  • There is no client-side validation.
  • 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 one Log out of your account request, DELETE /v3/user-session.
  • Without authtoken, the request uses the authtoken of the client. After a successful response, logout removes the authtoken from the client, including a token from the authtoken option of client(). Later requests of the client send no authtoken.
  • With authtoken, the request sends that token instead, and the client keeps its own authtoken.
  • Resolves to the response body, which carries notice.
  • logout does not end an Open Authorization (OAuth) session. Use the logout method of the OAuth handler for that.

Example

Basic usage: end the session of the client

import contentstack from '@contentstack/management'

const client = contentstack.client()

try {
  await client.login({ email: '<EMAIL>', password: '<PASSWORD>' })
  const response = await client.logout()
  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)
}

End the session of another authtoken

import contentstack from '@contentstack/management'

const client = contentstack.client()

try {
  // The client keeps its own authtoken, if it has one
  const response = await client.logout('<AUTHTOKEN>')
  console.log(response.notice)
} catch (error) {
  console.error(error.errorMessage)
}

oauth

oauth creates an OAuthHandler that signs a user in to your app with Open Authorization (OAuth) and stores the tokens on this client. The following table lists its parameters.

NameTypeDescription
paramsobject

OAuth settings of your app.

Default: {}
params.appIdstring

UID of the app in Developer Hub.

Default: '6400aa06db64de001a31c8a9'
params.clientIdstring

OAuth client ID of the app.

Default: 'Ie0FEfTzlfAHL4xM'
params.redirectUristring

URL that receives the authorization code.

Default: 'http://localhost:8184'
params.clientSecretstring

OAuth client secret of the app.

Default: undefined (uses PKCE)
params.responseTypestring

Response type. The handler keeps it but sends it nowhere.

Default: 'code'
params.scopestring[]

OAuth scopes. The handler keeps them but sends them nowhere.

Default: Empty array

Returns: OAuthHandler. A new OAuth handler.

Validation

  • There is no client-side validation of the IDs or the redirect URI. A wrong value surfaces when the sign-in page or the token request rejects it.
  • Throws TypeError if scope is a string or null, because the handler joins the array with spaces. Pass an array, such as ['cm.labels.management:read'].
  • An invalid value surfaces as a rejected promise from the handler method you call next.

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

Behavior

  • Client-side only. oauth sends no request.
  • Without clientSecret, the handler uses Proof Key for Code Exchange (PKCE) and creates a code verifier now. With clientSecret, it sends the secret in the token request instead.
  • Without appId and clientId, the handler uses the app ID and client ID that the SDK sets as defaults. Pass the values of your own app.
  • The handler stores its tokens on this client, in client.axiosInstance.oauth.
  • The OAuthHandler page describes the sign-in flow and two known issues with the default headers and expired tokens.

Limitations

  • The handler keeps responseType and scope but sends them nowhere.
  • Every handler from the same client shares the stored tokens, and each oauth call overwrites the stored appId, clientId and redirectUri.

Example

Basic usage: build the sign-in URL for your app

import contentstack from '@contentstack/management'

const client = contentstack.client()
const oauthHandler = client.oauth({ appId: '<APP_ID>', clientId: '<CLIENT_ID>', redirectUri: '<REDIRECT_URI>' })

try {
  const url = await oauthHandler.authorize()
  console.log('Open this URL and sign in:', url)
} catch (error) {
  // authorize sends no request. It rejects only when the client has no app host.
  console.error(error.message)
}

All parameters: an app with a client secret

import contentstack from '@contentstack/management'

const client = contentstack.client({ region: 'eu' })
const oauthHandler = client.oauth({
  appId: '<APP_ID>',
  clientId: '<CLIENT_ID>',
  redirectUri: '<REDIRECT_URI>',
  clientSecret: '<CLIENT_SECRET>',
  responseType: 'code',
  scope: ['cm.labels.management:read', 'cm.extensions.management:read']
})

try {
  // With a client secret, the URL carries no PKCE challenge
  console.log(await oauthHandler.authorize())
} catch (error) {
  console.error(error.message)
}

organization

organization creates an Organization object for one organization, or for all the organizations of the user. The following table lists its parameters.

NameTypeDescription
uidstring

UID of the organization to open.

Default: null (returns the collection form)

Returns: Organization. A new organization object.

Validation

  • There is no client-side validation.
  • Methods that act on one organization, such as fetch and stacks, exist only on the object from organization('<ORGANIZATION_UID>'). On organization() they are undefined, and calling one throws TypeError. The collection form has only fetchAll.
  • Unlike the factory methods of a stack, organization('') returns the single-organization form with an empty UID, because the SDK checks only for null. Its requests then go to the path /organizations/ with no UID. Check the UID before you call organization.
  • 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. organization sends no request.
  • The organization requests need an authtoken. Use a client with the authtoken option, or call login first.
  • With a UID, the object has fetch, stacks, roles, teams and the invitation methods, for example. The Organization page lists every method of each form.

Example

Basic usage: fetch one organization

import contentstack from '@contentstack/management'

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

try {
  const organization = await client.organization('<ORGANIZATION_UID>').fetch()
  console.log(organization.name)
} catch (error) {
  // The API rejected the request. The error carries status, errorCode, errorMessage and errors.
  console.error(error.status, error.errorCode, error.errorMessage)
}

List every organization of the user

import contentstack from '@contentstack/management'

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

try {
  const result = await client.organization().fetchAll()
  result.items.forEach((organization) => console.log(organization.uid, organization.name))
} catch (error) {
  console.error(error.errorMessage)
}

stack

stack creates a Stack object for one stack, or for all the stacks you can access. The following table lists its parameters.

NameTypeDescription
paramsStackConfig

Stack options.

Default: {} (returns the collection form)
params.api_keystring

API key of the stack to open.

Default: undefined (returns the collection form)
params.management_tokenstring

Management token for the stack's requests.

Default: undefined
params.branch_uidstring

Branch UID or alias for every module request.

Default: undefined (the API uses the main branch)
params.organization_uidstring

Organization for create and query in the collection form.

Default: undefined

Returns: Stack. A new stack object.

Validation

  • There is no client-side validation. A missing or empty api_key returns the collection form without an error.
  • Methods that act on one stack, such as fetch and contentType, exist only on the object from stack({ api_key: '<API_KEY>' }). On stack() they are undefined, and calling one throws TypeError. The collection form has create and query instead.
  • 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. stack sends no request.
  • With api_key, the object sends the api_key header with every request, and the branch header when you pass branch_uid.
  • management_token becomes the default authorization header of the client, not of this stack. Every request of the client sends it from then on. The Stack page describes the effect of a second token.
  • Without api_key, the object has create and query. With organization_uid, create sends the organization_uid header, and query lists only the stacks of that organization.
  • The Stack requests that create, fetch, update and list stacks need an authtoken. Use a client with the authtoken option, or call login first, which signs in with an email and password and stores the authtoken on the client.

Example

Basic usage: open a stack with a management token

import contentstack from '@contentstack/management'

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

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

Work on a branch

import contentstack from '@contentstack/management'

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

try {
  const entry = await stack.contentType('<CONTENT_TYPE_UID>').entry('<ENTRY_UID>').fetch()
  console.log(entry.title)
} catch (error) {
  console.error(error.errorMessage)
}

List and create stacks in an organization

import contentstack from '@contentstack/management'

const client = contentstack.client({ authtoken: '<AUTHTOKEN>' })
const stacks = client.stack({ organization_uid: '<ORGANIZATION_UID>' })

try {
  const result = await stacks.query().find()
  console.log(result.items.map((stack) => stack.name))

  const created = await stacks.create({ stack: { name: 'docs-test-stack', master_locale: 'en-us' } })
  console.log(created.api_key)
} catch (error) {
  console.error(error.errorMessage)
}