Shopify App Session Storage: Move Off SQLite Safely

The Shopify React Router app template keeps session storage in a SQLite file through PrismaSessionStorage, and that file holds every shop’s offline access token. It is fine on one instance with a persistent disk. Anywhere else, move it to Postgres before launch: change the Prisma provider, replace the template’s SQLite-only migration, and make the adapter survive a database that is slow to start.

We worked through that move against the current template (commit 81eb98b, October 2026) with @shopify/shopify-app-session-storage-prisma 11.0.3, Prisma 6.19.3 and PostgreSQL 18.6 running locally through the embedded-postgres package. The errors quoted below are the ones we got.

What does the Session table actually hold?

One row per session. For an embedded app the row that matters is the offline session, whose id is offline_ plus the shop domain (offline_example.myshopify.com). It carries the access token your webhooks, background jobs and unauthenticated.admin(shop) calls use, and, with expiringOfflineAccessTokens switched on (the template’s default), the refreshToken and refreshTokenExpires columns that our post on migrating to expiring offline tokens covers. Online sessions, one per staff user, sit alongside it if you turn on useOnlineTokens.

Losing the table hurts in a lopsided way. The next time a merchant opens your app in the admin, the token exchange strategy in @shopify/shopify-app-react-router finds no valid session, exchanges the session token for a new offline token and stores it. Nothing running in the background can recreate it. Until the merchant opens the app, unauthenticated.admin throws SessionNotFoundError (“Could not find a session for shop … when creating unauthenticated admin context”), and any job that needs a token for that shop stops.

Shopify’s deployment guide also recommends encrypting session data at rest, because those rows are live credentials for your merchants’ stores.

When is SQLite good enough?

The template README says SQLite “works in production if your app runs as a single instance”. The deployment guide spells out the conditions: a container with filesystem access, a separate volume if you want more than one web container, and a disk that is not wiped. Fly.io is the guide’s own example of a host that can put idle containers to sleep and reset the disk, taking the database with it, unless the file sits on a volume.

So one long-running VM or container with a mounted volume and a backup is a legitimate setup. Serverless functions, autoscaling groups and anything with an ephemeral filesystem are not. Each instance gets its own empty file, and merchants appear to lose their install at random.

Why does prisma migrate deploy fail on Postgres?

Because the migration that ships with the template is SQLite SQL. prisma/migrations/20240530213853_create_session_table/migration.sql declares expires and refreshTokenExpires as DATETIME, a type PostgreSQL does not have. Change the provider and point DATABASE_URL at Postgres. The template’s setup script then fails:

Applying migration `20240530213853_create_session_table`
Error: P3018

A migration failed to apply. New migrations cannot be applied before the error is recovered from.

Database error code: 42704

Database error:
ERROR: type "datetime" does not exist

Prisma normally catches a provider switch for you: per its limitations page, Migrate compares the configured provider with the one recorded in migrations/migration_lock.toml and prints a mismatch error. The template’s repository does not include a migration_lock.toml, so that check has nothing to compare against and the SQLite SQL goes straight to Postgres.

The second run is worse. Prisma has now recorded a failed migration in _prisma_migrations, and every later migrate deploy stops with P3009: migrate found failed migrations in the target database. The template’s Dockerfile runs npm run docker-start, which is npm run setup && npm run start, so the container exits on every boot. Replacing the migration files does not clear it either. We deleted the folder, generated a correct migration, and still got P3009 until we resolved the old record.

How do you move Shopify app session storage to Postgres?

Point the datasource at an environment variable:

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

Then replace the migration history rather than editing the old file. Prisma’s guidance for a provider change is to remove the migrations folder and start a new history. prisma migrate dev does that, but it needs a shadow database, which means the database user must be allowed to create databases. migrate diff writes the same baseline without touching a database:

rm -rf prisma/migrations
mkdir -p prisma/migrations/0_init
npx prisma migrate diff \
  --from-empty \
  --to-schema-datamodel prisma/schema.prisma \
  --script > prisma/migrations/0_init/migration.sql
printf 'provider = "postgresql"\n' > prisma/migrations/migration_lock.toml
npx prisma migrate deploy

The generated SQL uses TIMESTAMP(3) for both date columns and adds a Session_pkey constraint. Commit the lock file this time, so the next provider change fails loudly. Local development then needs a Postgres too. The Google Cloud Run guide keeps SQLite locally with a second schema.prod.prisma, but that means two schemas and two migration histories to keep in step, and we would rather run one database type everywhere.

