---
title: "Extend Contentstack"
url: "https://developers.contentstack.com/paths/extend-contentstack"
type: "path_full"
level: "intermediate"
outcome: "Your own csdx plugin and a Developer Hub app running in your organization."
steps:
  - "https://developers.contentstack.com/blog/every-csdx-command-is-a-plugin"
  - "https://developers.contentstack.com/guides/write-your-own-csdx-plugin"
  - "https://developers.contentstack.com/guides/build-your-first-developer-hub-app"
  - "https://developers.contentstack.com/blog/five-developer-hub-gotchas-that-bite-on-day-two"
updated: "2026-11-15T11:47:32.377Z"
---

# Extend Contentstack

- **Level:** Intermediate
- **Steps:** 4
- **Overview:** https://developers.contentstack.com/paths/extend-contentstack.md

---

Go beyond the defaults. Learn how the CLI plugin system works, write your own csdx command, and build and ship a Developer Hub app.

**You'll end up with:** Your own csdx plugin and a Developer Hub app running in your organization.

## Table of Contents

1. Every csdx command is a plugin
2. Write your own csdx plugin
3. Build your first Developer Hub app
4. Five Developer Hub gotchas that bite on day two


---

## Step 1: Every csdx command is a plugin

- **Source:** https://developers.contentstack.com/blog/every-csdx-command-is-a-plugin
- **Checkpoint:** You know which plugins ship with csdx and how to install the rest.

- **Authors:** Tim Benniks
- **Published:** 2026-11-27T09:00:00.000Z
- **Updated:** 2026-11-15T10:56:38.159Z
- **Level:** Intermediate
- **Intent:** Learn
- **Tags:** cli, automation, sdk

---

