ylahav

payload db backup restore

by ylahav
Databases & data
v3
^3.0.0
MIT

Overview

Summary generated from the README

Adds an admin view at a configurable route plus a sidebar link for downloading and restoring selected collections as a single JSON file. Backups use EJSON so ObjectIds and Dates round-trip exactly, and draft version collections are included automatically. Restore writes through raw Mongoose without running hooks or validation. Requires Payload 3 with the MongoDB adapter.

Features

  • Select collections to export as one portable JSON file
  • EJSON serialization preserves ObjectIds, Dates and Decimal128 values
  • Includes version collections for collections with drafts enabled
  • Restore with optional drop-before-restore, skipping hooks and validation
  • Configurable access check, route and sidebar visibility
  • Exposes endpoints for listing collections, exporting and importing, usable from scripts

Use cases

  • Take a snapshot of selected collections before a risky deployment or migration
  • Copy content between environments by exporting from one and restoring into another
  • Restore a MongoDB-backed Payload site's content after accidental data loss

From the author

Admin UI for exporting and restoring selected Payload CMS collections as portable JSON. Includes a /admin/backup view and a sidebar shortcut.

Installation

npm i @yairl/payload-db-backup-restore

3

Stars

0

Forks

0

Open Issues

4 months ago

Last Updated

105

Weekly Downloads

v0.1.2

npm Version

62.4 KB

Unpacked Size

1

Dependencies

GitHub stars

30 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20263
Dec 4, 20263
Dec 3, 20263
Dec 2, 20263
Dec 1, 20263
Nov 30, 20263
Nov 29, 20263
Nov 28, 20263
Nov 27, 20263
Nov 26, 20263
Nov 25, 20263
Nov 24, 20263
Nov 23, 20263
Nov 22, 20263
Nov 21, 20263
Nov 20, 20263
Nov 19, 20263
Nov 18, 20263
Nov 17, 20263
Nov 16, 20263
Nov 15, 20263
Nov 14, 20263
Nov 13, 20263
Nov 12, 20263
Nov 11, 20263
Nov 10, 20263
Nov 9, 20263
Nov 8, 20263
Nov 7, 20263
Nov 6, 20263
Nov 5, 20263
Nov 4, 20263
Nov 3, 20263
Nov 2, 20263
Nov 1, 20263
Oct 31, 20263
Oct 30, 20263
Oct 29, 20263
Oct 28, 20263
Oct 27, 20263
Oct 26, 20263
Oct 25, 20263
Oct 24, 20263
Oct 23, 20263
Oct 22, 20263
Oct 21, 20263
Oct 20, 20263
Oct 19, 20263
Oct 18, 20263
Oct 17, 20263
Oct 16, 20263
Oct 15, 20263
Oct 14, 20263
Oct 13, 20263
Oct 12, 20263
Oct 11, 20263
Oct 10, 20263
Oct 9, 20263
Oct 8, 20263
Oct 7, 20263
Oct 6, 20263
Oct 5, 20263
Oct 4, 20263
Oct 3, 20263
Oct 2, 20263
Oct 1, 20263
Sep 30, 20263
Sep 29, 20263
Sep 28, 20263
Sep 27, 20263
Sep 26, 20263
Sep 25, 20263
Sep 24, 20263
Sep 23, 20263
Sep 22, 20263
Sep 21, 20263
Sep 20, 20263
Sep 19, 20263
Sep 18, 20263
Sep 17, 20263
Sep 16, 20263
Sep 15, 20263
Sep 14, 20263
Sep 13, 20263
Sep 12, 20263
Sep 11, 20263
Sep 10, 20263
Sep 9, 20263
Sep 8, 20263
Sep 7, 20263
Sep 6, 20263
npm weekly downloads

