SynqDocs
Guides

Choose a session store

Where @synqauth/nextjs keeps a signed-in person's tokens. One server can keep them in the sealed cookie; an app on several servers or serverless functions needs a store they all share. Ready-made stores for Redis and Valkey, Upstash, Vercel, Cloudflare and Postgres.

@synqauth/nextjs keeps each person's session on your app's server, never in the browser. By default the whole session lives in a sealed, HttpOnly cookie. With a store, the cookie holds only the session's id, and the tokens live in the store.

The store matters because Synq rotates refresh tokens. Each refresh spends the refresh token it used and returns a new one, and when a spent one comes back Synq ends the whole session, since that is what a stolen token looks like. So when two requests refresh one session at once, the slower one signs the person out. One server process prevents that with a lock in its own memory. Several processes (replicas, serverless functions, containers behind a load balancer) need a store with one lock per session that all of them share.

Which store

Where your app runsUse
One server process: next start on one machine, one containerThe cookie: no store
Replicas or containers, with Redis or Valkeyioredis or node-redis
Vercel, Netlify or another serverless hostUpstash, which is also Vercel's Redis
Cloudflare Workers, through OpenNextDurable Objects
Anywhere you have Postgres and no RedisPostgres

synqAuth() refuses cookie sessions where VERCEL, AWS_LAMBDA_FUNCTION_NAME, NETLIFY, K_SERVICE or KUBERNETES_SERVICE_HOST is set, since those hosts run more than one process. Pass allowSingleProcessCookieMode: true only if your app really runs one.

A store also lets your server end a session: deleting it signs the person out on their next request. A cookie can't be taken back.

What every store does

Each store below is an import of its own, @synqauth/nextjs/stores/<name>, so your app bundles only the one it uses. None brings a database driver with it: you install your driver and pass its client in, and the store calls only what it needs of it.

Every one of them:

  • keeps a session until its age runs out (sessionMaxAge, 30 days by default), then forgets it
  • gives each session one lock, held by one request at a time across every process that shares the store
  • lets a lock expire after 30 seconds should the process holding it die, so a crash never holds a session for good
  • releases a lock only for the request that holds it, in one step, never a lock that expired and another request took

Synq runs one test suite against every store: on stand-ins in every test run, and against a real Valkey, a real Postgres 18 and Upstash's REST API in CI.

The store holds the session's tokens as they are: the access tokens, the refresh token and the ID token, under synq:session:<id>. Keep it private, as you would your database: a password or ACL, TLS for anything that crosses a network, and no other tenant on it.

Redis or Valkey with ioredis

npm install ioredis

With pnpm, Yarn or Bun, it's pnpm add, yarn add or bun add, here and below.

src/synq.config.ts
import { defineSynqConfig } from '@synqauth/nextjs/config'
import { ioredisSessionStore } from '@synqauth/nextjs/stores/ioredis'
import Redis from 'ioredis'

export const synqConfig = defineSynqConfig({
  store: ioredisSessionStore(new Redis(process.env.REDIS_URL!)),
})

It takes ioredis's Redis and Cluster, and iovalkey's client, which keeps ioredis's commands. Each lock is SET … PX … NX, released by a script that deletes it only while it still holds the holder's token. Use a rediss:// URL wherever the connection leaves your private network.

Redis or Valkey with node-redis

npm install redis
src/synq.config.ts
import { defineSynqConfig } from '@synqauth/nextjs/config'
import { redisSessionStore } from '@synqauth/nextjs/stores/redis'
import { createClient } from 'redis'

const redis = createClient({ url: process.env.REDIS_URL })
redis.on('error', (error) => console.error('Redis:', error))

export const synqConfig = defineSynqConfig({ store: redisSessionStore(redis) })

It takes node-redis version 5 or later, createClient() or createCluster(). A client you pass unconnected is connected on first use, once, so the config module needs no top-level await. node-redis stops the process on an error event that nothing listens for, so listen for them.

Upstash Redis

npm install @upstash/redis
src/synq.config.ts
import { defineSynqConfig } from '@synqauth/nextjs/config'
import { upstashSessionStore } from '@synqauth/nextjs/stores/upstash'
import { Redis } from '@upstash/redis'

export const synqConfig = defineSynqConfig({
  store: upstashSessionStore(Redis.fromEnv()),
})

Upstash is reached over HTTPS, one request per command, so a serverless or edge function keeps no connection open. Redis.fromEnv() reads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN. The client parses the JSON it reads by default, and the store handles that: you don't have to turn it off.

Vercel

Vercel KV is now Upstash Redis, added from the Vercel Marketplace. Use the Upstash store: Redis.fromEnv() also reads the KV_REST_API_URL and KV_REST_API_TOKEN the integration sets, and @vercel/kv's kv is an Upstash client too, so an older project can pass it as it is.

A Redis from the Marketplace that gives you a REDIS_URL instead (Redis Cloud) takes the ioredis or node-redis store. A Neon Postgres takes the Postgres store over Neon's HTTP driver.

Cloudflare: Durable Objects

On Cloudflare Workers, keep sessions in Durable Objects. Each object handles one request at a time and its storage is strongly consistent, so a lock is held by one request in every isolate and location, and a session read after a refresh is the refreshed one. The store keeps each key in an object of its own, SynqSessionObject, whose alarm deletes it once it expires.

Export the class from your Worker's entry. With OpenNext, that is a custom Worker beside the one it builds:

worker.ts
export { default } from './.open-next/worker.js'
export { SynqSessionObject } from '@synqauth/nextjs/stores/cloudflare'

Bind it, with a migration that makes the class, in your wrangler configuration:

wrangler.jsonc
{
  "main": "worker.ts",
  "durable_objects": {
    "bindings": [{ "name": "SYNQ_SESSIONS", "class_name": "SynqSessionObject" }],
  },
  "migrations": [{ "tag": "synq-sessions", "new_sqlite_classes": ["SynqSessionObject"] }],
}

Bindings are read during a request, so pass a function that reads it:

src/synq.config.ts
import { getCloudflareContext } from '@opennextjs/cloudflare'
import { defineSynqConfig } from '@synqauth/nextjs/config'
import { durableObjectSessionStore } from '@synqauth/nextjs/stores/cloudflare'

export const synqConfig = defineSynqConfig({
  store: durableObjectSessionStore(() => getCloudflareContext().env.SYNQ_SESSIONS),
})

Cloudflare: Workers KV

Workers KV can hold sessions, with two limits to know first:

  • It has no "set if absent", so it can't hold a lock. The KV store keeps its locks in the same SynqSessionObject Durable Objects, or, if you say lock: 'per-isolate', in each isolate's memory alone. Isolates don't share that memory, so two of them can refresh one session at once and Synq signs the person out.
  • It is eventually consistent. A write is seen at once at the location that made it, and at other locations up to 60 seconds later. A person whose requests reach two locations within that minute can be refreshed from a session that hasn't caught up, with a refresh token already spent, and Synq signs them out. The lock can't prevent that: the stale copy is in KV itself.

Neither puts a token at risk; each can sign a person out. Use the Durable Objects store or Redis unless sessions are read far more often than they are refreshed and the occasional sign-out is acceptable.

src/synq.config.ts
import { getCloudflareContext } from '@opennextjs/cloudflare'
import { defineSynqConfig } from '@synqauth/nextjs/config'
import { cloudflareKvSessionStore } from '@synqauth/nextjs/stores/cloudflare'

const env = () => getCloudflareContext().env

export const synqConfig = defineSynqConfig({
  store: cloudflareKvSessionStore(() => env().SESSIONS, { lock: () => env().SYNQ_SESSIONS }),
})

KV keeps a key for 60 seconds at least, so the store keeps each session's own expiry with it and reads nothing once that has passed.

Postgres

npm install pg
src/synq.config.ts
import { defineSynqConfig } from '@synqauth/nextjs/config'
import { postgresSessionStore } from '@synqauth/nextjs/stores/postgres'
import { Pool } from 'pg'

export const sessions = postgresSessionStore(
  new Pool({ connectionString: process.env.DATABASE_URL }),
)

export const synqConfig = defineSynqConfig({ store: sessions })

It takes any driver with a query(text, values) that uses $1 parameters: pg's Pool and Client as they are, and Neon's neon() over HTTP, which suits serverless functions:

import { neon } from '@neondatabase/serverless'

export const sessions = postgresSessionStore(neon(process.env.DATABASE_URL!))

postgres.js fits as { query: (text, values) => sql.unsafe(text, values) }.

Make the table once, in a migration:

create table if not exists "synq_sessions" (key text primary key, value text not null, expires_at timestamptz not null);
create index if not exists "synq_sessions_expires_at_idx" on "synq_sessions" (expires_at);

postgresSessionTableSql() gives you those two statements for your migration tool, and sessions.createTable() runs them, for an app without migrations. Pass table: 'auth.sessions' to use another name or schema.

A lock is a row taken with INSERT … ON CONFLICT DO UPDATE … WHERE the holder's time has run out, which Postgres runs atomically, so two servers never both take it. Expiry follows the database's clock, the same for every server.

Expired rows are never read. The store deletes them itself, up to 1,000 at a time, on the first write each hour in each process. An app that can sit idle for long, or that turns that off with sweepIntervalMs: false, deletes them on a schedule instead:

src/app/api/cron/sessions/route.ts
import { sessions } from '@/synq.config'

export async function GET(request: Request) {
  // Vercel Cron sends CRON_SECRET; anyone else is turned away.
  if (request.headers.get('authorization') !== `Bearer ${process.env.CRON_SECRET}`) {
    return new Response(null, { status: 401 })
  }
  return Response.json({ deleted: await sessions.deleteExpired() })
}

or, with pg_cron, in the database itself:

select cron.schedule('synq-sessions', '17 * * * *', $$delete from "synq_sessions" where expires_at <= now()$$);

Options every store takes

  • prefix (synq: by default) goes before every key, so one Redis can hold several apps' sessions apart.
  • lockTtlMs (30 seconds) is how long a lock outlives a process that died holding it. It must be over 20 seconds, twice the 10 seconds a request to Synq may take, so a slow refresh never outlives its lock.
  • lockWaitMs (35 seconds) is how long a request waits for a lock before giving up with lock_timeout.

An app that serves several sites shares one store between them: each site's storePrefix keeps its sessions apart.

Your own store

For any other store, keyValueSessionStore takes four operations (get, set with an expiry and an optional "only if absent", delete, and an atomic deleteIfEquals) and does the rest, as every store above does. Each store's module also exports its own operations (ioredisKeyValue, redisKeyValue, upstashKeyValue, postgresKeyValue, durableObjectKeyValue), so you can wrap them, for example to encrypt each session before it reaches the store. A store of your own from scratch implements SynqSessionStore: get, set, delete and lock. See the SDK reference.

On this page