Skip to main content
Contentstack MCP profile hub is in general availability!

App SDK v2 essentials

•
6 min read

The App SDK is the only way your app talks to Contentstack. It tells you where you are running, gives you the open entry or field, proxies API calls, and stores configuration per installation. Version 2 is the current major line, and @contentstack/app-sdk 2.4.1 is the latest release at the time of writing.

This chapter covers the calls you will use in almost every app.

What you'll learn

  • How to initialize the SDK once and share it

  • How to tell which location your code is running in

  • How to read and write field and entry data

  • How to size the iframe

  • How installation data and secrets are stored

  • How to call Contentstack APIs through the SDK

Initialize once

Install the package if you did not start from the boilerplate:

npm install @contentstack/app-sdk

Then initialize it:

import ContentstackAppSDK from "@contentstack/app-sdk";

const appSdk = await ContentstackAppSDK.init();

init() does a handshake with the parent frame and returns a UiLocation object. The call is memoized, so calling it again returns the same instance. In React, call it in one provider and share the result through context. The boilerplate does this in MarketplaceAppProvider and exposes a useAppSdk() hook.

Handle rejection. init() rejects when the page has no parent window, and times out after 10 seconds when the parent never answers. Render an error state instead of a blank screen:

ContentstackAppSDK.init()
  .then((sdk) => setAppSdk(sdk))
  .catch(() => setFailed(true));

Know where you are

Contentstack concept: appSdk.location holds one object per location type. Only the object for the current location is set. The others are null.

const location = appSdk.getCurrentLocation();

if (location === "FIELD") {
  const customField = appSdk.location.CustomField;
  // customField.field, customField.entry, customField.frame
}

if (location === "WIDGET") {
  const sidebar = appSdk.location.SidebarWidget;
  // sidebar.entry, sidebar.stack
}

The values come from the SDK's LocationType enum: APP_CONFIG_WIDGET, FIELD, WIDGET (entry sidebar), DASHBOARD, ASSET_SIDEBAR_WIDGET, FULL_PAGE_LOCATION, FIELD_MODIFIER_LOCATION, CONTENT_TYPE_SIDEBAR_WIDGET, GLOBAL_FULL_PAGE_LOCATION and RTE. If you are coming from v1, note that v2 renamed EntryFieldLocation to FieldModifierLocation and FullscreenAppWidget to FullPage.

You also get identifiers you will need later: appSdk.ids contains apiKey, appUID, installationUID, locationUID, orgUID and userUID.

Read and write field data

A custom field reads its current value with getData() and writes with setData():

const field = appSdk.location.CustomField?.field;

const current = field?.getData() ?? {};

await field?.setData({ ...current, score: 82, checkedAt: new Date().toISOString() });

setData() updates the value in the editor. The entry still has to be saved before the value is stored. The shape must match the field's data_type from the manifest. A json field takes an object, a text field takes a string.

From 2.4.0, setData() throws a ValidationError when the host rejects the value. Wrap writes in try/catch, and subscribe to field.onError() for errors that happen after the write is applied.

React to the entry

The entry is available in custom fields, entry sidebars and field modifiers:

const entry = appSdk.location.SidebarWidget?.entry;

const saved = entry?.getData();
const draft = await entry?.getDraftData();

entry?.onChange((data) => runChecks(data));
entry?.onSave((data) => runChecks(data));

getData() returns the saved entry. getDraftData() returns what the editor has not saved yet. Use onChange for live feedback and onSave for anything expensive. Subscribe to events instead of polling the entry on a timer.

Size the frame

Custom field and dashboard frames do not resize themselves by default. If your field grows, the editor sees a scrollbar or a clipped UI. Turn on auto-resizing, or set a height yourself:

const frame = appSdk.location.CustomField?.frame;

frame?.enableAutoResizing();
// or a fixed height
await frame?.updateHeight(320);

Store installation data

Contentstack concept: Each installation has two configuration buckets. configuration is readable by your app in every location. serverConfiguration is encrypted, never sent to a UI location, and only read by the proxy and your own backend.

The app configuration location reads and writes both:

const installation = appSdk.location.AppConfigWidget?.installation;

const data = await installation?.getInstallationData();

const payload: Record<string, unknown> = {
  configuration: { ...data?.configuration, region: "eu", hasApiKey: true },
};

// Only send serverConfiguration when the user typed a new key.
if (apiKeyInput) {
  payload.serverConfiguration = { apiKey: apiKeyInput };
}

await installation?.setInstallationData(payload as any);

installation?.setValidity(Boolean(apiKeyInput || data?.configuration.hasApiKey), {
  message: "Add an API key",
});

setValidity(false) blocks the Save button on the config screen, with an optional message. The SDK types mark both buckets as required, hence the cast: leaving serverConfiguration out is what keeps a stored key in place.

Two rules keep this safe:

  • Secrets go in serverConfiguration, never in configuration. Put a non-secret flag such as hasApiKey: true in configuration so other locations can check that a key exists.

  • Each bucket you send replaces what is stored. Sending serverConfiguration: {} wipes the saved secret. Only send serverConfiguration when the user sets or clears a secret, and send one full snapshot per change instead of one call per keystroke.

Call Contentstack APIs

appSdk.api() is a fetch-style call that the host executes with the app's granted permissions:

const res = await appSdk.api(`${appSdk.endpoints.CMA}/v3/content_types`, {
  method: "GET",
});

if (!res.ok) {
  throw new Error(`Request failed with ${res.status}`);
}

const { content_types } = await res.json();

api() resolves on HTTP errors. A 401 or 404 comes back as a Response, and a transport failure becomes a Response with status 500. Always check res.ok. Log appSdk.endpoints once in your app to confirm the base URL for your region.

For heavier work, pass the SDK's adapter to the Management SDK so every request goes through the host:

import { client } from "@contentstack/management";

const cma = client({ adapter: appSdk.createAdapter() });

The SDK also exposes appSdk.stack with helpers such as getContentTypes(), getEnvironments() and search().

Where people get confused

appSdk.store looks like a place for settings, but it is per location and backed by browser storage. Use installation data for anything that must survive across users and browsers.

The app config location only exists while someone is configuring the app. Other locations read configuration with appSdk.getConfig(), not with getInstallationData().

Key takeaways

  • Call ContentstackAppSDK.init() once, share it through context, and handle rejection.

  • Branch on appSdk.getCurrentLocation(). Only the matching appSdk.location.* object is set.

  • field.setData() is saved with the entry and throws ValidationError on rejection from 2.4.0.

  • Call frame.enableAutoResizing() in custom fields that change height.

  • Keep secrets in serverConfiguration, and never send it as {} unless you mean to delete it.

  • Check res.ok after appSdk.api(). It does not throw on HTTP errors.

Next, OAuth and machine-to-machine apps explains which token your calls use and how to reach third-party APIs.

Frequently asked questions

  • Why does ContentstackAppSDK.init() fail when I open my app URL directly?

    The SDK only resolves inside a Contentstack host iframe. Opened as a top-level page it rejects, so open the app through an installed location instead.

  • When is a value from field.setData() saved?

    When the editor saves the entry. setData() updates the field in the editor, and the entry save persists it.

  • Where do I store an API key for my app?

    In serverConfiguration through setInstallationData(). It is encrypted at rest and never sent to a UI location.