Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 10 min read

How to update one dynamic zone block in Strapi 5 (without deleting the others)

You have a Strapi 5 page built from a dynamic zone: a hero, a feature grid and a call to action. You want to change the hero's heading and nothing else. So you send an update with the hero block, and the feature grid and

You have a Strapi 5 page built from a dynamic zone: a hero, a feature grid and a call to action. You want to change the hero's heading and nothing else. So you send an update with the hero block, and the feature grid and the call to action are gone.

That is how Strapi 5 writes lists. A dynamic zone, a repeatable component or a rich-text blocks field is replaced as a whole: the array you send becomes the new list, and anything you left out is deleted. The REST API works this way, and so does the update_<type> tool in Strapi's built-in MCP server. With one writer, that is a matter of sending the right array. With two writers, it is a race: each one sends a list built from its own read, the second write wins, and the first writer's block disappears with a 200 and no error.

People keep running into this. One GitHub issue reads, "found that I cannot update component". A docs issue is blunter: "Updating dynamic zones via REST API does not work." It does work. It just doesn't work the way most of us assume the first time.

Below are three routes, in order of how much control you have over the writer.

Disclosure up front: the third route uses writesafe, a plugin my company, IsoKron, built and maintains. It's free and MIT-licensed. Routes 1 and 2 need nothing but Strapi.

Why ids don't save you

In Strapi v4 you could send a component's id and update that one row. The v4-to-v5 breaking changes document two things about that in Strapi 5:

  • REST responses for components and dynamic zones no longer include an id, so partial updates of them over REST are documented as not possible.
  • With Draft & Publish, component ids are status-local: publishing creates new component rows, so the draft and the published version of the same block have different ids. Sending a published id against the draft fails with "…not related to the entity".

The reporter of the issue above, on 5.32.0, got a 400 Invalid key id for sending id in a REST body at all. On 5.62.0 the server has moved on from the first point. A REST GET returns an id on every block, and if you read the draft (?status=draft) and send those ids back, the PUT returns 200 and updates the rows in place. Published ids still get a 400: "Some of the provided components in sections are not related to the entity".

None of which saves you. An id only decides whether Strapi updates a row or recreates it. The list is still replaced as a whole: a block you leave out is deleted, id or no id, and nothing in the request says which version you read.

Strapi's documented pattern for REST is still to leave ids out, so that is Route 1. I wouldn't build on undocumented id handling that changed between 5.32 and 5.62. The Document Service, which reads and writes the draft by default, accepts draft component ids by design; that is Route 2.

Route 1: REST, send the whole list

Strapi's recommended pattern for Content API clients is to omit component ids and send the complete list you want. Their docs put it in one line: "Include every component you want to keep."

Read the draft with the zone populated. For dynamic zones, Strapi 5's docs use on fragments, one per component; list every component the zone allows:

curl -sg "http://localhost:1337/api/pages/$DOC_ID?status=draft\
&populate[sections][on][blocks.hero][populate]=*\
&populate[sections][on][blocks.feature-grid][populate]=*\
&populate[sections][on][blocks.cta][populate]=*" \
  -H "Authorization: Bearer $API_TOKEN"

Then change the one block and send the whole zone back, every entry with its __component and without id:

curl -s -X PUT "http://localhost:1337/api/pages/$DOC_ID?status=draft" \
  -H "Authorization: Bearer $API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "data": {
      "sections": [
        { "__component": "blocks.hero", "heading": "Spring sale", "subheading": "Ends Sunday" },
        { "__component": "blocks.feature-grid", "title": "Why us", "items": [ { "label": "Fast" }, { "label": "Quiet" } ] },
        { "__component": "blocks.cta", "label": "Buy", "url": "/buy" }
      ]
    }
  }'