97+86 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 202697
Dec 4, 2026103
Dec 3, 2026121
Dec 2, 2026114
Dec 1, 2026108
Nov 30, 202690
Nov 29, 202693
Nov 28, 202688
Nov 27, 202684
Nov 26, 202682
Nov 25, 202695
Nov 24, 2026113
Nov 23, 2026120
Nov 22, 2026124
Nov 21, 2026140
Nov 20, 2026135
Nov 19, 2026128
Nov 18, 2026117
Nov 17, 202693
Nov 16, 202691
Nov 15, 202686
Nov 14, 202675
Nov 13, 202675
Nov 12, 202684
Nov 11, 202676
Nov 10, 202677
Nov 9, 202660
Nov 8, 202650
Nov 7, 202649
Nov 6, 202651
Nov 5, 202632
Nov 4, 202639
Nov 3, 202679
Nov 2, 202691
Nov 1, 202698
Oct 31, 202696
Oct 30, 202697
Oct 29, 202695
Oct 28, 202679
Oct 27, 202651
Oct 26, 202641
Oct 25, 202636
Oct 24, 202644
Oct 23, 202635
Oct 22, 202643
Oct 21, 202654
Oct 20, 202648
Oct 19, 202655
Oct 18, 202660
Oct 17, 202660
Oct 16, 202682
Oct 15, 202679
Oct 14, 202683
Oct 13, 202676
Oct 12, 202685
Oct 11, 202682
Oct 10, 202692
Oct 9, 202675
Oct 8, 202681
Oct 7, 202699
Oct 6, 2026110
Oct 5, 202695
Oct 4, 2026102
Oct 3, 202693
Oct 2, 202689
Oct 1, 202692
Sep 30, 202671
Sep 29, 202676
Sep 28, 202673
Sep 27, 202665
Sep 26, 202657
Sep 25, 202658
Sep 24, 202653
Sep 23, 202656
Sep 22, 202638
Sep 21, 202641
Sep 20, 202637
Sep 19, 202677
Sep 18, 202678
Sep 17, 202672
Sep 16, 202661
Sep 15, 202660
Sep 14, 202656
Sep 13, 202655
Sep 12, 202613
Sep 11, 202612
Sep 10, 20269
Sep 9, 20265
Sep 8, 20265
Sep 7, 20266
Sep 6, 202611

Each point is npm's rolling 7-day download count.

Health Score