The Contentstack CLI does almost nothing on its own. csdx is a small core built on [oclif](https://oclif.io), and every command you run, from auth:login to cm:stacks:export, comes from a plugin. Some plugins ship inside the CLI, some you install when you need them, and some you write yourself.

I like this setup a lot. Each plugin ships on its own schedule, and the official commands are built the same way you would build your own, so nothing stops you from adding the command your team is missing. In this post I walk through how plugins load in CLI 2.x, which ones are bundled, what changed from 1.x, and five recipes I use.

## The short version

- csdx plugins lists the plugins you installed or linked. csdx plugins --core adds the bundled ones.


- csdx plugins:install <npm-package> adds a plugin, csdx plugins:uninstall <name> removes it.


- csdx plugins:link <path> wires a local folder into the CLI while you develop a plugin.


- The CLI's own package.json decides what is bundled. Everything else is one install away.



## How csdx finds its commands

oclif plugins are npm packages with an oclif section in their package.json that points at a folder of compiled commands. The @contentstack/cli package lists the plugins it bundles in its own oclif.plugins array. When you run a command, oclif loads that list, then the plugins you installed, then the plugins you linked, and resolves the command ID against all of them.

flowchart LR  U["csdx cm:branches:diff"] --> Core["@contentstack/cli (oclif core)"]  Core --> B["Bundled plugins<br/>listed in oclif.plugins"]  Core --> I["User-installed plugins<br/>csdx plugins:install"]  Core --> L["Linked plugins<br/>csdx plugins:link"]  L -. "overrides" .-> I  L -. "overrides" .-> BLinked plugins win. If you link a local plugin that defines a command the CLI already has, your version runs instead. That is great for testing a fix to an official plugin, and it is also the first thing to check when a command suddenly behaves differently on one machine.

The plugin management commands come from @oclif/plugin-plugins, which is itself bundled:

```bash
csdx plugins                      # user-installed and linked plugins
csdx plugins --core               # include the bundled plugins
csdx plugins:install contentstack-cli-tsgen
csdx plugins:inspect contentstack-cli-tsgen
csdx plugins:update
csdx plugins:uninstall contentstack-cli-tsgen
csdx plugins:link ./my-plugin
csdx plugins:reset                # remove every user-installed and linked plugin
```

## What ships bundled in 2.x

This is the bundled set in @contentstack/cli 2.0.2, next to what each plugin is for:

Plugin package

Main commands

What it is for

@contentstack/cli-auth

auth:login, auth:logout, auth:tokens:add

Session login and saved token aliases

@contentstack/cli-config

config:set:region, config:set:base-branch

Region, proxy, rate limit and branch defaults

@contentstack/cli-cm-export

cm:stacks:export

Export a stack to disk

@contentstack/cli-cm-import

cm:stacks:import

Import an export into a stack

@contentstack/cli-cm-import-setup

cm:stacks:import-setup

Prepare UID mappings before an import

@contentstack/cli-cm-clone

cm:stacks:clone

Export and import in one step

@contentstack/cli-cm-seed

cm:stacks:seed

Seed a stack from a GitHub repo

@contentstack/cli-cm-bootstrap

cm:bootstrap

Start a starter app with a seeded stack

@contentstack/cli-cm-export-to-csv

cm:export-to-csv

Export entries or users to CSV

@contentstack/cli-migration

cm:stacks:migration

Run content model migration scripts

@contentstack/cli-cm-branches

cm:branches:diff, cm:branches:merge

Create, compare and merge branches

@contentstack/cli-audit

cm:stacks:audit, cm:stacks:audit:fix

Find and fix broken references in an export

@contentstack/cli-bulk-operations

cm:stacks:bulk-entries, cm:stacks:bulk-assets, cm:stacks:bulk-taxonomies

Bulk publish and unpublish

## What you install yourself

These official plugins are opt-in. Install them with csdx plugins:install <package>:

Plugin package

Commands

What it is for

@contentstack/cli-launch

launch, launch:deployments, launch:logs and more

Deploy and manage Launch projects

@contentstack/apps-cli

app:create, app:deploy, app:install

Developer Hub apps

contentstack-cli-tsgen

tsgen

TypeScript types from your content types

contentstack-cli-content-type

content-type:list, content-type:compare, content-type:diagram

Inspect, compare and draw content types

@contentstack/cli-cm-migrate-rte

cm:entries:migrate-html-rte

Move HTML RTE content to JSON RTE

@contentstack/cli-cm-export-query

cm:stacks:export-query

Export only what a query matches

@contentstack/cli-cm-regex-validate

cm:stacks:validate-regex

Check regex validations in your content types

@contentstack/cli-external-migrate

migrate:create, migrate:export, migrate:import

Migrate from another CMS, starting with Contentful

## What changed from 1.x

If you are coming from CLI 1.x, these are the changes that show up in daily use:

- Bulk publish became bulk operations. The old cm:bulk-publish commands are gone. The bundled bulk-operations plugin replaces them with cm:stacks:bulk-entries, cm:stacks:bulk-assets and cm:stacks:bulk-taxonomies, each driven by an --operation flag. Taxonomies are new territory for bulk publishing, and the commands support --dry-run, --retry-failed and --revert from a log folder.


- Launch and migrate-rte are opt-in. Both used to ship with the CLI. If you run csdx launch without the plugin, the CLI tells you it is now opt-in and prints the install command instead of a "command not found" error.


- tsgen moved in with the other official plugins. contentstack-cli-tsgen 5.x is developed alongside the rest and requires CLI 2.x. If you still have tsgen 4 installed, run csdx plugins:update or reinstall it.


- Launch has its own version line. The CLI and most plugins are on 2.x, while @contentstack/cli-launch continues on 1.x. That is fine: the version numbers of plugins are independent of the core.


- Node.js 22 is the minimum. @contentstack/cli 2.x declares node >= 22.



## Five recipes

All recipes assume you ran csdx config:set:region and csdx auth:login. Where a command takes -a, that is a management token alias you saved with csdx auth:tokens:add.

### Typed models with tsgen

Generate TypeScript interfaces from your content types so your front end breaks at compile time instead of in production:

```bash
csdx plugins:install contentstack-cli-tsgen
csdx auth:tokens:add --delivery -a my-delivery-token
csdx tsgen -a my-delivery-token --output ./types/contentstack.d.ts --include-system-fields
```

tsgen reads the schema with a delivery token alias, not a management token. Add --api-type graphql if your app queries GraphQL. This site does exactly this and keeps the generated file in the repo.

### Compare and merge branches

Before you merge a branch, look at what changed in the content model:

```bash
csdx cm:branches:diff -k <stack-api-key> --base-branch main --compare-branch feature-nav --module content-types --format detailed-text
csdx cm:branches:merge -k <stack-api-key> --base-branch main --compare-branch feature-nav --comment "New navigation model"
```

The merge creates a revert branch by default, so you have a way back. For the full workflow with aliases, read [Safe content model changes with branches and aliases](/guides/safe-content-model-changes-with-branches-and-aliases).

### Migration scripts

Content model changes belong in code. A migration script is a JavaScript module that receives a migration object:

```javascript
// migrations/01-add-summary.js
module.exports = ({ migration }) => {
  const article = migration.editContentType('article');
  article.createField('summary').display_name('Summary').data_type('text').mandatory(false);
};
```

```bash
csdx cm:stacks:migration -a my-management-token --branch feature-nav --file-path ./migrations/01-add-summary.js
```

Point --file-path at a folder and add --multiple to run every script in it. Run migrations against a branch first, then merge.

### Audit an export before you import it

cm:stacks:import already runs an audit fix unless you pass --skip-audit. I still run the audit on its own first, because it gives me a report to read before anything touches the target stack:

```bash
csdx cm:stacks:export -a source-token -d ./export
csdx cm:stacks:audit -d ./export --report-path ./audit --modules content-types entries
csdx cm:stacks:audit:fix -d ./export --report-path ./audit --copy-dir
```

--copy-dir writes the fixes to a copy, so your original export stays untouched. Then import the fixed copy.

### Draw and compare content types

The content-type plugin answers "what does this stack look like" faster than clicking through the UI:

```bash
csdx plugins:install contentstack-cli-content-type
csdx content-type:list -a my-management-token --order modified
csdx content-type:diagram -a my-management-token --output content-model.svg --direction landscape
csdx content-type:compare-remote --origin-stack <api-key-a> --remote-stack <api-key-b> --content-type page
```

The diagram is an SVG of every content type and its references. compare-remote is the quickest way I know to see why the same content type behaves differently in two stacks. --type dot gives you a Graphviz file instead, if you want to style it yourself.

## Write your own

The official plugins have no special access. They extend the same Command class from @contentstack/cli-command, get the region and session from the CLI, and call the Management API through the same client wrapper in @contentstack/cli-utilities. Anything you can script against Contentstack, you can turn into a csdx command your team installs with one line.

That is why I like this architecture so much. If a task comes up twice, make it a command. Start with [Write your own csdx plugin](/guides/write-your-own-csdx-plugin), which builds a read-only csdx stack:health command from scaffold to npm publish.



---

## Do this with AI

Install the dx-cli skill from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills). Then ask your agent:

> List the csdx plugins installed on my machine, mark which ones ship with CLI 2.x and which I added, and show the command to export only my content types.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### How do I see which csdx plugins are installed?

Run csdx plugins to list the plugins you installed or linked yourself, and csdx plugins --core to include the ones bundled with the CLI.

### Why does csdx launch say it is an opt-in plugin?

In CLI 2.x the Launch plugin no longer ships with the CLI. Install it with csdx plugins:install @contentstack/cli-launch and the launch commands come back.

### What replaced cm:bulk-publish in CLI 2.x?

The bulk-operations plugin, which ships bundled. It adds cm:stacks:bulk-entries, cm:stacks:bulk-assets and cm:stacks:bulk-taxonomies, each taking an --operation flag such as publish or unpublish.

### Can a linked plugin override a built-in command?

Yes. A plugin linked with csdx plugins:link takes priority over a user-installed or core plugin with the same command, which is handy for local development.


---

## Step 2: Write your own csdx plugin

- **Source:** https://developers.contentstack.com/guides/write-your-own-csdx-plugin
- **Checkpoint:** Your own read-only csdx command runs against your stack.

- **Authors:** Tim Benniks
- **Published:** 2026-12-02T09:00:00.000Z
- **Updated:** 2026-11-15T10:56:32.926Z
- **Level:** Advanced
- **Intent:** Build
- **Tags:** cli, automation, sdk

---

Every csdx command is an oclif plugin, including the official ones. That means you can package any script you keep running against Contentstack as a real command, with flags, help text, the user's existing login and region, and a one-line install. If you want the background on how the CLI loads plugins, read [Every csdx command is a plugin](/blog/every-csdx-command-is-a-plugin) first.

In this guide you build csdx stack:health. It reads every content type on a branch and prints a table with entry counts, unpublished entries, entries nobody touched in a year, and entries that are missing a value in a required field. It only reads, so you can run it against any stack.

## What you'll learn

- How a csdx plugin is structured and where the CLI looks for commands


- How to extend the Contentstack base Command class


- How to get an authenticated Management API client from the CLI session or a token alias


- How to print a table that supports sorting, filtering and CSV


- How to link, test and publish the plugin



## How the pieces fit together

A plugin is an npm package. Its package.json has an oclif section that points at a folder of compiled commands. The file path decides the command ID, so lib/commands/stack/health.js becomes csdx stack:health.

flowchart LR  CLI["csdx (oclif core)"] --> P["your plugin<br/>oclif.commands = ./lib/commands"]  P --> C["stack/health.js<br/>extends Command"]  C --> U["@contentstack/cli-utilities<br/>managementSDKClient, flags, cliux"]  U --> CMA["Content Management API<br/>this.cmaHost"]Two packages do the heavy lifting:

- @contentstack/cli-command exports the base Command. It extends the oclif command with this.region, this.cmaHost, this.cdaHost, this.email and this.getToken(alias).


- @contentstack/cli-utilities re-exports oclif's flags and Args, and adds managementSDKClient, cliux, CLITable, isAuthenticated and the Management SDK types.



Import from these two packages, not from @oclif/core directly. That keeps your plugin on the same oclif version as the CLI.

## Scaffold the plugin

Use the oclif generator, as the Contentstack docs recommend:

```bash
npx oclif generate csdx-plugin-stack-health
cd csdx-plugin-stack-health
npm install @contentstack/cli-command@~2.0.2 @contentstack/cli-utilities@~2.0.2
```

The generator asks for a module type, package name, binary name and a few more details. This guide uses CommonJS, which matches how the official plugins compile.

Then open package.json and set the oclif section. bin must be csdx so help output shows the right command, and commands must point at the compiled output, not at src:

```json
{
  "oclif": {
    "bin": "csdx",
    "commands": "./lib/commands",
    "topicSeparator": ":",
    "topics": {
      "stack": { "description": "Inspect a stack" }
    }
  },
  "files": ["/lib", "/oclif.manifest.json"],
  "scripts": {
    "build": "tsc -b",
    "prepack": "tsc -b && oclif manifest",
    "postpack": "rm -f oclif.manifest.json",
    "test": "mocha --require ts-node/register \"test/**/*.test.ts\""
  }
}
```

Make sure outDir in tsconfig.json matches. This is the config used for this guide:

```json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2022",
    "rootDir": "src",
    "outDir": "lib",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}
```

Delete the example hello command the generator created. You do not want it to show up in csdx --help.

## Keep the report logic separate

Put the checks in a plain function with no CLI or network code. That makes it trivial to test.

```typescript
// src/health.ts
export type FieldSchema = { uid: string; mandatory?: boolean }

export type EntryLike = {
  updated_at?: string
  publish_details?: unknown[]
  [field: string]: unknown
}

export type HealthRow = {
  content_type: string
  entries: number
  unpublished: number
  stale: number
  missing_required: number
}

const isEmpty = (value: unknown) =>
  value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)

export function summarize(
  contentTypeUid: string,
  schema: FieldSchema[],
  entries: EntryLike[],
  staleBefore: Date,
): HealthRow {
  const required = schema.filter((field) => field.mandatory).map((field) => field.uid)

  return {
    content_type: contentTypeUid,
    entries: entries.length,
    unpublished: entries.filter((entry) => !entry.publish_details?.length).length,
    stale: entries.filter((entry) => entry.updated_at && new Date(entry.updated_at) < staleBefore).length,
    missing_required: entries.filter((entry) => required.some((uid) => isEmpty(entry[uid]))).length,
  }
}
```

The "missing required" check finds a real problem. Contentstack enforces required fields when an entry is saved, so a gap usually means someone made a field required after entries already existed. Those entries fail validation the next time an editor opens and saves them.

## Write the command

Create src/commands/stack/health.ts. This is the whole command:

```typescript
import { Command } from '@contentstack/cli-command'
import {
  CLITable,
  ContentstackClient,
  ManagementStack,
  TableFlags,
  cliux,
  flags,
  isAuthenticated,
  managementSDKClient,
} from '@contentstack/cli-utilities'
import { EntryLike, FieldSchema, HealthRow, summarize } from '../../health'

const PAGE_SIZE = 100

export default class StackHealth extends Command {
  static description = 'Report entry counts, unpublished, stale and incomplete entries per content type (read-only)'

  static examples = [
    '$ csdx stack:health -k blt0123456789abcdef',
    '$ csdx stack:health -a my-token --branch development --stale-days 180',
    '$ csdx stack:health -a my-token --sort=-stale --csv',
  ]

  static flags = {
    'stack-api-key': flags.string({ char: 'k', description: 'API key of the stack', exclusive: ['alias'] }),
    alias: flags.string({ char: 'a', description: 'Alias of a management token added with csdx auth:tokens:add' }),
    branch: flags.string({ description: 'Branch to inspect', default: 'main' }),
    'stale-days': flags.integer({ description: 'Days without an update before an entry counts as stale', default: 365 }),
    ...CLITable.getTableFlags(),
  }

  async run(): Promise<void> {
    const { flags } = await this.parse(StackHealth)
    const stack = await this.getStack(flags.alias, flags['stack-api-key'], flags.branch)
    const staleBefore = new Date(Date.now() - flags['stale-days'] * 24 * 60 * 60 * 1000)

    const contentTypes = await this.fetchAll((skip) =>
      stack.contentType().query({ include_count: true, limit: PAGE_SIZE, skip }).find(),
    )

    const rows: HealthRow[] = []
    for (const contentType of contentTypes) {
      const entries = await this.fetchAll<EntryLike>((skip) =>
        stack
          .contentType(contentType.uid)
          .entry()
          .query({ include_count: true, include_publish_details: true, limit: PAGE_SIZE, skip })
          .find(),
      )
      rows.push(summarize(contentType.uid, contentType.schema as FieldSchema[], entries, staleBefore))
    }

    cliux.table(
      [
        { value: 'content_type', alias: 'Content type' },
        { value: 'entries', alias: 'Entries' },
        { value: 'unpublished', alias: 'Unpublished' },
        { value: 'stale', alias: `Stale (${flags['stale-days']}d)` },
        { value: 'missing_required', alias: 'Missing required' },
      ],
      rows,
      flags as TableFlags,
    )

    const total = rows.reduce((sum, row) => sum + row.entries, 0)
    this.log(`\n${rows.length} content types, ${total} entries on branch "${flags.branch}".`)
  }

  private async getStack(alias: string | undefined, apiKey: string | undefined, branch: string): Promise<ManagementStack> {
    if (alias) {
      const token = this.getToken(alias)
      const client: ContentstackClient = await managementSDKClient({
        host: this.cmaHost,
        management_token: token.token,
      })
      return client.stack({ api_key: token.apiKey, management_token: token.token, branch_uid: branch })
    }

    if (!apiKey) this.error('Pass --stack-api-key or --alias.', { exit: 2 })
    if (!isAuthenticated()) this.error('You are not logged in. Run csdx auth:login first.', { exit: 2 })

    const client: ContentstackClient = await managementSDKClient({ host: this.cmaHost })
    return client.stack({ api_key: apiKey, branch_uid: branch })
  }

  private async fetchAll<T>(page: (skip: number) => Promise<{ items: T[]; count: number }>): Promise<T[]> {
    const items: T[] = []
    let count = Infinity
    while (items.length < count) {
      const result = await page(items.length)
      items.push(...result.items)
      count = result.count
      if (result.items.length === 0) break
    }
    return items
  }
}
```

