Writing Strapi database migration scripts

Migration scripts let you rename fields, move data and backfill values before Strapi's schema sync runs. This page covers how to order, make and test them safely on a copy of production.

On this page

Why Strapi database migration scripts matter before schema sync

A migration script is a file that changes existing data before or alongside a schema change, so that a renamed field, a moved value or a new required field does not leave content behind or orphaned. You need one when a content model change would otherwise cause data loss during schema sync, for example when a field is renamed, a field's meaning changes, or editors have values that must be carried into a new structure. Schema sync reads the model files and updates the database to match them, and removed fields and tables can be dropped in the process. A script gives you a place to copy or transform that data first, so the sync finds nothing left to discard.

The Content-type Builder is development-only. Editors and developers may be tempted to change fields directly on a production admin panel, but that path bypasses review, testing and rollback. Production schema changes should travel through the same controlled release process as code: the model change and its migration script are written in version control, reviewed, run against a copy of production data, and deployed in a planned window with a verified database backup. Confirm with your Strapi version's documentation how the Content-type Builder is restricted in production on your installation, and decide who owns the release sign-off before the first change is requested.

This page covers writing, ordering and testing these scripts, not the full move from Strapi v4 to v5. The supplied material describes Strapi's data migration scripts that run on first start of Strapi 5, and the upgrade tool and codemods are a separate concern. Read the Strapi v4 to v5 migration introduction and FAQ for the upgrade context, and treat any script you write here as a change you must be able to rerun and verify. Confirm the exact hook timing and file locations for your Strapi version before you rely on them.

Which kind of migration script fits which change

A rename looks like a single edit in the content-type schema, but the schema sync treats it as removing the old field and adding a new one. Unless the old values are copied first, the data stored under the old name can be lost. The script has to read the old column and write its values into the new one while both still exist in the database.

  • Copy before the sync: move each value from the old field to the new field while the old field still exists.
  • Handle empty values: decide what happens to rows where the old value is null or empty, and whether the new field's default should apply.
  • Cover every locale and status: confirm the copy reaches localized rows and both draft and published versions, since a single query may miss some.
  • Recognize the run-after failure: if the script runs after the sync, the old column may already be gone, leaving the new field empty and the original values recoverable only from a backup.

Before you approve the change, compare row counts for the old and new fields, sample entries in each locale, and confirm the API returns the same values under the new field name.

Migration approaches and when each fits

This table compares four ways to move or backfill data around a Strapi schema change, with the risk, reversibility and environments each one suits. Read it to pick the least risky option for a given change, then check the details against your own Strapi version and database before you rely on it.

ApproachMain riskReversibilityBest suited environments
One-off script run on startRuns once per database, so a half-finished run or a second start can leave data in a state the script did not expectLow, unless the script stores the original values before it changes themDevelopment and test databases, or small internal sites with a tested restore point
Raw SQL step through the database clientBypasses Strapi's validation, draft and locale handling, so rows can be valid SQL but invalid for the content APIMedium, if you write a matching reverse statement and keep a dump taken before the stepOperators who know the schema well, with a reviewed script and a backup taken immediately before the deploy
Document Service based scriptDepends on the Strapi version's API behavior, and a bulk update can touch draft and published versions in ways you did not planMedium, when the script reads and writes through the same service the application uses and you can reverse it with a second scriptProjects where content must stay consistent with Strapi's lifecycle rules, including localized and draft content
Split release: move data in one deploy, change schema in the nextTwo deploys mean the old and new code must both run against the data in between, which adds coordination workHigh, because the first release only adds or copies data and the schema change waits until you confirm the resultProduction systems with real editors and public traffic, and any change that drops or renames fields with content in them

How to write, order and run a migration script

