# How to back up a better-sqlite3 database

Use db.backup() to save a consistent SQLite copy while the app writes, then open the copy readonly and check it.

## Copy and check a live SQLite database

```js
import Database from "better-sqlite3";
import { mkdtemp, realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

if (!process.argv[2]) {
  throw new Error("Pass the path to an existing SQLite database file");
}
const sourcePath = await realpath(process.argv[2]);
const restoreDirectory = await mkdtemp(join(tmpdir(), "sqlite-restore-"));
const restorePath = join(restoreDirectory, "restored.sqlite");
const source = new Database(sourcePath, {
  readonly: true,
  fileMustExist: true,
});
try {
  await source.backup(restorePath);
} finally {
  source.close();
}

const restored = new Database(restorePath, {
  readonly: true,
  fileMustExist: true,
});
try {
  const checks = restored.pragma("integrity_check");
  if (checks.length !== 1 || checks[0].integrity_check !== "ok") {
    throw new Error("The backup failed its integrity check");
  }
  console.log(restorePath);
} finally {
  restored.close();
}
```

## Make a one-time backup

In a Node.js project with `better-sqlite3` installed, save the example as `backup.mjs`. Run `node backup.mjs /var/lib/app/main.sqlite` with the path your app opens. The example prints the path to the checked copy. Store the copy on another machine or in a bucket so you can restore it if you lose the app host.

Wait for the [`backup()` promise](https://github.com/WiseLibs/better-sqlite3/blob/master/docs/api.md#backupdestination-options---promise) before closing the database or uploading the copy. Writes from other connections can restart a copy in progress, so a busy database may take longer. Copying through SQLite includes committed writes that may still be in the WAL file.

## Restore into a separate location

Open the checked copy with the same driver and query an application record you expect to find. Start a test instance of the app using that copy before you replace the production database. To replace the live database, stop all processes that use it and move the old database and any journal files aside together. Put the checked copy in place, give the app user permission to read and write it, and start the app.

## Keep continuous backups

[Install your Litebackup server](/install) first. As the app user, install the client and join with a token from **Machines**, **Add machine** in the console. These commands back up the same file and restore a copy without changing the app's connection.

```bash
# Install the Litebackup client and join the backup server.
curl --fail --silent --show-error --location https://litebackup.com/cli.sh | bash
export LITEBACKUP_API_KEY=JOIN_TOKEN@HOST
litebackup install service --api-key "${LITEBACKUP_API_KEY}"
```

After the client joins, start continuous backup and send the first version.

```bash
# Start continuous backup and send the first SQLite version.
litebackup start /var/lib/app/main.sqlite app/
litebackup sync app/main.sqlite
```

After the first version syncs, restore it into a fresh directory.

```bash
# Restore the saved SQLite version into a fresh directory and check it.
# Runs on Linux and macOS.
RESTORE_DIR=$(mktemp -d)
litebackup restore app/main.sqlite "${RESTORE_DIR}/restored.sqlite"
sqlite3 -bail -readonly "${RESTORE_DIR}/restored.sqlite" 'PRAGMA integrity_check;'
```

The last command should print `ok`.

## Install

[Install Litebackup](/install) to keep versions of your Node.js application's SQLite database. See [SQLite backup methods](/sqlite-backup) for Amazon S3 and [the restore guide](/sqlite-point-in-time-restore) to recover a version from before a mistake.