A few things in this command are worth calling out:

- this.cmaHost comes from the region the user set with csdx config:set:region. Never hard-code api.contentstack.io, or your plugin breaks for every team outside the default region.


- managementSDKClient returns a configured @contentstack/management client. It applies the user's proxy settings and retries 429 responses, so you do not need your own rate limit handling for a report like this.


- CLITable.getTableFlags() adds --columns, --sort, --filter, --csv and --no-truncate, and cliux.table applies them. You get the same table behavior as cm:stacks:audit for free.


- The flags -k, -a and --branch follow the naming the official plugins use. People already know them, so keep them.



## Where people get confused about auth

The command supports two ways in, and they behave differently.

Session auth is what you get after csdx auth:login. When you call managementSDKClient without a management token, the client uses the session, including basic auth tokens and OAuth access tokens that it refreshes for you. The user's role decides what the command can read.

Token aliases come from csdx auth:tokens:add --management. this.getToken(alias) returns the saved token with its token and apiKey, so the user does not have to pass the stack API key separately. A management token is scoped to a stack and to the branches it was created for, which makes it the better fit for CI.

If the user passes a delivery token alias by mistake, the Management API rejects the requests. A friendly check on token.type is a good first improvement once the basics work.

## Link and run it locally

Build, generate the manifest, and link the folder into your global csdx:

```bash
npm run build
npx oclif manifest
csdx plugins:link .
csdx stack:health --help
csdx stack:health -k <stack-api-key> --branch main --sort=-unpublished
```

You see a table with one row per content type, followed by a summary line with the number of content types and entries. If csdx says the command does not exist, check that lib/commands/stack/health.js exists and that oclif.commands points at ./lib/commands.

Linking does not rebuild anything. After every change, run npm run build and npx oclif manifest again. A linked plugin also overrides any user-installed or core command with the same ID, which is another reason to keep your commands under their own topic.

When you are done, remove the link with csdx plugins:uninstall csdx-plugin-stack-health.

## Test without a stack

oclif's test package, @oclif/test version 4, exports runCommand, captureOutput and runHook. The older chained test.stdout().command() style is gone. Test the report logic directly and use runCommand for flag handling:

```typescript
// test/health.test.ts
import { expect } from 'chai'
import { runCommand } from '@oclif/test'
import { summarize } from '../src/health'

describe('summarize', () => {
  it('counts unpublished, stale and incomplete entries', () => {
    const row = summarize(
      'article',
      [{ uid: 'title', mandatory: true }, { uid: 'summary', mandatory: true }],
      [
        { title: 'Fresh', summary: 'ok', updated_at: '2026-06-01', publish_details: [{ environment: 'production' }] },
        { title: 'Old draft', summary: '', updated_at: '2025-03-01', publish_details: [] },
      ],
      new Date('2026-01-01'),
    )

    expect(row).to.deep.equal({ content_type: 'article', entries: 2, unpublished: 1, stale: 1, missing_required: 1 })
  })
})

describe('stack:health', () => {
  it('asks for a stack when no flags are passed', async () => {
    const { error } = await runCommand('stack:health')
    expect(error?.message).to.contain('Pass --stack-api-key or --alias')
  })
})
```

Install the test dependencies with npm install -D @oclif/test mocha chai@4 @types/mocha @types/chai ts-node and run npm test. Neither test calls the API: the second one fails on the missing flags before the command reads the region or creates a client.

## Publish and install

Publishing is a normal npm release. The prepack script compiles the code and writes oclif.manifest.json, which the CLI uses to find commands without loading every file:

```bash
npm publish
```

Anyone on CLI 2.x can then install it:

```bash
csdx plugins:install csdx-plugin-stack-health
csdx stack:health -a my-token
```

Updates go through csdx plugins:update, and csdx plugins shows the installed version.

## Limits to remember

- The report reads entries in the stack's master locale. Add a locale query parameter and a --locale flag if you need other locales.


- The required field check looks at top-level fields only. Required fields inside groups, global fields and modular blocks need a recursive walk of the schema.


- Every content type costs at least one request, plus one per 100 entries. On very large stacks, run it against a management token in CI rather than on every commit.


- Stale is based on updated_at, so an entry that was published but never edited still counts as stale.