This sequence turns a schema change into a migration script that runs predictably, can be safely re-run, and is verified against a restored copy of production before anyone ships it.

  1. Back up the database first

    Before touching any migration, take a full backup of the production database and confirm you can restore it. Strapi's upgrade documentation advises backing up the database first, and downgrading is not supported, so the backup is your only way back if a script goes wrong. Whoever owns the database (usually the platform or DevOps team) performs the backup and records its location and timestamp. The step is done when a test restore of that backup has completed on a separate host and the restored database starts.

  2. Inventory the schema diff

    Compare the content types in the current codebase with the schema the database expects. List every renamed field, removed field, type change, new required field and relation that moves data. Mark each item as either safe for schema sync or as needing data movement first. Schema sync can drop removed fields and tables, so anything marked as data-bearing needs a script before the sync runs. The output is a written inventory that the developer and the content owner both sign off on, with one line per change.

  3. Write the migration script

    Create the migration file in the project's migrations folder and write the change as a single, narrow operation: copy values from the old field to the new one, fill a new field from a default or a lookup, or split one field into two. Use the database query layer for bulk work rather than loading every entry through the Document Service, and keep the script limited to the data it must touch. Name the file with a timestamp so its position in the sequence is clear. The step is done when the script runs without error against a local database seeded with representative content.

  4. Make the script idempotent

    Make the script safe to run twice. Either write a marker that records the migration has completed, such as a row in a dedicated table, or check each record before writing so that already-converted values are skipped. Test this directly: run the script, then run it again, and confirm the second run changes nothing. The output is a second run that reports zero updated rows and leaves the data unchanged.

  5. Order multiple scripts by dependency

    When several scripts exist, run them in dependency order first and timestamp order second. A script that copies a value must run before a script that deletes the source field, and a backfill must run after the field it fills exists. Review the file list against the inventory from step two and confirm every data-bearing change has exactly one script. The check is a short written order, reviewed in the pull request, that matches the file names.

  6. Rehearse on a restored copy of production

    Restore the production backup to a separate environment that matches production's database engine and version, then run the scripts and the schema sync in the same order planned for release. Time the run and record any errors. Confirm that the script ran once, that a second run changes nothing, and that the schema sync did not remove data you still need. Use a copy of production rather than seeded test data, because real content exposes edge cases such as empty fields, legacy values and locale variants.

  7. Verify row counts and sample content

    Compare row counts before and after the rehearsal for each affected table and content type, and confirm the totals match what the script was meant to change. Then check a sample of entries in the admin panel and through the API, including localized entries and entries with relations. Confirm that the migrated values display correctly and that API responses return the new field names. The output is a signed-off verification record listing counts, sampled entry IDs and the reviewer.

  8. Promote the tested sequence to production

    Run the same scripts, in the same order, against production during the agreed change window, using the same code version that passed the rehearsal. Take a fresh backup immediately before the run, and keep the rehearsal log to compare against. Check the counts and sample entries again after the run. The step is done when the post-release checks match the rehearsal results and the backup is retained according to your recovery policy.

How a migration run moves from copy to production

The run starts with a code change to the migration scripts, which is committed and then tested against a fresh backup. Production is backed up first, then restored into a copy where the scripts run in their defined order before the schema sync. Verification on the copy decides whether the same release goes to production. If verification fails at production, the rollback is a restore from the backup, because downgrading Strapi is not supported.

Migration run from code change through the copy to production, with the restore rollback.

How to test migrations on a copy of production

A migration script that passes on a developer's seed data can still fail on real content. The cards below cover the sequence that connects a production copy, repeated runs, data comparison, state coverage, timing and copy handling, so the rehearsal gives you evidence you can rely on at cutover.

Obtain a recent production copy

Take a fresh database dump from production, restored into an isolated environment, so that the scripts meet the real mix of locales, drafts, relations and legacy values. Before restoring, agree how personal data in editorial content and user tables is masked or removed under your data policy. Confirm which file uploads and media records come along, since the migration may touch them. Record the dump time and schema version so that every rehearsal can be compared against the same baseline.

Run the chain twice

Execute the full ordered set of migration files against the copy, then run the same chain a second time without restoring. The second run should change nothing. If it renames a field again, rewrites values again or fails on a missing column, the script is not idempotent and must be fixed before anyone relies on it. Keep the console output from both runs as part of the release evidence.

Compare counts and sampled records

Before the run, export row counts per content type, per locale and per status, along with a fixed sample of records chosen by ID. After the run, repeat the export and compare. Counts should match except where the script deliberately creates or removes rows, and each difference should be explained by a named rule. Sampled records should show that moved values landed in the new fields without losing precision, empty values or relation links.

Test draft and published states

Strapi 5 stores draft and published versions of documents, so a script that only updates one row can leave the two states inconsistent. For each affected type, check an entry that is published, one that is draft only, and one with both versions that differ. Confirm the API returns the expected values in each state and in each locale. Include an entry that has a pending or changed localization, because those are common sources of partial updates.

Time the run at production size

A script that finishes in seconds on a small copy may lock tables for a long time on production volumes. Run the chain against a copy sized like production and record how long each file takes, which steps hold locks and whether the database could be read during the run. Use these timings to decide the maintenance window and whether a batch approach is needed. Ask your database team to review the timings against your backup and replication behavior.

Keep test copies out of shared environments

A production copy contains the data you are trying to protect, so store it only in the isolated environment that the rehearsal needs, with access limited to named people. Do not point shared staging, preview or developer environments at it, and do not leave dumps on laptops or shared storage. Delete the copy when testing ends, and log that deletion alongside the rehearsal evidence. Confirm this handling with your security and privacy owners before the first restore.

What breaks migration scripts in practice

What happens if a Strapi migration script runs twice?