Three things to know:

  1. __component is not optional. The REST docs say that without it, "writes can fail validation or return success without changing data." The second outcome is the one that costs an afternoon. Put it first, too: on 5.62, a block whose nested list comes before __component gets a 400 Invalid key __component at sections, and the GET returns __component last, so pasting the GET output straight back fails.
  2. Every entry comes back as a new row with a new id. If something downstream keyed off component ids, it no longer matches.
  3. Nested lists inside a block (the grid's items above) have to be sent in full too. Populate deep enough to see them, or they go the same way as the call to action.

This route is correct for one writer. It has no version check, so if an editor adds a testimonial block between your GET and your PUT, your PUT removes it. Nothing in the response tells you.

Route 2: backend code, Document Service with draft ids

If the write happens in your own Strapi code (a controller, a cron job, a migration script), you can do what the REST docs say not to count on: load the draft with its component ids and update one entry in place. This is the second workaround in Strapi's breaking-change note. Wrapping it in a transaction keeps the read and the write together:

// src/api/page/services/update-hero.js
module.exports = ({ strapi }) => ({
  async updateHeroHeading(documentId, heading) {
    return strapi.db.transaction(async () => {
      const draft = await strapi.documents('api::page.page').findOne({
        documentId,
        status: 'draft',
        populate: {
          sections: {
            on: {
              'blocks.hero': { populate: '*' },
              'blocks.feature-grid': { populate: '*' },
              'blocks.cta': { populate: '*' },
            },
          },
        },
      });

      const sections = draft.sections.map((block) =>
        block.__component === 'blocks.hero'
          ? { ...block, heading }   // keeps id and __component
          : block                    // every other block, with its draft id
      );

      return strapi.documents('api::page.page').update({
        documentId,
        data: { sections },
      });
    });
  },
});

Rules that matter here:

  • Use draft ids only. The docs are explicit: don't reuse ids from a default Content API GET, which returns the published version.
  • Send every block. It is still a whole-list write; the ids only decide whether Strapi updates the rows or recreates them.
  • A transaction is not a lock. Under the default isolation levels of Postgres and MySQL, two of these running at once can both read the same draft and both write, and the second one still drops whatever the first added. Editors saving in the admin panel don't go through your transaction at all. If you need this to be safe under concurrency, lock the draft rows before the read (SELECT … FOR UPDATE) or check a version and retry. The rest of this article is, more or less, what happens when you do that properly.

Route 3: agents over MCP, with writesafe

Strapi 5 ships an MCP server, which is how a growing number of pages now get edited: an agent connected at /mcp, sometimes while a person is in the admin panel. The built-in update_<type> tool behaves like REST. It replaces each list it is sent, it can't send component ids, and it has no version check.

We measured that during development on Strapi 5.62.0 with SQLite. An agent writing from a stale read while a colleague added a block deleted the colleague's block in 12 of 12 trials, for each of dynamic zones, repeatable components and blocks fields. None of 233 responses carried a conflict signal.

writesafe adds ws_* tools to that same /mcp endpoint through Strapi's plugin API (strapi.ai.mcp.registerTool), with the same admin tokens and permissions. Two of them do the work here.

ws_get returns the draft with a version token and a _key on every row of each top-level list. Over plain HTTP it's a JSON-RPC tools/call; the server is stateless, so no initialize is needed first:

curl -s http://localhost:1337/mcp \
  -H "Authorization: Bearer $STRAPI_MCP_TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
        "name":"ws_get",
        "arguments":{"uid":"api::page.page","documentId":"'"$DOC_ID"'","fields":["sections"]}}}' \
  | sed -n 's/^data: //p' | jq '.result.structuredContent'

Abridged, the part you care about looks like this (version and keys shortened; yours will differ):

{
  "version": "v3.PZ6WXSDnDcYZPXpw…",
  "data": {
    "sections": [
      { "_key": "blocks.hero:10:wb2tiA9SP1YF…", "heading": "Welcome", "subheading": "Hi", "__component": "blocks.hero" },
      { "_key": "blocks.feature-grid:13:EY-ZPnXzVjOd…", "title": "Why us", "items": [ { "label": "Fast" }, { "label": "Quiet" } ], "__component": "blocks.feature-grid" },
      { "_key": "blocks.cta:11:0T_4M8oXIMsf…", "label": "Buy", "url": "/buy", "__component": "blocks.cta" }
    ]
  },
  "rows": { "sections": [ "blocks.hero:10:wb2tiA9SP1YF…", "blocks.feature-grid:13:EY-ZPnXzVjOd…", "blocks.cta:11:0T_4M8oXIMsf…" ] }
}