## Key takeaways

- A csdx plugin is an npm package with an oclif section whose commands path points at compiled output.


- Extend Command from @contentstack/cli-command and import flags, cliux and managementSDKClient from @contentstack/cli-utilities.


- Use this.cmaHost and managementSDKClient({ host: this.cmaHost }) so your command respects the user's region, login and proxy.


- Support both -k with session auth and -a with a management token alias, the same way official plugins do.


- Rebuild and run npx oclif manifest before every csdx plugins:link test, and namespace your commands under their own topic.



## Next steps

- Read [Every csdx command is a plugin](/blog/every-csdx-command-is-a-plugin) for the list of bundled and opt-in plugins you can learn from.


- Pair the health report with [Safe content model changes with branches and aliases](/guides/safe-content-model-changes-with-branches-and-aliases) to check a branch before you merge it.


- Run the command in CI next to your deploys, as in [Deploy from CI with the Launch CLI and API](/guides/deploy-from-ci-with-the-launch-cli-and-api).





---

## Do this with AI

Install the dx-cli skill from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills). Then ask your agent:

> Scaffold a read-only csdx plugin command that counts entries per content type and lists unpublished ones, with a unit test, and no calls that write to the stack.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### Which base class should a csdx command extend?

Extend Command from @contentstack/cli-command. It adds the region hosts, the logged-in email and saved token lookups on top of the oclif command class.

### How does my plugin reuse the user's csdx login?

Call managementSDKClient from @contentstack/cli-utilities with host set to this.cmaHost. Without a management token it uses the session from csdx auth:login, including OAuth refresh.

### Why does csdx not see my new command after linking?

Linking does not compile anything. Run the TypeScript build and npx oclif manifest again, then check that oclif.commands in package.json points to the compiled folder.

### Can I name my command anything?

Yes, but put it under its own topic, like stack:health. A linked plugin overrides any core command with the same ID, so avoid reusing names such as cm:stacks:export.


---

## Step 3: Build your first Developer Hub app

- **Source:** https://developers.contentstack.com/guides/build-your-first-developer-hub-app
- **Checkpoint:** A Developer Hub app is installed in your stack.

- **Authors:** Tim Benniks
- **Published:** 2026-11-28T09:00:00.000Z
- **Updated:** 2026-11-15T10:55:43.491Z
- **Level:** Intermediate
- **Intent:** Build
- **Tags:** sdk, api, security, react

---

> **Full guide available:** [View all 4 chapters in one document](https://developers.contentstack.com/guides/build-your-first-developer-hub-app/full.md)

A Developer Hub app is how you put your own UI inside Contentstack. It can be a custom field, a sidebar next to the entry editor, a dashboard widget, or a full page, and it ships as one web app that Contentstack loads into iframes. If you have built a Contentful app or a Shopify app before, the model will feel familiar: a manifest declares where the app shows up and what it may do, and an SDK connects your code to the host.

This guide takes you from an empty folder to an installed app that reads and writes entry data, stores configuration per installation, calls APIs without exposing tokens, and runs on a production URL. Each chapter covers one layer of the stack, so you can also jump to the one you need.

## What you'll learn

- How an app, its manifest and its UI locations fit together


- How to scaffold an app with the csdx app:create command


- How to initialize App SDK v2 and use location-specific APIs


- How installation configuration and secrets are stored


- How app tokens, user tokens and the proxy differ


- How to host the app, subscribe to lifecycle webhooks, and go live



## How the pieces fit

Contentstack concept: An app is a manifest plus hosted code. The manifest lives in Developer Hub. The code lives wherever you host it.

When an editor opens an entry that uses your custom field, Contentstack reads the installed manifest, builds the iframe URL from your hosting URL plus the location's path, and loads your app. Your code calls ContentstackAppSDK.init() and gets back an object that knows which location it is running in, which entry is open, and which installation configuration applies.

flowchart LR  A[Developer Hub manifest] -->|UI locations, OAuth, webhooks, hosting| B[Installation in a stack]  B --> C[Contentstack UI]  C -->|iframe: hosting URL + path| D[Your app]  D -->|App SDK: init, field, entry, api| C  C -->|proxied requests| E[Contentstack APIs]  C -->|rewrites + mappings| F[Third-party APIs]The diagram shows the two directions that matter. Configuration flows down from the manifest into each installation. Requests flow up from your app through the host, which adds credentials so your frontend never holds a token.

## How the chapters fit together

- [Manifest and UI locations](/guides/build-your-first-developer-hub-app/manifest-and-ui-locations) creates the app, explains the manifest, and helps you pick locations.


- [App SDK v2 essentials](/guides/build-your-first-developer-hub-app/app-sdk-v2-essentials) initializes the SDK and reads and writes field, entry and installation data.


- [OAuth and machine-to-machine apps](/guides/build-your-first-developer-hub-app/oauth-and-machine-to-machine-apps) covers app tokens, user tokens, scopes and the proxy patterns.


- [Hosting and going live](/guides/build-your-first-developer-hub-app/hosting-and-going-live) moves the app off localhost, adds lifecycle webhooks, and walks through a go-live checklist.



Read them in order the first time. Chapter 2 assumes the scaffold from chapter 1, and chapter 4 assumes the secrets setup from chapter 3.

## Key takeaways

- An app is a manifest in Developer Hub plus a single-page app you host.


- UI locations are iframes. The location's path is appended to your hosting URL.


- The App SDK is the only channel between your code and Contentstack.


- API calls go through the host, so your frontend never stores a token.



When you hit problems after launch, [five Developer Hub gotchas that bite on day two](/blog/five-developer-hub-gotchas-that-bite-on-day-two) covers the ones that show up most often.



---

## Do this with AI

Install the developer-hub-app-architect skill from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills). Then ask your agent:

> I want a custom field that lets editors pick products from our PIM. Recommend the UI locations, token type and hosting setup, and draft the app manifest for me to review.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### What is a Developer Hub app?

A single-page web app you host yourself or on Launch. Contentstack loads it in iframes at the UI locations you declare in the app manifest, and it talks to the host through the App SDK.

### Do I need a backend to build an app?

Not for most apps. The App SDK proxies Contentstack API calls, and Advanced Settings let you call third-party APIs with secrets that never reach the browser.

### Which framework should I use?

Any framework that builds a single-page app works. The official boilerplate uses React, TypeScript and Vite, and this guide follows it.

### Can I keep the app private to my organization?

Yes. Every app starts private and installs right away in your own organization. Publishing to the Marketplace is a separate, optional step.


---

## Step 4: Five Developer Hub gotchas that bite on day two

- **Source:** https://developers.contentstack.com/blog/five-developer-hub-gotchas-that-bite-on-day-two
- **Checkpoint:** You know the five mistakes that break apps after go-live.

- **Authors:** Tim Benniks
- **Published:** 2026-11-30T09:00:00.000Z
- **Updated:** 2026-11-15T10:56:40.534Z
- **Level:** Intermediate
- **Intent:** Fix
- **Tags:** sdk

---

Day one of a Developer Hub app is fine. It installs, the sidebar renders, the custom field saves. Day two is when an editor saves the config page and the API key disappears, or a sidebar shows "no results" because a request failed and nobody noticed.

None of these are exotic. They come from how the App SDK, installation data and the proxy behave, and each one is quick to fix once you know the cause. Here are the five I would check first, each with the symptom, the cause and the fix.

## The short version

- setInstallationData() replaces what is stored. It never merges.


- appSdk.api() resolves on HTTP errors. Check res.ok.


- Proxy mapping values are paths inside serverConfiguration, with no prefix.


- Code is live instantly. Manifest changes wait for each installation to update.


- A signed location only protects you if a missing token fails the check.



## 1. Saving the config page wipes the API key

Symptom: Everything works after install. A week later someone changes a non-secret setting, saves, and every proxied call starts returning 401.

Cause: setInstallationData() writes two buckets, configuration and serverConfiguration, and each one you send replaces the stored value. An empty object counts as a value. So this call wipes the saved key:

```typescript
await installation.setInstallationData({
  configuration: { region: "eu" },
  serverConfiguration: {}, // replaces the stored secret with nothing
});
```

The same goes for configuration. Even the public Advanced Settings tutorial sends configuration: {} next to the secret, which is fine on a first save and destructive on any later one.

There is a second part. Every call is a separate round trip to the host, and nothing orders them. Calling setInstallationData() on every keystroke can leave an older snapshot as the last one stored.

Fix: Send serverConfiguration only when the user sets or clears a secret. Keep the form in one state object, debounce, and send the full configuration snapshot each time. Store a non-secret flag so other locations know a key exists:

```typescript
const data = await installation.getInstallationData();

const payload: Record<string, unknown> = {
  configuration: { ...data.configuration, region, hasApiKey: Boolean(newKey || data.configuration.hasApiKey) },
};

if (newKey) {
  payload.serverConfiguration = { apiKey: newKey };
}

await installation.setInstallationData(payload as any);
```

The SDK types mark both keys as required, hence the cast. Leaving serverConfiguration out of the payload is what keeps the stored key untouched.

## 2. Failed requests look like empty results

Symptom: A dashboard widget shows "No entries found". The entries exist. There is no error in the console.

Cause: appSdk.api() behaves like fetch. It resolves on HTTP errors and hands you the status in a Response. A transport failure inside the host also comes back as a Response, with status 500. If your code goes straight to res.json() and reads an empty array from the error body, the UI shows "nothing found" instead of "something broke".

Fix: Check res.ok on every call and show a real error state:

```typescript
const res = await appSdk.api(`${appSdk.endpoints.CMA}/v3/content_types/blog/entries`);

if (!res.ok) {
  setError(`Contentstack returned ${res.status}`);
  return;
}

const { entries } = await res.json();
```