A script that is not idempotent applies its change again on the second run, which can rename a field that no longer exists, duplicate values or shift data that was already moved. The cause is usually a script that assumes the source state without checking it. The check is to run the script twice against a copy of production and compare the database before and after the second run. Guard each step with a condition, such as checking whether the target column exists or whether a value is still null, and record completed steps in a dedicated table so a rerun skips them. Your team should confirm how the Strapi version you run tracks migration state before relying on it.

Why does a migration fail after schema sync has already dropped the field?

Schema sync removes fields and tables that no longer exist in the content type definitions, so a script that reads the old field after sync finds nothing to move. The data is lost at that point unless a copy was made first. The fix is ordering: the script must read and copy the source field before the schema change is applied, and it must be placed where it runs before sync. The check is to take a restore point, run the full sequence on a copy of production, and confirm the target column holds the expected values before the source column is removed. Review the documented ordering in the Strapi v4 to v5 migration introduction and FAQ for how Strapi runs its own data migrations.

How do localized and draft rows get missed by a migration?

Content in Strapi can exist as several rows: one per locale when internationalization is enabled, and separate draft and published versions. A query that selects only one row per entry updates the default locale or the published version and leaves the rest with the old field value. The result is content that looks correct in one language or in the live site but is wrong elsewhere. The check is to count rows per document, locale and status before and after the script, and to assert that no row still holds a value in the old field. Include a test entry in every locale that has a draft and a published copy, and confirm the expected row count for each.

What happens to relations when a field is renamed in a script?

Relations are stored in join tables that reference content rows, and a script that renames a field or changes a relation name without updating the join table leaves links pointing at nothing. Editors then see empty relation fields, and API queries that populate those relations return incomplete results. Relations also break when a script moves data between types but does not carry the links with it. The check is to compare the relation counts for each affected type before and after the migration, and to query a sample of populated endpoints on the copy to confirm the linked entries still resolve. Test these checks with the same relation graph that editors use, not only with flat fields.

Why do migrations lock tables for a long time on large content sets?

A single statement that updates every row of a large table takes locks that block reads and writes for as long as it runs, and on a busy site that means editors and public API requests wait or fail. Duration depends on row count, index use, the database engine and whether the update rewrites whole rows. The check is to measure the run on a copy sized like production and watch lock waits. Break large updates into batches, schedule them in a maintenance window, and confirm how your database engine handles schema changes that rewrite tables. Ask your database administrator to review the plan before the change window is set.

What breaks when a migration script calls a Strapi API that changed between versions?

Strapi 5 replaces the Entity Service API with the Document Service API and changes the response format, so a script written against v4 calls methods that no longer exist or receives data in a different shape. Scripts may also assume older field names or return values. The failure often appears only on the run that reaches the changed call, which can be late in a long job. The check is to pin the Strapi version the script targets, run it against that version on a copy, and compare its output with expected results. Where possible, prefer direct database statements for data moves, and use the documented Document Service calls for logic that must respect Strapi rules such as draft handling.

Can our own team write and test these scripts, or do we need a partner?

A team with database and Strapi experience can write these scripts, but the work usually depends on a copy of production that is sized and refreshed correctly, a restore path that has been tested, and a review of each script against the checks above. Cost comes from the time to analyze the content model, write and test each script, run rehearsals and document the sequence, and it recurs whenever the content model changes. Ask any partner for a written scope that lists the rehearsal runs, the checks they will run, and what the handover includes, and compare it with the effort your own team can commit to.

Security and operational considerations for migration runs

A migration script runs with write access to production data, so its database access, data handling, audit trail, backups and release approvals matter as much as its logic. The cards below cover the controls that should be settled before the first run, not after the first failure.

Database credentials and scope

Migration scripts usually connect with the same database user the application uses, which often has rights to drop tables and columns. Create a separate migration role that can alter only the schema objects and rows the script touches, and confirm that the Strapi runtime user cannot perform those changes. Ask your DBA to review the grants before the first production run.

Strapi installation docs

Personal data in production copies

Testing on a copy of production means personal data is now in a second environment, often with weaker access controls. Mask or subset sensitive fields before the copy leaves the production boundary, and keep the copy inside the same data location rules as production. Confirm the retention period for test copies with your privacy team.

Audit trail of script runs

Record which script ran, who approved it, which environment it ran in, the start and end times, and the row counts it changed. Store this record outside the database the script modifies, so it survives a failed run. Strapi's audit logs are an Enterprise feature, so for other plans the record usually has to come from your own runbook and pipeline logs.

Strapi self-hosted plans

Backups before every run

Take a verified backup of the database immediately before each run, not only the nightly backup. Strapi's upgrade documentation says to back up the database first because downgrading is not supported, so a restore is the only rollback path. Test the restore on a copy and record how long it takes, so the team knows the recovery window before it needs one.

Strapi v4 to v5 migration docs

Change control for schema releases