Then ws_patch edits one row by key:

{
  "uid": "api::page.page",
  "documentId": "<documentId>",
  "ops": [
    { "op": "update", "field": "sections", "key": "blocks.hero:10:wb2tiA9SP1YF…", "data": { "heading": "Spring sale" } }
  ]
}

Row ops (add, update, remove, move) apply to the current list inside the write transaction, under a row lock, not to the list as the agent last saw it. So a block a colleague added a minute ago survives, and the rows you didn't name keep their database ids. Row ops need no version, because a key is bound to the row's content: if someone changed the hero since your read, the call is refused with stale_row_key; if the hero is gone, row_not_found. Either way the agent reads again. It doesn't guess.

Sometimes you really do mean to replace the whole list. That's a set, and a set needs the version you read:

{
  "uid": "api::page.page",
  "documentId": "<documentId>",
  "expected_version": "v3.PZ6WXSDnDcYZPXpw…",
  "set": { "sections": [ { "__component": "blocks.cta", "label": "Buy", "url": "/buy" } ] }
}

If the draft changed since that read, nothing is written. The reply is version_conflict with the current version, the current document and a retry hint telling the agent to re-apply only its own change.

In the same trials as above: with row ops, 0 of 36 colleague rows were lost and no ids were recreated. With a stale whole-list set, 36 of 36 writes were refused with version_conflict, and 36 of 36 landed after one re-read and retry. The table and conditions are in the reference.

To be plain about scope: this only applies to MCP tool calls. writesafe adds no REST routes and does not change what PUT /api/pages/:id does. Any HTTP client can make the calls above, not only an AI agent, but they go to /mcp, not /api. If your writers are REST clients, Routes 1 and 2 are your options.

By default (builtinUpdates: 'guard') the plugin also makes Strapi's built-in update_<type> refuse list and component writes and point the agent at ws_patch, so an agent can't take the old path by accident.

Which route when

Writer Route
One REST or GraphQL client, nobody else editing that page at the same time 1: send the full list
Your own Strapi code 2: Document Service with draft ids, plus a lock if it can run concurrently
Agents or other MCP clients, especially alongside human editors 3: row ops by key

Limits

  • Only api:: collection and single types. Types with a polymorphic relation inside a component, or components nested deeper than 8 levels, are left out, and ws_schema names them.
  • Tested on every Strapi 5 minor from 5.47 to 5.62, each on SQLite, Postgres 16 and MySQL 8.4 (48 of 48 cells pass). MariaDB is not tested. Prefer a minor other than 5.51.x: its MCP endpoint's memory grows per request, with or without the plugin.
  • Two editors in the admin panel still overwrite each other. Last Save wins, as in Strapi.
  • One behaviour change to know about: staleFormGuard (on by default) makes an admin form that was opened before a newer REST, GraphQL or agent write refuse its Save with a 409, keeping the editor's values. staleFormGuard: { otherWriters: false } restores last-write-wins for non-agent writers.
  • In keep or guide mode, an agent that ignores its instructions can still call update_<type>.

Install

npm install strapi-plugin-writesafe-mcp
// config/plugins.js
module.exports = () => ({
  writesafe: { enabled: true },
});

// config/server.js: add this to the object it returns
//   mcp: { enabled: true },

Then npm run build (the plugin adds a jobs page and a settings page to the admin) and restart. Create an admin token with Read and Update on your content type; tools/list on /mcp should now show the ws_* tools. Client setup for Claude Code, Cursor and others is in docs/clients.md.

Closing

None of this is a Strapi bug. Whole-list replacement is a reasonable contract for a REST API, and Strapi documents it. It just assumes one writer, and that assumption got quieter and less true once agents started editing content. If you only have one writer, send the full list and move on. If you have several, give each one a way to say which row it means and which version it read.

writesafe is on npm, in the Strapi Marketplace and on GitHub. If you hit a list edit the row ops don't cover, open an issue. The general idea behind it is written up in Send the change, not the object.

IsoKron built and maintains writesafe. I'm IsoKron's founder.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.