58/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1289282287-root.svg)](https://payloaddirectory.dev/plugins/1289282287-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1289282287-root"><img src="https://payloaddirectory.dev/badge/1289282287-root.svg" alt="Payload Directory"></a>
Updated Jul 17, 2026Created Jul 4, 2026Published Jul 17, 2026

README

@yairl/payload-db-backup-restore

Admin UI for exporting and restoring selected Payload CMS collections as a portable JSON file. Ships an /admin/backup view and a sidebar shortcut. Round-trips ObjectIds and Dates faithfully via EJSON.

Works with any Payload 3 project on MongoDB.

Screenshot

Install

pnpm add @yairl/payload-db-backup-restore
# or
npm install @yairl/payload-db-backup-restore
# or
yarn add @yairl/payload-db-backup-restore

Use

Add the plugin to your Payload config:

// payload.config.ts
import { buildConfig } from 'payload';
import { backupPlugin } from '@yairl/payload-db-backup-restore';

export default buildConfig({
  plugins: [
    backupPlugin(),
  ],
  // ...rest of your config
});

Regenerate Payload's importMap so it picks up the plugin's components, then start dev:

pnpm payload generate:importmap
pnpm dev

Visit http://localhost:3000/admin/backup. You'll see every collection listed with checkboxes and two actions: Download backup (writes a .json file) and Restore from file (reads one back). The sidebar gets a "Backup & restore" link at the bottom.

First-time setup: "Failed to load collections: HTTP 401"

If the view loads but no collections appear and you see "Failed to load collections: HTTP 401", the plugin's default access check isn't matching your Users collection shape.

Why: the default is req.user.roles.includes('admin') — but Payload's out-of-the-box template doesn't add a roles field to users, so every existing user has roles === undefined and the check returns false.

Two ways to fix — pick one:

A. Loosen the check for testing — any logged-in user can back up/restore:

backupPlugin({
  access: (req) => !!req.user,
})

Reasonable when the whole /admin panel is already gated to trusted staff.

B. Add a roles field to your Users collection — production-grade, matches the default check:

// src/collections/Users.ts
const Users: CollectionConfig = {
  slug: 'users',
  auth: true,
  fields: [
    // your existing fields...
    {
      name: 'roles',
      type: 'select',
      hasMany: true,
      defaultValue: ['admin'],
      options: [
        { label: 'Admin', value: 'admin' },
        { label: 'User',  value: 'user' },
      ],
    },
  ],
};

Existing users need the role set once — via the admin UI or, if you have many, once in mongo:

db.users.updateMany({}, { $set: { roles: ['admin'] } })

Options

backupPlugin({
  enabled: true,                     // default
  route: '/backup',                  // default — mounted at /admin/backup
  showInSidebar: true,               // default
  access: (req) =>                   // default: role check
    Array.isArray(req.user?.roles) && req.user.roles.includes('admin'),
  packageName: '@yairl/payload-db-backup-restore',  // only override if you've forked/renamed
});

access: (req: PayloadRequest) => boolean

Called on every backup/restore request AND on the view render. Return true to permit, false to reject (401). The default checks req.user.roles for the string 'admin'. Common overrides:

// Any authenticated user
access: (req) => !!req.user,

// A specific collection field
access: (req) => req.user?.collection === 'admins',

// Multiple roles allowed
access: (req) =>
  Array.isArray(req.user?.roles) &&
  ['admin', 'devops'].some(r => req.user.roles.includes(r)),

route: string

The URL segment under /admin where the view is mounted. Change if you already have a /admin/backup route in your project.

showInSidebar: boolean

Set to false to skip the "Backup & restore" sidebar entry. The /admin/backup route still exists — you'd link to it yourself.

What the backup file contains

A single JSON document with this shape:

{
  "version": 1,
  "exportedAt": "2026-07-04T09:12:34.567Z",
  "exportedBy": "[email protected]",
  "collections": ["posts", "media", "_posts_versions"],
  "data": {
    "posts":            [ /* every doc from `posts` */ ],
    "media":            [ /* every doc from `media` */ ],
    "_posts_versions":  [ /* drafts/version rows, when versions.drafts is on */ ]
  }
}
  • Written with EJSON.stringify(..., { relaxed: false }) so ObjectId, Date, Decimal128, etc. round-trip byte-for-byte.
  • When a collection has versions.drafts: true, its _<slug>_versions sidecar is included automatically. Both the main and the versions collections are restored together as long as the base slug is selected.

What restore does

On the server, for each selected collection, restore uses raw Mongoose (db.collections[slug].insertMany(docs)) — not payload.create. That means:

  • Hooks don't fire (beforeChange, afterChange, etc.). Good — you don't want setTitle overwriting titles or revalidatePage firing thousands of times during a bulk restore.
  • _id is preserved exactly as written in the backup.
  • Validation isn't rerun — the source is a Payload backup, which is trusted to be well-formed.

If Drop before restore is checked (the default), the target collection is emptied with deleteMany({}) first. If unchecked, insertMany is used with ordered: false — duplicates by _id will error per-row but the rest succeed.

What it does NOT back up

  • Uploaded files on disk. The media collection's metadata rows (filenames, alt text, sizes) are included, but the actual blob files under your staticDir are not. Snapshot those separately (tar / rsync / S3 sync).
  • Global settings from admin. Only regular collections are handled.
  • Payload's internal system collections (like payload-preferences, payload-locked-documents). These aren't in payload.config.collections.

Endpoints

The plugin mounts three endpoints. If you want to script backups from the CLI:

GET  /api/db-backup/collections   → { collections: [{ slug, hasVersions }, ...] }
POST /api/db-backup/export        → binary JSON body, Content-Disposition attachment
POST /api/db-backup/import        → multipart: file, collections, dropFirst

All three require the access check to pass. Authenticate the same way you would any Payload API call (session cookie or Authorization: JWT <token>).

Compatibility

  • Payload: ^3.0.0
  • Database adapter: MongoDB only (@payloadcms/db-mongodb). Postgres/SQLite adapters don't expose the raw model in the same shape.
  • Node.js: >= 20.9
  • React: 18 or 19
  • Next.js: whichever version Payload 3 supports on your project.

Development

pnpm install
pnpm build       # tsc → dist/
pnpm dev         # tsc --watch, useful when using pnpm link

To develop against a local Payload project without publishing:

cd payload-db-backup-restore && pnpm build
cd ../my-payload-project   && pnpm link ../payload-db-backup-restore

Rebuild and Payload's importMap regen after any source change.

License

MIT

Similar plugins