Treat each migration file as a release artifact that goes through the same review as application code. Require a named approver for production runs, a change ticket that links the script to the content model change, and a rollback decision recorded before the deployment window opens. Keep the schema sync and the migration in the same release so they cannot drift.

Secrets kept out of scripts

Migration scripts should read database passwords and API keys from the environment or a secrets manager at run time, never from hard-coded values or committed .env files. Scripts often log their configuration on failure, so check that connection strings are masked in output. Rotate any credential that appeared in a script, log or ticket.

Questions buyers ask before writing migration scripts

How much effort does a typical Strapi migration script take?

Effort depends on how much of the schema changes and how much data sits behind each change, so no single number applies to every project. A script that only renames one field on one type is small. Effort grows with the number of content types touched, the amount of localized data that must move with each change, the row volume in affected tables, and the relations that point at moved or renamed data. Each script also needs a rehearsal against a copy of production, and that repeated run usually costs more time than writing the first draft. Ask for a written estimate that lists each change, the tables it touches and the number of rehearsal runs assumed.

Can our own team write Strapi migration scripts without a partner?

Yes, a team that already knows Strapi's content model, its database schema and its startup behavior can write and test these scripts internally. The skills that matter most are careful SQL against the database you actually run, idempotent logic that can safely run twice, and disciplined testing on a restored copy. Teams without a database engineer often underestimate the ordering problems and the localization edge cases. A useful check is whether someone on your team can explain, step by step, what happens to a renamed field between the old schema and the new one.

What does our organization need to provide for a migration rehearsal?

You need a recent copy of the production database, a staging environment running the same Strapi version and Node.js runtime as production, and a window in which the rehearsal can run without interfering with editors. You also need a named owner who can approve the schema changes, confirm the expected data results and decide whether a run is good enough to repeat in production. Confirm where the copy may be stored, who can access it, and whether it contains personal data that your data handling rules restrict. Without those inputs, the rehearsal will not match the production run closely enough to trust.

How long does a rehearsal on a production copy take?

The duration is driven by data volume, the number of scripts, the speed of the database host and how many rehearsal cycles the team plans. A rehearsal includes restoring the copy, running the scripts, checking the results, fixing issues and repeating until the run is clean. Large tables, heavy relation updates and localized content extend each cycle. Ask the team to state the number of planned cycles and the time each one needs on your hardware, and to measure it on the first run rather than guess from the schema.

Which parts of a migration must run in a fixed order?

Scripts that rename fields or move data must run before Strapi's schema sync removes or recreates the affected columns, so the data is safe at the moment the schema changes. Scripts that backfill values usually depend on earlier renames, so they run after them. Relation changes often depend on both. Ordering errors are a common cause of data loss, so write down the sequence and check it against a rehearsal log. The Strapi migration documentation and the release notes for your version should be the first reference for these startup steps.

When should we bring in a partner for migration scripts?

Bring in a partner when the schema change affects many content types, localized content, dynamic zones or relations that span several collections, or when the production data is large enough that a failed run would be costly. A partner is also useful when the team lacks time for repeated rehearsals or needs an independent review of the scripts before a release. DeployOpen plans and implements Strapi work inside the client's own infrastructure, and most engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts. Ask for the written scope to name the scripts, the rehearsal cycles and the handover of the final runbook.

Do we need a backup before running Strapi migration scripts?

Yes. Strapi's v4 to v5 migration documentation tells teams to back up the database first because downgrading is not supported, so a failed script cannot be rolled back by reverting Strapi alone. Confirm that the backup is restorable, that someone has tested the restore on a separate host, and that the backup is taken immediately before the production run. Keep the rehearsal logs with the scripts so the production run can be compared against them.

How DeployOpen works on this

DeployOpen plans and builds Strapi migration scripts as part of a fixed-scope engagement agreed in writing before work starts. Each script is written, tested against a copy of your production database, documented and handed to your team, with ongoing support available as a retainer.

How we scope

  • Inventory every content type, field and component the migration script must rename, move or backfill.
  • Agree which Strapi version, database engine and Node.js runtime the scripts will run against.
  • Write the scope, deliverables and timeline in writing before any script work starts.

How we build

  • Write idempotent migration scripts that check state before changing data, so reruns are safe.
  • Order scripts explicitly and run them against a restored copy of production before any shared environment.
  • Record row counts and sample values before and after each run to confirm the backfill worked.

How we hand over

  • Deliver scripts with a runbook covering execution order, expected output and rollback steps.
  • Document which backups must exist before running, since downgrading Strapi is not supported.
  • Walk your engineers through the test results and the checks they should repeat in staging.

How we support

  • Offer retainer support for scripts that still need adjustment after your first production run.
  • Retest scripts when you upgrade Strapi minor versions or change the content model again.
  • Confirm with your team how migration scripts fit into your existing release and backup process.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.