If the SQLite migration already ran against production

Tell Prisma that the failed migration was rolled back, then deploy the new baseline:

npx prisma migrate resolve --rolled-back 20240530213853_create_session_table
npx prisma migrate deploy

That cleared P3009 for us, applied 0_init, and prisma migrate status reported the schema as up to date. That works because PostgreSQL rolled the failed CREATE TABLE back, so there was no half-built table left behind. Check for a stray Session table before you deploy anyway: 0_init creates it without IF NOT EXISTS and fails if one is there.

Why does it say the Session table does not exist when it does?

PrismaSessionStorage checks for its table once, in the constructor, which runs when shopify.server.ts is imported. By default it tries twice, five seconds apart. A Postgres that scales to zero, or a database container that starts after the app container, can miss that window. The adapter then stores a rejected promise, and every later loadSession or storeSession throws:

MissingSessionTableError: Prisma session table does not exist. This could happen for a few reasons, see https://github.com/Shopify/shopify-app-js/tree/main/packages/apps/session-storage/shopify-app-session-storage-prisma#troubleshooting for more information

It keeps throwing after the database comes back. We started the adapter with Postgres stopped, brought Postgres up 14 seconds later, and at 25 seconds loadSession still threw MissingSessionTableError. Nothing in @shopify/shopify-app-react-router 4.0.3 calls the adapter’s isReady(), which is the only method that re-polls, so a process in this state stays broken until it restarts. The error text sends you to the migration checklist, when the table exists and only the first connection failed.

Two changes fix it. Give the adapter a start-up window that matches your database, using the options its README documents:

import "@shopify/shopify-app-react-router/adapters/node";
import {
  ApiVersion,
  AppDistribution,
  shopifyApp,
} from "@shopify/shopify-app-react-router/server";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import prisma from "./db.server";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: ApiVersion.October26,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma, {
    connectionRetries: 10, // default 2
    connectionRetryIntervalMs: 3000, // default 5000
  }),
  distribution: AppDistribution.AppStore,
  future: {
    expiringOfflineAccessTokens: true,
  },
});

export default shopify;
export const authenticate = shopify.authenticate;
export const sessionStorage = shopify.sessionStorage;

Then give your host something to restart on. shopify.sessionStorage is typed as the adapter you passed in, so a route can call isReady() directly:

import { sessionStorage } from "../shopify.server";

// Point the platform's health check at /healthz. isReady() re-polls
// the table and, on success, clears the adapter's failed start-up state.
export const loader = async () => {
  const ready = await sessionStorage.isReady();
  return new Response(ready ? "ok" : "session storage unavailable", {
    status: ready ? 200 : 503,
    headers: { "Cache-Control": "no-store" },
  });
};

When the check succeeds, the process recovers without a restart. When the database is down, the loader takes the full retry window to answer, 30 seconds with the settings above, so the health check timeout has to be longer than that or you will read every slow probe as a failure.

What about MySQL, Redis and the other adapters?

On MySQL, Prisma maps String to VARCHAR(191), which is what the warning in the adapter README is about. Running migrate diff against the template schema with the MySQL provider gives VARCHAR(191) for accessToken, refreshToken and scope. Twelve common read and write scopes already come to 183 characters, so an app that asks for a few more will fail to store its session. Add @db.Text to scope before the first migration.

Shopify also publishes non-Prisma adapters: -postgresql, -mysql, -sqlite, -redis, -mongodb, -dynamodb, -kv (Cloudflare KV) and -drizzle, all under @shopify/shopify-app-session-storage-*. If the app has no other database, one of those saves you running Prisma just for one table. If it does, keep sessions in the same database, so the cleanup in our app/uninstalled webhook post can delete a shop’s sessions and its data in one transaction.

Whatever you choose, pin the ORM. The Prisma adapter’s peer range is prisma@^6.19.0, while the Prisma 6 CLI’s update banner currently suggests a version 8 release candidate.

What we would do

For an app headed to the App Store, we would move session storage to Postgres before the first real install, while the table is empty and a new baseline migration costs nothing. We would commit migration_lock.toml, raise connectionRetries to cover the database’s cold start, and point the host’s health check at isReady().

We would keep SQLite only for a custom app on one machine with a mounted, backed-up volume. That is the single-instance case the template README says SQLite handles in production.

We build and maintain embedded Shopify apps, including moving template apps onto production databases and hosting. Our Shopify development page covers that work.

Need this built properly?

Get in touch

Hack the planet!