While you are here, check where your 401s and 403s come from. With appSdk.api(), the permissions are the App Permissions on the UI Locations tab. Nothing is selected by default, so a missing scope shows up as an error status, not an exception.

## 3. The proxy sends the placeholder, not the secret

Symptom: A third-party API called through a rewrite returns 401 on every request. The key in the config page is correct.

Cause: Mappings in Advanced Settings point a name at a path inside the installation's serverConfiguration. The path is already scoped to that bucket. If you write the mapping as server_configuration.apiKey, the proxy looks for server_configuration inside serverConfiguration, finds nothing, and sends {{map.API_KEY}} upstream as literal text. The mapping saves without complaint, so the first sign is the vendor's 401.

Fix: Write the mapping value as the bare path:

```json
{
  "mappings": {
    "API_KEY": "apiKey",
    "TRANSLATE_KEY": "integrations.translate.key"
  }
}
```

Then reference it in the request:

```typescript
await appSdk.api("/translate", {
  method: "POST",
  headers: { Authorization: "Bearer {{map.TRANSLATE_KEY}}" },
  body: JSON.stringify({ text, target: "fr" }),
});
```

After saving a mapping, make one real call from an installed app with a real stored value. A saved mapping only proves it validates.

## 4. The new location never shows up

Symptom: You add an entry sidebar, deploy, and open the stack. The sidebar is not there. A bug fix you shipped the same day is already live everywhere.

Cause: Developer Hub versions the manifest, not your code. New code at your hosting URL reaches every installation immediately. A change to UI locations, webhooks, OAuth or hosting creates a new manifest version, and existing installations see it as an available update. They do not move to it on their own.

That split cuts both ways. A UI change ships to every customer the moment your host serves it, with no version to roll back to in Developer Hub. A new location ships to nobody until each installation updates.

Fix: Plan releases around the split. Keep a separate staging app pointing at a staging URL, so code reaches a test installation before it reaches everyone. For manifest changes, update your own installations after saving, and tell installers when an update adds something they need. Then make sure new code still works for installations on the previous manifest, since some will stay there for a while:

```typescript
const sidebar = appSdk.location.SidebarWidget;

if (!sidebar) {
  // This installation has not updated to the version with the sidebar yet.
  return null;
}
```

## 5. Signed locations that sign nothing

Symptom: You set signed: true, the boilerplate verifies the token, and your backend trusts whatever the frontend sends. A request without a token gets through.

Cause: With signed: true, Contentstack appends an app-token JWT to the iframe URL. The boilerplate's useVerifyAppToken hook returns early when there is no token, so the app renders as if the check passed. The token also expires after a few minutes, so a backend that stores it as a session starts failing on its own.

Fix: Fail closed, and verify on the server where it counts:

```typescript
import jwt from "jsonwebtoken";

export async function requireAppToken(token: string | null) {
  if (!token) throw new Error("Missing app-token");

  const keys = await fetch("https://app.contentstack.com/.well-known/public-keys.json").then((r) => r.json());

  return jwt.verify(token, keys["signing-key"], { algorithms: ["RS256"] });
}
```

Use the payload's installation_uid and stack_api_key to scope data, never IDs from the request body. Create your own session from the payload instead of reusing the token. And set signed: true on each location's meta entry, not only at the top of ui_location.

## Concluding

All five share one root: the app works on install, so nobody looks again until a real editor does something you did not test. A second save on the config page, a request that fails, a mapping that never resolved, a manifest update nobody accepted, a missing token.

Test the second save, not just the first. Check res.ok. Make one real proxied call per mapping. And treat manifest changes like releases. If you are starting a new app, [build your first Developer Hub app](/guides/build-your-first-developer-hub-app) walks through all of it, with the details on [installation data](/guides/build-your-first-developer-hub-app/app-sdk-v2-essentials), [the proxy](/guides/build-your-first-developer-hub-app/oauth-and-machine-to-machine-apps) and [signed requests](/guides/build-your-first-developer-hub-app/hosting-and-going-live).



---

## Do this with AI

Install the developer-hub-app-architect skill from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills) and connect the App Integration Admin profile in MCP Profile Hub. Then ask your agent:

> Inspect the installations of my Developer Hub app, list any whose configuration is missing required keys, and point to the code path that could have cleared them.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### Why did my app's API key disappear after someone saved the config page?

setInstallationData replaces each bucket you send. Sending serverConfiguration as an empty object wipes the stored secret, so only send it when a secret is set or cleared.

### Why does appSdk.api() not throw on a 404?

It returns a Response for HTTP errors and turns transport failures into a Response with status 500. Check res.ok on every call.

### Why does my third-party API return 401 through the proxy?

Usually the mapping value is wrong. It is a path inside serverConfiguration, so drop any server_configuration prefix, or the placeholder is sent upstream as literal text.

### Why don't existing installations show my new UI location?

Manifest changes create a new version that installations see as an available update. Code changes go live right away, but new locations need the update.

