GlobalField
GlobalField
A Global field is a reusable field, or group of fields, that you define once and add to many content types. The GlobalField class manages the Global fields of one stack through the Content Management API (CMA). Use this class to
- list, create and import Global fields
- read, update and delete one Global field
- choose the API version and the branch that the requests use
Call the globalField method of the Stack class to get an object.
Instance State
- Call stack.globalField() without a UID to work with the collection, for example create and query.
- Call stack.globalField('<GLOBAL_FIELD_UID>') to work with one Global field, for example fetch and update.
- Pass an options object as the first argument, as in stack.globalField({ api_version: '3.2' }), to get the collection form with those options.
- Each form has only its own request methods. fetch is undefined on stack.globalField(), and create is undefined on stack.globalField('<GLOBAL_FIELD_UID>'), so calling the wrong one throws TypeError.
Warning stack.globalField('') returns the collection form, because the SDK treats an empty string as no UID. Check the UID before you build the object.
Class-Level Notes
API version and branch headers. stack.globalField(uidOrOptions, option) sets two headers on every object it returns:
- api_version: '3.0' by default. option.api_version replaces it, for example stack.globalField('<GLOBAL_FIELD_UID>', { api_version: '3.2' }).
- branch: the branch of the stack (branch_uid), else the branch header of the client, else 'main'. option.branch replaces it.
- When the first argument is an object, the SDK reads it as option and returns the collection form.
The api_version header after a response.
- After a create, fetch or update resolves, the object that sent the request and the object that the method returns no longer send api_version. The branch header stays.
- To send api_version again, call addHeader, for example globalField.addHeader('api_version', '3.2'), before the next request.
Headers.
- Every request sends the headers of this object. Change them for this object only with addHeader, addHeaderDict and removeHeader.
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
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Export a Global field | No | Read it with fetch, which returns the same schema |
| Keep api_version on an object after a response | No | Call addHeader before each request that needs it |
| Import from a file in a browser | No | import reads a file path with Node.js fs. Use create with the schema object instead |
Method Index
Work with the collection. Available on stack.globalField().
| Method Name | Returns | Description |
|---|---|---|
| query | A query for Global fields, sent when you call find(), findOne() or count(). | Builds a Global field query. |
| create | The new Global field. | Creates a Global field. |
| import | The imported Global field. | Imports a Global field from a JSON file. |
Work with one Global field. Available on stack.globalField('<GLOBAL_FIELD_UID>').
| Method Name | Returns | Description |
|---|---|---|
| fetch | The requested Global field. | Retrieves one Global field. |
| update | The updated Global field. | Saves the fields of this object. |
| delete | The API response with a notice. | Deletes the Global field. |
Set request headers. Available on both forms.
| Method Name | Returns | Description |
|---|---|---|
| addHeader | The same global field, for chaining. | Adds one request header. |
| addHeaderDict | The same global field, for chaining. | Adds several request headers. |
| removeHeader | The same global field, for chaining. | Removes one request header. |
Class-Level Snippet
The snippet below reads one Global field with API version 3.2 and prints the UIDs of its fields.
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const globalField = await stack.globalField('<GLOBAL_FIELD_UID>', { api_version: '3.2' }).fetch()
console.log(globalField.title, globalField.schema.map((field) => field.uid))
} 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 GlobalField class has its own section below, with its parameters, validation rules, behavior, and examples.
addHeader
addHeader adds one header to every request that this global field object sends.
| Name | Type | Description |
|---|---|---|
| key (required) | string | Header name, for example x-request-id. |
| value (required) | string | Header value to send. |
Returns: GlobalField. The same global field, 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 from the stack. 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. A key that the object already holds gets the new value.
- The headers of a global field object start with api_version and branch, which stack.globalField() sets. addHeader can replace either of them for this object.
Example
Basic usage: tag the requests of one global field object
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const globalField = stack.globalField('<GLOBAL_FIELD_UID>').addHeader('x-request-id', 'docs-123')
// Every request this object sends from now on carries the header
console.log(globalField.stackHeaders['x-request-id'])addHeaderDict
addHeaderDict adds several headers to every request that this global field object sends.
| Name | Type | Description |
|---|---|---|
| headerDict (required) | object | Header names and values to add. |
Returns: GlobalField. The same global field, 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.
- Copies every key of headerDict into the headers 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 from the stack. The change then applies to this object only.
Example
Basic usage: send two extra headers from one global field object
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const globalField = stack.globalField('<GLOBAL_FIELD_UID>')
.addHeaderDict({ 'x-request-id': 'docs-123', api_version: '3.2' })
// fetch(), update() and delete() on this object send both headers
console.log(globalField.stackHeaders)create
create creates a Global field in the stack from the schema you pass.
| Name | Type | Description |
|---|---|---|
| data (required) | object | Request body with the Global field under global_field. |
| data.global_field.title (required) | string | Display name of the Global field. |
| data.global_field.uid (required) | string | Unique ID of the Global field in the stack. |
| data.global_field.schema (required) | object[] | Field definitions of the Global field. |
| param | object | Query parameters, sent as given. |
| param.include_branch | boolean | Adds the _branch key to the response. |
Returns: Promise<GlobalField>. The new Global field.
Validation
- There is no client-side validation. create sends data as the JSON body as it is.
- create exists only on stack.globalField(). On stack.globalField('<GLOBAL_FIELD_UID>') 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/global_fields with data as the body and the api_version and branch headers of this object, as Create a global field describes.
- The API lets only the stack owner, administrators and developers create Global fields.
- Resolves to a new GlobalField object that holds the fields of the created Global field, with fetch, update and delete.
- After the promise resolves, this object and the returned object no longer send api_version. Call addHeader('api_version', '<value>') before the next request that needs it.
Example
Basic usage: create a Global field with two text fields
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const global_field = {
title: 'docs-test-seo',
uid: 'docs_test_seo',
schema: [
{ display_name: 'Meta title', uid: 'meta_title', data_type: 'text' },
{ display_name: 'Meta description', uid: 'meta_description', data_type: 'text' }
]
}
try {
const globalField = await stack.globalField().create({ global_field })
console.log(globalField.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: create a Global field on a branch with API version 3.2
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
const global_field = {
title: 'docs-test-author-card',
uid: 'docs_test_author_card',
schema: [
{ display_name: 'Name', uid: 'name', data_type: 'text' }
]
}
try {
const globalField = await stack.globalField({ api_version: '3.2', branch: '<BRANCH>' })
.create({ global_field }, { include_branch: true })
console.log(globalField.uid, globalField._branch)
} catch (error) {
console.error(error.errorMessage)
}delete
delete removes the Global field whose UID you passed to stack.globalField('<GLOBAL_FIELD_UID>') from the stack.
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
| param.force | boolean | Deletes a Global field that a content type uses. |
Returns: Promise<Response>. The API response with a notice.
Warning A successful delete removes the Global field, and you cannot undo it. With force: true, the API also deletes a Global field that content types use.
Validation
- There is no client-side validation.
- delete exists only on stack.globalField('<GLOBAL_FIELD_UID>') and on the objects that fetch, create, import and query().find() return. On stack.globalField() it is undefined, and calling it throws TypeError.
- The API rejects the request when a content type uses the Global field and you do not pass force: true, because the deletion changes that content type.
- 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/global_fields/{global_field_uid} with every key of param as a query parameter, as Delete global field describes.
- Resolves to the response body, which carries notice. When the API answers with an empty body, it resolves to { status, statusText } instead.
Example
Basic usage: delete a Global field that no content type uses
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.globalField('<GLOBAL_FIELD_UID>').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: force the deletion of a Global field in use
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.globalField('<GLOBAL_FIELD_UID>').delete({ force: true })
console.log(response.notice)
} catch (error) {
console.error(error.errorMessage)
}fetch
fetch retrieves the Global field whose UID you passed to stack.globalField('<GLOBAL_FIELD_UID>').
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
| param.version | number | Version of the Global field to read. |
| param.include_global_field_schema | boolean | Adds the schema of nested Global fields. |
| param.include_content_types | boolean | Adds the content types that use the Global field. |
| param.include_global_fields | boolean | Adds the Global fields that use the Global field. |
| param.include_branch | boolean | Adds the _branch key to the response. |
Returns: Promise<GlobalField>. The requested Global field.
Validation
- There is no client-side validation.
- fetch exists only on stack.globalField('<GLOBAL_FIELD_UID>'). On stack.globalField() 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/global_fields/{global_field_uid} with every key of param as a query parameter, and the api_version and branch headers of this object, as Get a single global field describes.
- Nested Global fields appear in the schema of the response.
- Resolves to a new GlobalField object that holds the Global field fields, with update and delete.
- After the promise resolves, this object and the returned object no longer send api_version. Call addHeader('api_version', '<value>') before the next request that needs it.
Example
Basic usage: read one Global field
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const globalField = await stack.globalField('<GLOBAL_FIELD_UID>').fetch()
console.log(globalField.title, globalField.schema.length)
} 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: read version 2 with its usage details on a branch
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const globalField = await stack.globalField('<GLOBAL_FIELD_UID>', { api_version: '3.2', branch: '<BRANCH>' })
.fetch({
version: 2,
include_global_field_schema: true,
include_content_types: true,
include_global_fields: true,
include_branch: true
})
console.log(globalField._version, globalField._branch)
} catch (error) {
console.error(error.errorMessage)
}import
import creates a Global field, or replaces one, from a JSON file of its schema.
| Name | Type | Description |
|---|---|---|
| data (required) | object | Holds the path of the file to upload. |
| data.global_field (required) | string | Path of the Global field JSON file. |
| params | object | Query parameters, sent as given. |
| params.overwrite | boolean | Replaces an existing Global field with the same UID. |
| params.include_branch | boolean | Adds the _branch key to the response. |
| headers | object | Extra headers. The SDK adds them to this object's headers. |
Returns: Promise<GlobalField>. The imported Global field.
Validation
- There is no client-side validation. The SDK does not check that the file exists before it sends the request.
- import exists only on stack.globalField(). On stack.globalField('<GLOBAL_FIELD_UID>') it is undefined, and calling it throws TypeError.
- Without data, the returned promise rejects with a TypeError, because the SDK reads data.global_field to build the upload.
- 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/global_fields/import as multipart/form-data, with the file in a field named global_field, as Import a global field describes.
- Reads the file with the Node.js fs module, so import runs only in Node.js.
- headers stays on this object, so later requests from the same stack.globalField() object also send it. The exception is api_version, which this object and the returned object no longer send after the promise resolves.
- Resolves to a new GlobalField object that holds the fields of the imported Global field.
Example
Basic usage: import a Global field from a file
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const globalField = await stack.globalField().import({ global_field: '<FILE_PATH>' })
console.log(globalField.uid, globalField.title)
} 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: replace an existing Global field with API version 3.2
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 globalField = await stack.globalField().import(
{ global_field: '<FILE_PATH>' },
{ overwrite: true, include_branch: true },
{ api_version: '3.2' }
)
console.log(globalField.uid, globalField._branch)
} catch (error) {
console.error(error.errorMessage)
}query
query builds a request for the Global fields of the stack. It sends nothing until you call a method of the returned query.
| Name | Type | Description |
|---|---|---|
| params | object | Query parameters for the request. |
| params.query | object | Condition on Global field fields, sent as JSON. |
| params.include_count | boolean | Adds the total number of Global fields. |
| params.include_global_field_schema | boolean | Adds the schema of nested Global fields. |
| params.include_content_types | boolean | Adds the content types that use each Global field. |
| params.include_global_fields | boolean | Adds the Global fields that use each Global field. |
| params.include_branch | boolean | Adds the _branch key to each Global field. |
| params.deleted | boolean | Returns only deleted Global fields. |
Returns: Query. A query for Global fields, sent when you call find(), findOne() or count().
Validation
- There is no client-side validation.
- query exists only on stack.globalField(). On stack.globalField('<GLOBAL_FIELD_UID>') 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
- Client-side only. query copies the headers of this object, including api_version and branch, and params, and returns a Query object.
- find and findOne send GET /v3/global_fields and resolve to GlobalField objects, as Get all global fields describes. count resolves to the response body.
- The SDK sends params.query as query=<JSON>, and every other key of params as a query parameter.
- Each GlobalField object in items carries the headers of the query, including api_version.
Example
Basic usage: list the Global fields 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 result = await stack.globalField().query().find()
for (const globalField of result.items) {
console.log(globalField.uid, globalField.title)
}
} 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 Global field by title with its usage details
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 result = await stack.globalField({ api_version: '3.2' })
.query({
query: { title: 'SEO' },
include_count: true,
include_global_field_schema: true,
include_content_types: true,
include_global_fields: true,
include_branch: true,
deleted: false
})
.find()
console.log(result.count)
for (const globalField of result.items) {
console.log(globalField.uid, globalField._branch)
}
} catch (error) {
console.error(error.errorMessage)
}removeHeader
removeHeader removes one header from the requests that this global field object sends.
| Name | Type | Description |
|---|---|---|
| key (required) | string | Name of the header to remove. |
Returns: GlobalField. The same global field, 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.
- An invalid value surfaces as a rejected promise from the request method you call next.
Behavior
- Client-side only. removeHeader sends no request.
- Removing a header that the object inherited from the stack first copies the inherited headers, so the stack and other objects keep the header.
- The SDK adds some headers at request time, for example the authorization header of the client. removeHeader cannot remove those.
Example
Basic usage: send requests from one global field object without the branch header
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>', branch_uid: '<BRANCH>' })
const globalField = stack.globalField('<GLOBAL_FIELD_UID>').removeHeader('branch')
// This object now works with the default branch
console.log(globalField.stackHeaders.branch)update
update saves the fields that this Global field object holds, such as title and schema, to the stack.
| Name | Type | Description |
|---|---|---|
| param | object | Query parameters, sent as given. |
| param.include_branch | boolean | Adds the _branch key to the response. |
Returns: Promise<GlobalField>. The updated Global field.
Validation
- There is no client-side validation.
- update exists only on stack.globalField('<GLOBAL_FIELD_UID>') and on the objects that fetch, create, import and query().find() return. On stack.globalField() 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/global_fields/{global_field_uid} with the body { global_field: <fields of this object> }, as Update a global field describes. The SDK leaves out uid, created_at, created_by, updated_at, updated_by and its own keys.
- The body holds only the fields this object has. Call fetch first, change the fields of the object it returns, and then call update.
- The object that fetch returns no longer sends api_version. Call addHeader('api_version', '<value>') on it before update when the request needs the header.
- Resolves to a new GlobalField object with the saved fields.
Example
Basic usage: rename a Global field
import contentstack from '@contentstack/management'
const client = contentstack.client()
const stack = client.stack({ api_key: '<API_KEY>', management_token: '<MANAGEMENT_TOKEN>' })
try {
const globalField = await stack.globalField('<GLOBAL_FIELD_UID>').fetch()
globalField.title = 'SEO settings'
const updated = await globalField.update()
console.log(updated.title)
} 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 a field with API version 3.2 and read the branch key
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 globalField = await stack.globalField('<GLOBAL_FIELD_UID>', { api_version: '3.2' }).fetch()
globalField.schema.push({ display_name: 'Keywords', uid: 'keywords', data_type: 'text' })
// fetch removed api_version from the returned object, so set it again
globalField.addHeader('api_version', '3.2')
const updated = await globalField.update({ include_branch: true })
console.log(updated.schema.length, updated._branch)
} catch (error) {
console.error(error.errorMessage)
}