This guide provides an overview of how to set up Activity.next for development or production.
Just want to try it locally? See the Quickstart for the fastest minimal setup (SQLite and the three core settings: host, secret phrase, and a database). This guide covers the full set of configuration options.
- Node.js 26 (the repo pins
engines.nodeto26.x) - Yarn 4 package manager via Corepack (
npm install -g corepack && corepack enable; the exact Yarn version is pinned by thepackageManagerfield inpackage.json) - Git (to clone the repository)
- A domain name (required for federation with other servers)
Activity.next supports multiple SQL database backends. Choose the one that best suits your needs:
- SQLite Setup Guide — Best for development or small instances
- PostgreSQL Setup Guide — Recommended for production deployments
- Only SQLite (
better-sqlite3) and PostgreSQL (pg) are supported; any otherACTIVITIES_DATABASE_CLIENTfails at startup (see the Environment Variables Guide)
Activity.next is configured through environment variables prefixed with ACTIVITIES_. Top-level options use ACTIVITIES_<KEY> (e.g., ACTIVITIES_HOST); nested options use ACTIVITIES_<SECTION>_<KEY> (e.g., ACTIVITIES_DATABASE_PG_HOST).
For a complete reference of all configuration options, see the Environment Variables Guide.
At minimum, you need to configure these settings:
Set your instance's domain name (without protocol or trailing slash):
ACTIVITIES_HOST=your-domain.tldSet a secret phrase for signing cookies and tokens:
# Generate with: openssl rand -base64 32
ACTIVITIES_SECRET_PHASE=your-random-secret-for-sessionsNote: The production runtime rejects an
ACTIVITIES_SECRET_PHASEshorter than 32 characters.
Restrict who can sign up to your instance by specifying allowed email addresses:
ACTIVITIES_ALLOW_EMAILS='["your_email@example.com"]'Tip: If
allowEmailsis set, only users with matching email addresses can register. This is recommended for personal or small-group instances.
One server can serve profiles on several domains (social.example, run.example, …). Each domain needs its own route to this server before the app can use it:
- DNS: point the domain (an
A/AAAArecord or aCNAME) at the same public address asACTIVITIES_HOST. - TLS: issue a certificate for the domain on whatever terminates HTTPS (your proxy, load balancer or hosting platform).
- Proxy: route the domain to this server and keep the original
Hostheader (or setX-Forwarded-Hostto it). A proxy that rewrites the host to the primary domain makes every request look like it arrived onACTIVITIES_HOST. Strip any client-suppliedX-Activity-Next-Hostheader at the reverse proxy unless the proxy itself sets it, and overwrite or strip client-suppliedX-Forwarded-Host— the application readsX-Activity-Next-HostandX-Forwarded-Hostahead ofHost, so forwarding an untrusted value lets callers spoof the request host (including routing to an embedded Bluesky PDS hostname). - Add it in the app: open Admin › Served domains › Add domain and enter the domain. The server asks
https://<domain>/.well-known/activities-domain-checkfor a proof only it can sign, and shows which of DNS, TLS and the Host header still needs work. The domain is saved as Off; Turn on runs the check again and only turns it on when it passes. - Sign-ups: on the domain's page, open sign-ups (with an optional list of allowed email addresses) and choose whether people who already have an account can add a profile there. A new domain starts with sign-ups closed.
- Identity and policies (optional): on the same page, give the domain its own name, description and contact email, and its own terms of service and privacy policy (Markdown). Each field says Same as server until you set it, and then falls back to Admin › Server settings. They apply only while the domain is on (an
ACTIVITIES_TRUSTED_HOSTSdomain: always); other server instances pick a change up within 15 seconds. The primary domain always uses the server's own, set on Admin › Server settings.
Domains can still be pinned in the environment with ACTIVITIES_TRUSTED_HOSTS; those show in Admin › Served domains as always on, and only their sign-up settings, identity and policies can be changed there. Existing users can always add a profile on them, except someone who joined through another domain's sign-ups: they need that domain's own sign-ups open to their address, or a profile there already (the same holds for the primary). A wildcard entry such as *.vercel.app stays environment-only: it lets forwarded preview hosts sign in, but never serves profiles or sign-ups.
Activity.next uses better-auth for authentication and supports local email/password accounts, passkeys, and two-factor authentication.
By default, media files are not stored (uploads are disabled). To enable media uploads, configure a storage backend:
ACTIVITIES_MEDIA_STORAGE_TYPE=fs
ACTIVITIES_MEDIA_STORAGE_PATH=./uploadsAccount archive exports and imports use the same bucket and credentials as media. They need these permissions in addition to the media policy: s3:PutObject, s3:GetObject, s3:DeleteObject and s3:AbortMultipartUpload (to clean up an unfinished upload) on both archives/* and imports/*; s3:ListBucket on the bucket, limited to both prefixes with a condition; and optionally s3:ListMultipartUploadParts on both prefixes. Without the last permission an export still completes, with a warning in the logs, but cannot double-check its part ETags. Add a bucket lifecycle rule that aborts incomplete multipart uploads after a day or two.
This is an extra IAM identity policy for the app's S3 credentials, added alongside the existing media policy (not a replacement for it, and not a bucket policy). If S3 answers 403 instead of 404 for missing keys, the s3:prefix condition on s3:ListBucket may be left off.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts"
],
"Resource": [
"arn:aws:s3:::my-bucket/archives/*",
"arn:aws:s3:::my-bucket/imports/*"
]
},
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::my-bucket",
"Condition": {
"StringLike": { "s3:prefix": ["archives/*", "imports/*"] }
}
}
]
}ACTIVITIES_MEDIA_STORAGE_TYPE=s3 # or 'object' for S3-compatible
ACTIVITIES_MEDIA_STORAGE_BUCKET=my-bucket
ACTIVITIES_MEDIA_STORAGE_REGION=us-east-1
# Optional: public CDN/custom domain used to serve media files.
# Account archives live in the same bucket under archives/ (exports) and
# imports/ (staged uploads), and embedded Bluesky PDS blobs live under
# pds-blobs/. The hostname must not serve any of these prefixes (or the bucket
# root) publicly. Exports are protected by a secret key segment plus the
# owner-checked download endpoint, not by the bucket; PDS blobs are served only
# through com.atproto.sync.getBlob with repo-status checks and sandbox headers.
# With this variable set, exports are streamed through the app instead of
# redirecting to a signed bucket URL. A streamed download lasts as long as the
# transfer, so on a host with a short request duration limit (serverless) a
# large export may be cut off; a client can resume it with a `Range: bytes=n-`
# request.
ACTIVITIES_MEDIA_STORAGE_HOSTNAME=media.example.com
# Optional: S3-compatible API endpoint for uploads/storage operations
ACTIVITIES_MEDIA_STORAGE_ENDPOINT=https://s3.example.comOptional storage limits:
ACTIVITIES_MEDIA_STORAGE_MAX_FILE_SIZE=209715200 # 200 MiB in bytes
ACTIVITIES_MEDIA_STORAGE_QUOTA_PER_ACCOUNT=1073741824 # 1 GiB in bytesAccount archive imports have a separate upload-size limit of 10 GiB by
default. Set ACTIVITIES_ACCOUNT_IMPORT_MAX_FILE_SIZE to a byte count to
change it; see the Environment Variables Guide.
Some uploads stream through the app as multipart/form-data: every media
upload on local (fs) media storage; the sync media endpoints
(POST /api/v1/media and /api/v2/media, which Mastodon clients use) and
custom emojis on any media backend; and fitness-file uploads and fitness-activity
imports on any fitness storage backend. Strava archive imports on S3/object
fitness storage go straight to the bucket through a presigned URL and fall back
to multipart only if that fails. The Next.js proxy (proxy.ts) is skipped for
multipart /api requests, so its 10 MB request-body buffer does not apply. The
per-file limit is ACTIVITIES_MEDIA_STORAGE_MAX_FILE_SIZE (or, when that is
unset, the admin media.maxFileSize setting) for media and
ACTIVITIES_FITNESS_STORAGE_MAX_FILE_SIZE for fitness files, on top of the
per-account quota. A reverse proxy in front of the app has its own request-body
limit (nginx's client_max_body_size defaults to 1 MB), which must be raised to
match.
Email is optional. Leave the email variables unset when the instance should not send account verification or notification messages. When email is configured, notification delivery is best effort: errors are logged, with no durable retries or delivery-status tracking.
The supported providers are SMTP, Resend, and AWS SES. If an explicit provider
value is unknown, including the removed lambda value, configuration fails
instead of silently disabling email. Before upgrading an instance that used
Lambda, migrate its configuration to one of the retained providers and remove
the Lambda-specific variables. No replacement provider is selected
automatically. See the Environment Variables Guide
for JSON precedence, malformed-JSON fallback behavior, and the requirement that
individual email variables include ACTIVITIES_EMAIL_TYPE.
ACTIVITIES_EMAIL_TYPE=smtp
ACTIVITIES_EMAIL_FROM=noreply@your-domain.tld
ACTIVITIES_EMAIL_SMTP_HOST=smtp.example.com
ACTIVITIES_EMAIL_SMTP_PORT=587
ACTIVITIES_EMAIL_SMTP_USER=your-username
ACTIVITIES_EMAIL_SMTP_PASSWORD=your-password
ACTIVITIES_EMAIL_SMTP_SECURE=falseACTIVITIES_EMAIL_TYPE=resend
ACTIVITIES_EMAIL_FROM=noreply@your-domain.tld
ACTIVITIES_EMAIL_RESEND_TOKEN=re_xxxxxxxxxxxxACTIVITIES_EMAIL_TYPE=ses
ACTIVITIES_EMAIL_FROM=noreply@your-domain.tld
ACTIVITIES_EMAIL_SES_REGION=us-east-1Background jobs (sending ActivityPub activities, processing uploads) use a queue. Without a queue configured, jobs run synchronously.
Wahoo webhook synchronization and date-range history import require a durable queue (database, QStash, or Cloud Tasks). The default synchronous mode cannot acknowledge a webhook before its FIT download and activity processing finish, or schedule delayed retries, so the Wahoo settings page disables automatic/history import in that mode. With ACTIVITIES_QUEUE_TYPE=database, run the database queue worker described in maintenance.md if the application process does not run the queue runner.
Note: Client libraries for queue providers (
@upstash/qstashand@google-cloud/tasks) are optional dependencies packaged as Yarn workspaces (@activities/qstashand@activities/cloudtasks). They are dynamically imported when the respective queue is enabled.
ACTIVITIES_QUEUE_TYPE=qstash
ACTIVITIES_QUEUE_URL=https://your-domain.tld/api/v1/queue/qstash
ACTIVITIES_QUEUE_TOKEN=your-qstash-token
ACTIVITIES_QUEUE_CURRENT_SIGNING_KEY=your-signing-key
ACTIVITIES_QUEUE_NEXT_SIGNING_KEY=your-next-signing-keyACTIVITIES_QUEUE_TYPE=cloudtasks
ACTIVITIES_QUEUE_NAME=activities-queue
ACTIVITIES_QUEUE_URL=https://your-domain.tld/api/v1/queue/cloudtasks
ACTIVITIES_QUEUE_CLOUDTASKS_LOCATION=europe-west1
ACTIVITIES_QUEUE_CLOUDTASKS_PROJECT_ID=your-gcp-project-id
# Optional authentication:
ACTIVITIES_QUEUE_CLOUDTASKS_SERVICE_ACCOUNT=service-account@project.iam.gserviceaccount.com
ACTIVITIES_QUEUE_CLOUDTASKS_AUDIENCE=https://your-domain.tld
ACTIVITIES_QUEUE_CLOUDTASKS_SECRET=your-shared-webhook-secretWeb push notifications require a VAPID key pair:
ACTIVITIES_PUSH_VAPID_PUBLIC_KEY=your-public-key
ACTIVITIES_PUSH_VAPID_PRIVATE_KEY=your-private-key
ACTIVITIES_PUSH_VAPID_EMAIL=mailto:admin@your-domain.tldTo run the service locally:
yarn devThe app will be available at http://localhost:3000.
To communicate with other servers in the Fediverse while running locally, you'll need a tunnel service to expose your local server to the internet:
- Set up a tunnel using Cloudflare Tunnel or ngrok
- Point the tunnel to
localhost:3000 - Use your tunnel's domain as the
hostin your configuration
After starting the application:
- Navigate to
https://your-domain.tld/auth/signup(if you setACTIVITIES_ALLOW_EMAILS, your email must be in it; any email works if you left it unset) - Create your account with email and password
- Log in and start interacting with the Fediverse
To deploy on Vercel:
- Fork this repository
- Connect it to your Vercel account
- Add the required environment variables (see Environment Variables Guide)
Note: Vercel deployments require an external PostgreSQL database and S3-compatible storage since Vercel has no persistent filesystem.
Activity.next provides official minimal Docker images at ghcr.io/llun/activities.next:main (the image is published with the main tag; there is no latest tag). The official image includes only the core application and SQLite dependencies to keep the image slim.
Basic Docker run command (uses SQLite by default):
docker run -p 3000:3000 \
-e ACTIVITIES_HOST=your.domain.tld \
-e ACTIVITIES_SECRET_PHASE=change-me-to-a-random-secret-at-least-32-chars \
-e ACTIVITIES_DATABASE_SQLITE_FILENAME=/opt/activities.next/data/data.sqlite \
-e ACTIVITIES_MEDIA_STORAGE_TYPE=fs \
-e ACTIVITIES_MEDIA_STORAGE_PATH=/opt/activities.next/data/uploads \
-v /path/to/local/storage:/opt/activities.next/data \
ghcr.io/llun/activities.next:mainImportant: Mount persistent data under
/opt/activities.next/dataas above — do not bind-mount/opt/activities.nextitself. That directory contains the application (the standaloneserver.js, static assets, etc.), so a host-path mount would shadow it and the container cannot start. See the SQLite Docker guide for preparing the mounted database file.
Docker image builds, including the migration step, do not need a production
ACTIVITIES_SECRET_PHASE. Set a real, stable secret of at least 32 characters
when running the image; the production runtime enforces that minimum.
Optional dependencies (such as PostgreSQL, Cloud Tasks, QStash, and optional email providers) are isolated in Yarn workspaces under packages/:
@activities/pg— PostgreSQL driver (pg)@activities/cloudtasks— Google Cloud Tasks client (@google-cloud/tasks)@activities/qstash— Upstash QStash client (@upstash/qstash)@activities/nodemailer— SMTP transport (nodemailer, included by default in Docker builds)@activities/resend— Resend client (resend)@activities/ses— AWS SES client (@aws-sdk/client-ses)
The Dockerfile includes @activities/nodemailer by default (ARG WORKSPACES="activities.next @activities/nodemailer"). Email delivery is disabled only when no ACTIVITIES_EMAIL_* provider is configured. If a provider is configured but its workspace is missing from the build (for example resend or ses on the default image), every send fails with a logged error instead of silently succeeding, so password reset, registration confirmation and email change report the failure and roll back; add the matching workspace to WORKSPACES.
Docker installs the selected workspaces from the root manifest, lockfile, Yarn configuration, every workspace manifest, and the Yarn patches in patches/ before copying application source. Source-only edits can therefore reuse the dependency layer; changes to those dependency files or WORKSPACES invalidate it. The install stays immutable and includes development dependencies needed by the build. When adding a workspace, add its manifest to the Dockerfile's COPY list at the same path under packages/. Dependency patches (yarn patch) live in patches/, not .yarn/patches/ (Docker builds ignore .yarn/): commit one with YARN_PATCH_FOLDER=./patches yarn patch-commit -s <folder>, check that the resolution it writes to package.json matches only the range you meant, and add a test that fails without the patch (see test/zodPatch.test.ts, which guards the zod 3 copy @atproto/* uses).
Docker builds require BuildKit and mount .next/cache during compilation to preserve Turbopack's compiler cache on a persistent builder. The cache is isolated by target platform, UID, GID, and WORKSPACES, with concurrent access locked, and is not copied into the runtime image. Ordinary GitHub Actions layer-cache export does not export cache-mount contents, so a fresh builder starts without this compiler cache; the application's CI build job caches .next/cache separately. Cache retention depends on the builder and its garbage collection.
To customize optional workspaces when building a Docker container, pass the WORKSPACES build argument:
# Example: Build with PostgreSQL, QStash, and default Nodemailer support
docker build --build-arg WORKSPACES="activities.next @activities/nodemailer @activities/pg @activities/qstash" -t activities.next:custom .
# Example: Build with all optional workspaces
docker build --build-arg WORKSPACES="activities.next @activities/nodemailer @activities/resend @activities/ses @activities/pg @activities/cloudtasks @activities/qstash" -t activities.next:full .To verify built Docker images locally:
node scripts/run.cjs scripts/maintenance/verifyDockerImages.tsPass --only <minimal|full> to verify just one of the two images; CI runs the verifier as two jobs (Docker Images Smoke Test (minimal) and Docker Images Smoke Test (full)), one per image.
For database-specific Docker deployment instructions:
Activity.next can host Bluesky accounts on a PDS embedded in the app, with one PDS hostname per served domain. It is off by default and preview-quality: accounts are always created fresh here, and moving an existing Bluesky account in is not supported (moving one out is).
Set ACTIVITIES_BLUESKY_PDS to a JSON object keyed by served domain:
ACTIVITIES_BLUESKY_PDS='{
"social.example": {
"enabled": true,
"hostname": "pds.social.example",
"allowEmails": ["alex@social.example"],
"allowActors": ["alex"],
"relays": ["https://bsky.network"]
}
}'enabledturns the domain's PDS on (defaultfalse).hostnameis the PDS's own hostname; it must not collide with a served domain or another PDS hostname, and yieldsdid:web:<hostname>.allowEmailsandallowActorsdecide who may create an account when the domain has no saved setting of its own; empty lists allow nobody. See Who can host below.relaysis an optional list of HTTPS relay origins to ask for a crawl at start-up (defaulthttps://bsky.network;[]disables crawl requests).clientSignIn(defaultfalse) lets members sign in to Bluesky apps with app passwords while the domain has no saved setting of its own. See Signing in from Bluesky apps below.
Unset or blank turns the PDS off; malformed JSON or an invalid entry turns it off and logs a warning, and a hostname used twice or equal to a served domain drops only that domain. See Environment Variables for the full schema.
The environment's allowEmails and allowActors are the fallback: they decide only while the domain has no saved setting. An admin can set it per domain in Admin › Served domains › Bluesky hosting, which shows when that domain has an enabled PDS entry:
- Nobody — no one may host an account on the domain.
- Listed accounts — only the email addresses and
username@domainprofiles entered there. - Everyone on this domain — any profile on the domain whose account is approved and confirmed. Suspended, unconfirmed, unapproved, disabled and deleting accounts are still refused.
The setting only decides who. An existing hosted account it no longer allows keeps its repo and posts and can still be turned off or deleted, but can't be turned back on or have its handle or recovery key changed. The PDS hostname, relays and whether the domain's PDS is on stay in ACTIVITIES_BLUESKY_PDS. Clearing the setting returns the domain to the environment's lists. The bare-domain handle stays admin-only, and <name>.<PDS hostname> handles need the wildcard DNS record and certificate below.
A member with an active hosted account can sign in to the official Bluesky app (and other apps that sign in with app passwords) once the domain's Sign in from Bluesky apps switch is on. It is off by default; an admin sets it per domain in Admin › Served domains › Bluesky hosting, and while the domain has no saved setting clientSignIn decides. The switch is read on every request, so turning it off, or turning the domain off in Admin, stops new sign-ins and every app call at once (the methods answer 501); an Admin save that turns the switch off also ends every app session on the domain (app passwords stay, and members can still revoke them in Settings). Turning the account off, suspending or deleting it ends its app sessions too.
Turn the switch on only where the app sees each client's address: behind the PDS gateway (its X-Activity-Next-Client-IP is used), or behind a proxy you trust with ACTIVITIES_TRUST_PROXY_IP_HEADERS=true and ACTIVITIES_TRUST_PROXY_IP_HEADER pinned to the header it overwrites: sign-in, and the upload tokens the video service calls back with, are limited per client IP, and without a trusted address every client shares one bucket per domain (a one-time warning says so), which one caller can fill for everyone.
The server needs ACTIVITIES_BLUESKY_PDS_SESSION_KEYS, the HMAC keys that sign app session tokens (see Environment Variables). Generate a secret with openssl rand -base64 32, keep it in your secret store, and put a new key first when rotating. Without it app sign-in is refused.
The member then:
- Opens Settings › Other networks, and under the hosted account creates an app password: a name, Allow direct messages (off by default), and their current site password (a profile with only a passkey signs out and back in first: a sign-in from the last 10 minutes confirms it instead).
- In the Bluesky app taps Sign in, chooses Custom under Hosting provider and pastes
https://<PDS hostname>, then enters@<handle>and the app password.
The app password is shown once. Revoking it signs out every app it signed in. The site password is never accepted by the PDS, and an app password cannot list, create or revoke app passwords.
Signed in, the app can browse: timelines, profiles, notifications, search, settings and, for an app password with Allow direct messages, chats. The PDS forwards those calls to the services configured below, and a few moderation and feed-feedback calls to the labeler or feed generator the app names (see Embedded Bluesky PDS). The app can also post, reply, quote, like, repost, follow, block, manage lists and starter packs, edit the profile and upload images and video; those records go into the hosted repo and out on the firehose, but they do not show in activities.next itself yet. Account settings (email, handle, password, deleting or moving the account) stay in Settings › Other networks on the website.
Limits per account (media storage and the 24-hour clean-up apply to the website's own uploads too):
- Writes cost points (a create 3, an update 2, a delete 1): 5,000 points an hour and 35,000 a day. Uploads: 100 an hour and 500 a day. Record writes also share the 3,000 calls per 5 minutes the app's other calls use. Over a limit the app gets
429withRetry-After. - Addresses of labelers and feed generators the app names: 60 lookups per 5 minutes (an address is remembered for 10 minutes); past that the app gets
429. - One upload is at most 50 MiB; one request body of records at most 2 MiB. Uploads running at once may declare 200 MiB together (one without a
Content-Lengthcounts as 50 MiB); past that the app gets429. - Media storage: 10 GiB of blobs in all, of which at most 1 GiB may be uploads no post uses yet. An upload past either is refused.
- An upload no record uses is private (never served) and is deleted with its file after 24 hours by the retention sweep that also prunes old firehose events.
- No writes are accepted while a move out is under way or after it.
- An upload token the app got for the video service (
getServiceAuth) keeps working until it expires, at most 30 minutes, even if the app password that asked for it is revoked first, as on Bluesky's own PDS.
The profile's display name, bio, avatar and banner still follow the fediverse profile: a profile edit on the website replaces those four fields of the Bluesky profile and keeps everything else the app set (pinned post, pronouns, website, labels).
ACTIVITIES_BLUESKY_PDS_ROTATION_KEY is the instance-wide secp256k1 private key (64 hex characters) that signs the did:plc operations for every hosted account. Generate one and keep it backed up:
openssl rand -hex 32Losing it means this server can no longer update the DIDs it hosts; the owner's recovery key is the way back. Creating a hosted account is refused while the key is unset or invalid. Never commit it or log it.
ACTIVITIES_BLUESKY_PLC_DIRECTORY_URLis the PLC directory the PDS submitsdid:plcoperations to and reads the address of adid:plclabeler or feed generator from (an https origin with no path, query, fragment or credentials; defaulthttps://plc.directory).ACTIVITIES_BLUESKY_APPVIEW_URLandACTIVITIES_BLUESKY_APPVIEW_DIDare the AppView a hosted account'sapp.bsky.*calls go to (defaulthttps://api.bsky.appanddid:web:api.bsky.app#bsky_appview). Set both together: another AppView refuses tokens addressed to Bluesky's.ACTIVITIES_BLUESKY_CHAT_URLandACTIVITIES_BLUESKY_CHAT_DIDare the chat service a signed-in app's direct messages go to (defaulthttps://api.bsky.chatanddid:web:api.bsky.chat#bsky_chat).ACTIVITIES_BLUESKY_MODERATION_URLandACTIVITIES_BLUESKY_MODERATION_DIDare the moderation service an app's reports and moderation inbox go to (defaulthttps://mod.bsky.appanddid:plc:ar7c4by46qjdydhdevvrndac#atproto_labeler); a report, and a read or an appeal of a labeler's decision, that the app addresses to another labeler goes to that labeler instead.ACTIVITIES_BLUESKY_VIDEO_DIDis the video service an app may get an upload token for (defaultdid:web:video.bsky.app).
Besides these, an app reaches through the PDS only a labeler or a feed generator it names, at the address that service's DID document gives. Each URL is an https origin with no path, query, fragment or credentials; an invalid value warns once and uses the default. Set each URL together with its DID (an overridden URL without its DID warns once), or leave both unset to use Bluesky's.
Point the PDS hostname at this server, and add a wildcard record for the handles it offers:
| Record | Name | Value |
|---|---|---|
| A/AAAA | pds.social.example |
this server |
| A/AAAA | *.pds.social.example |
this server |
A hosted account's handle is <username>.<PDS hostname> (for example alex.pds.social.example), so the wildcard record is what makes those handles resolve. An admin's profile may also claim the bare served domain as its handle, which needs no extra record. By default that is an admin's profile on the domain itself; Admin › Served domains › Bluesky handle can name one admin's profile, on any served domain, as the only holder instead; it takes the domain as a hosted account's handle. Naming a holder is refused while another profile's hosted account uses the domain as its handle: change that account's handle first.
Serve the PDS hostname over HTTPS with a certificate that covers both the hostname and its wildcard (pds.social.example and *.pds.social.example). The app routes by the request's Host header, so the reverse proxy must keep the original Host (or set X-Forwarded-Host to it) rather than rewriting it to the primary domain; a rewritten host makes every PDS request look like it arrived on ACTIVITIES_HOST. Strip any client-supplied X-Activity-Next-Host and X-Forwarded-Host at the proxy unless the proxy sets them itself.
The default container command (node server.js) runs the stock Next.js standalone server, which does not accept WebSockets. To expose the embedded Bluesky PDS firehose (com.atproto.sync.subscribeRepos), start the standalone build or Docker image with node pds-server.js on hosting that keeps long-lived WebSocket connections open:
docker run -p 3000:3000 \
... \
ghcr.io/llun/activities.next:main node pds-server.jspds-server.js passes every normal HTTP request to Next.js unchanged, answers any other WebSocket upgrade with 404, and accepts WebSocket upgrades on /xrpc/com.atproto.sync.subscribeRepos only for enabled PDS hostnames in ACTIVITIES_BLUESKY_PDS (all other hosts receive 404). At start-up it calls com.atproto.sync.requestCrawl on each domain's configured relays (defaulting to https://bsky.network), retrying with backoff for up to an hour; set "relays": [] on a domain entry to disable crawl requests. See Embedded Bluesky PDS (preview).
A deployment can split the PDS: the PDS hostname points at a host running node pds-server.js with a read-only database role, which serves the public reads and the firehose, while its reverse proxy (the gateway) forwards every XRPC request that writes or signs in to the web app, which has write access. Give that role SELECT on every table the public reads and the firehose read, bluesky_profile_merges included: a repo's status is read through it (the hosted account's owner and its merged profile), and a missing grant fails those reads. The gateway sends the web app any XRPC request that carries an Authorization header, plus com.atproto.server.createSession; the public reads and com.atproto.sync.subscribeRepos stay on the PDS process.
Set the same ACTIVITIES_PDS_GATEWAY_SECRET (at least 32 characters, for example openssl rand -hex 32; never commit or log it) on the web app, and have the gateway, on each request it forwards:
- set
Hostto the web app's own hostname (for example its Cloud Run URL), which must not be a served domain or a PDS hostname, andX-Activity-Next-Host(andX-Forwarded-Host, if it sets one) to the PDS hostname; - set
X-Activity-Next-Gatewayto the secret; - set
X-Activity-Next-Client-IPto the client's address, one IPv4 or IPv6 literal, replacing any value the client sent.
With the secret set, the web app handles a PDS request only with a valid X-Activity-Next-Gateway, whatever its Host (the gateway always rewrites Host to the web app's own name); without it the XRPC routes, /.well-known/did.json and the firehose answer 404, so calling the web app directly, or through any later domain mapping, gets no PDS handling. The served-domain, comma-list and X-Forwarded-Host conflict refusals still apply first. With a valid proof, X-Activity-Next-Client-IP is the client address for the PDS rate limits, ahead of the ACTIVITIES_TRUST_PROXY_IP_HEADER setting; without one it is ignored, and no other route ever reads either header. A secret that is set but blank or shorter than 32 characters logs a warning (never the value) and refuses every PDS request. A gateway request whose client address is missing or malformed falls back to the proxy address for its rate limits, and logs a warning once. Unset, nothing changes: a single self-hosted process handles the PDS hostname directly.
Settings › Other networks › "Host my Bluesky account here" creates a fresh did:plc account on the domain's PDS for an allowed, confirmed, approved profile that has no linked outside account. The offered handles are <username>.<PDS hostname> and, for an admin's profile that could claim its served domain (or that a served domain names as its bare-handle holder), the bare domain. Accounts are always created fresh here; moving an existing Bluesky account in is not supported.
The account's app.bsky.actor.profile record is written when it is created and kept in step with the profile: the display name, the bio as plain text with a link back to the fediverse profile, and the avatar and banner as blobs. A profile edit queues the update, which replaces only those fields and keeps the rest of the record a Bluesky app wrote, and opening Settings › Other networks repairs an account whose record is missing.
The owner can move a hosted account to another PDS from the same card. They enter the new server's https address, the handle and email to create there, and a password for the new account (sent once to that server's createAccount and never stored or logged), plus an invite code if the server asks for one, and confirm with the profile's current password. The page then copies the repo, the blobs and the preferences in resumable batches, and the switch asks for the profile's current password again before chaining a PLC operation that takes the directory's last operation's rotation keys except this server's, then the new server's recommended keys, takes the new server's signing key and PDS endpoint, and drops this server's rotation key. The new server must identify itself with the did:web of the address the owner typed. After the switch the copy left here is switched off, its local handle is cleared, it cannot be turned back on, and it can be deleted; the moved account can be linked again under "Your Bluesky account". Cancelling before the switch removes the stored move and leaves the account here working. Starting a move is limited to 3 a day.
The migrate_hosted_bluesky_ownership migration moves every live hosted account from its fediverse profile to the Bluesky actor row of its DID, which then carries the profile's account and is joined to the profile by a bluesky_profile_merges row (see Who a hosted account belongs to). It changes no repo content, signing key, PLC identity, publicId, post, Home row or notification.
The release that ships it runs safely on data that is not migrated yet: its readers fall back to the profile when no merge row exists, and up skips a repo already on a Bluesky actor, so accounts created after the deploy are left as they are. The release before it is not safe on migrated data: its profile deletion and hosted-account delete look the account up under the profile, so on migrated data its deletion would leave the Bluesky actor's live repo behind for good and its delete would leave a stale merge row. Upgrade only from the release that adds bluesky_profile_merges, and only once that release runs on every runner (the web app, the queue workers and any standalone pds-server.js).
Before deploying, take a database backup, and you can already save and review a first snapshot by running the snapshot script from the new release's checkout against the live database (it only reads).
On a platform that deploys the new release before migrations run, and with hosted accounts on the instance:
- Deploy the new release.
- Confirm that no instance of the previous release serves or runs jobs anywhere, a standalone
pds-server.jsincluded. - Quiesce background work: pause the job queue so Home and notification syncs, cross-posts and actor deletions do not run, keep Bluesky apps from signing in or writing to the hosted accounts, and keep hosted-account owners out of Settings › Other networks until step 8 (opening it repairs the account row, which can race the migration on PostgreSQL).
- Take a database backup.
- Check that no cross-post is in flight:
select count(*) from bluesky_crossposts where state in ('pending', 'posting')answers0. - Save the snapshot:
node scripts/run.cjs scripts/maintenance/hostedBlueskyIdentitySnapshot.ts > before.json(read-only; see Hosted Bluesky Identity Snapshot). Review it before going on. - Run
yarn migrate. It prints one line per moved DID and per skipped repo with the reason. - Save the snapshot again as
after.jsonanddiff before.json after.json. Only these may change:ownership(profile→bluesky, orbluesky-no-account-rowfor an account whose row was never written, which the Settings card writes later;tombstone keyed <profile id>→tombstonefor a deleted repo still keyed by its profile) and, for a Bluesky actor row the migration created,blueskyActorPublicId(null→ an id). Anything that still ran between the two snapshots shows up as well:lastSyncedAtandnotificationsSeenAt, thehomeandnotificationsdigests, thepds_*counts,maxEventSeq,rootCidandrev. If the diff shows abroken: …ownership state, do not resume: restore the backup, or roll back as below, and find the cause first. - Resume the job queue.
- Run
yarn search:reindex: the migration writes no search document for the Bluesky actor rows it creates, nor for a row that gave up its handle to one of them.
On a platform that runs migrations before the new release starts (yarn migrate while the previous release is stopped): take a backup, stop the previous release on every runner (web app, queue workers, any standalone pds-server.js), check that no cross-post is in flight as in step 5, save and review the snapshot from the new release's checkout, run yarn migrate, save the snapshot again and diff as in step 8, then start the new release and run yarn search:reindex. Do not let the previous release run on the migrated data.
To roll back, run yarn migrate:down while only the new release serves, then roll the release back. down moves every merged account back to its profile, including accounts created since; the Bluesky actor rows it created stay, without an account, and a row that gave up its handle keeps its DID as username until a sync stores its profile again. To go back past the release that added bluesky_profile_merges, run yarn migrate:down a second time to drop the empty table.
Each Home sync stores the newest 50 of the account's own Bluesky posts as Bluesky statuses here: for a hosted account every post record of its repo (written here or in a Bluesky app), for an outside link the copies of its cross-posts posted to the DID it holds now. Older ones are filled once by scripts/maintenance/reconcileBlueskyNativeCopies.ts, which reads every such post from the public AppView (25 per call, half a second apart) and stores it the way the Home sync does, for the accounts the Home sync serves (an actor that may act; a hosted repo that is on, or an outside link with a session) and only while the server allows Bluesky. It is a dry run unless given --apply, prints one line per post (would store or stored, not returned by the AppView, not stored, already stored, tombstoned, or AppView error for a batch whose call failed, after which it goes on) and a total, and a second run changes nothing (an AppView error or a post not returned yet is asked for again):
node scripts/run.cjs scripts/maintenance/reconcileBlueskyNativeCopies.ts # dry run
node scripts/run.cjs scripts/maintenance/reconcileBlueskyNativeCopies.ts --applyThe same script then repairs rows written before Bluesky replies and notifications named the copy, each only when the cross-post proves it (posted, with a DID, and its copy stored; --apply stores copies first, while a dry run reports a copy it would store as not stored): a Bluesky reply stored under the fediverse post now replies to the copy; a like or repost notification from a Bluesky account on the post, for its author, moves to the copy and its group; a reply or quote notification from a Bluesky account grouped under the post is grouped under the copy. A like or repost on the post whose same like or repost is already on the copy (synced after the change, before the repair) is a duplicate and is removed. It prints would repair … / repaired …, would remove duplicate … / removed duplicate …, or left … (<why>) (no DID, copy not stored, not the author's notification) per row, touches no counter or timestamp, and a second run repairs nothing. Rows it leaves keep working as before: an unrepaired reply still shows under the post, an unrepaired notification still names it.
Run yarn migrate before the release starts (it adds bluesky_record_tombstones). A release running before the table exists fails to store new Bluesky posts (the next sync retries), and worse: every cross-post that Bluesky accepts is rolled back and marked failed although it is on Bluesky (recording it also clears the URI's tombstone), and deleting your own Bluesky post here fails after it was already deleted on Bluesky. Take a backup, read the dry run, then apply.
Public fitness route-data responses are cacheable for 60 seconds when the source status is public or unlisted and the request is anonymous. Self-hosted deployments that expose public fitness route data should put Activity.next behind an upstream cache and rate limiter, such as nginx limit_req, Cloudflare, or an equivalent reverse proxy rule for /api/v1/fitness-files/*/route-data. The application does not keep process-local anonymous rate-limit buckets for this endpoint because client IP headers are deployment-specific, spoofable unless normalized by a trusted proxy, and not shared across serverless instances.
Read the applicable rules and review checks below before changing this subsystem. The mandatory workflow remains in AGENTS.md and CONTRIBUTING.md.
- Agents: MUST use Node.js version 26 for running any node commands in this project.
- Always use
yarnfor all package management. Never usenpm install,npm ci, or any othernpmcommands to install or manage packages. - Optional dependencies are modularized into Yarn workspaces (
packages/*). External database drivers, queue SDKs, and email providers (pg,@google-cloud/tasks,@upstash/qstash,nodemailer,resend,@aws-sdk/client-ses) live in isolated packages (@activities/pg,@activities/cloudtasks,@activities/qstash,@activities/nodemailer,@activities/resend,@activities/ses).yarn installat the repo root installs all workspaces by default for development and test execution. The Dockerfile builds minimal images usingyarn workspaces focus ${WORKSPACES}(defaulting toactivities.next @activities/nodemailer), and core code imports optional modules dynamically (dynamicImport/ dynamicimport()) with type stubs inlib/types/optional-modules.d.tsso the application runs without optional packages installed when those features are unconfigured. yarn devruns the local Next.js development server. The package script binds Next.js to0.0.0.0, so the dev server is reachable from the local network — only run it on trusted networks.yarn buildbuilds the production app;yarn startserves it.yarn analyzeruns Next's Turbopack bundle analyzer (next analyze) and serves an interactive UI on port 4000; add--output(yarn analyze --output) to write the results to.next/diagnostics/analyzewithout serving. For per-page numbers, runyarn build, thenyarn bundle:report: it prints each route's first-load JavaScript (uncompressed and gzip, largest first) and the size of the chunks every route shares. Save a baseline withyarn bundle:report --json before.jsonbefore a change and runyarn bundle:report --compare before.jsonafter rebuilding to see the gzip change per route (see Bundle Size Report).yarn lintruns Oxlint over the app and lib code, then a second pass,oxlint -c lint/oxlintrc.scripts.json scripts..oxlintrc.jsonignoresscripts/**,migrations/**,plans/**, and*.config.*files; the second pass exists because exactly one rule has to reach the otherwise-unlinted scripts tree (see A stored path is confined to the storage root indocs/maintenance.md), and keeping it to one rule is what avoids putting the whole rule set onto files that have never satisfied it. Several repository conventions are lint-enforced: noconsole.*, no../imports, noResponse.json()/NextResponse.json()or Zod.parse()inapp/apiroutes (agents/api-response-helpers,agents/zod-safe-parse), no directfetch()in component files (agents/no-component-fetch, whoseallowFilesoption in.oxlintrc.jsonis a frozen legacy-offender list — never add a file to it; shrink it by migrating callers tolib/client.ts), nopath.resolve/path.joinin a local storage driver (agents/no-storage-path-builder), nostartsWithagainst a resolved path anywhere (agents/no-resolved-path-prefix-check), no direct cookie-session read in a route or server action (agents/no-direct-cookie-session), and no storedhistory.statepassed to areplaceState/pushStatethat writes a URL (agents/no-history-state-address-write). Theagents/*rules are a local Oxlint JS plugin,lint/agentsRules.mjs, because Oxlint has nono-restricted-syntax;lint/agentsRules.test.tsruns the linter against fixtures so an Oxlint upgrade that stopped loading the plugin failsyarn testinstead of silently un-enforcing them, and also runs the repo's own configs over fixtures so a rule that stopped being pointed at anything fails too. Reach for a rule there rather than a raw-text Vitest scan whenever the convention depends on what a NAME refers to — aliases, destructuring, renamed imports — which a text scan decides wrongly in both directions. Suppress one line with// oxlint-disable-next-line <rule>(theeslint-disable-next-linespelling still works), but note Oxlint does not honor/* global … */block directives — declare globals in.oxlintrc.jsoninstead, as thepublic/sw.jsoverride does. That override carries more weight than it looks: the service worker is a static asset in no tsconfig and imported by nothing, so lint is the only thing that reads it at all — andno-undefis its only check for an undeclared global, which is what a typo there looks like. The no-env-reads-outside-lib/config/rule is enforced bylib/config/envAccess.test.ts; everyACTIVITIES_*/OTEL_*variable read inlib/config/must have a row indocs/environment-variables.md(lib/config/envDocumentation.test.tsfails otherwise); and server-only trees must not import a runtime value from a'use client'module (lib/clientModuleBoundary.test.ts— see Server/Client Module Boundary indocs/architecture.md). Three more repo-wide guards live as tests:test/next.config.test.ts(the build config must not consume runtime deployment values),app/globals.contrast.test.ts(the WCAG contrast floor), andlib/components/tailwindCssVariableSyntax.test.ts(see Tailwind CSS variables below). The remaining conventions in this file are review-enforced.yarn testruns the full Vitest suite (all tests run in parallel with SQLite in-memory databases). Each test file belongs to one of three sizes — small (no real I/O, 2s), medium (test database, tmpdir filesystem, short real waits, 15s) or large (child processes and everything else, 30s; timeouts doubled on CI) — which picks its guard and timeout; the size is inferred from the file's source and a/** @vitest-size … */docblock overrides it (see Test sizes in CONTRIBUTING.md).yarn run prettieralways writes ("prettier": "prettier --write app migrations lib lint test"inpackage.json, so evenyarn prettier --checkoverwrites files); pass a trailing.(yarn run prettier --write .) to format the whole tree, or runyarn prettier:checkfor a read-only check.yarn typechecktype-checks the whole project;yarn buildtype-checks everything except tests. TypeScript 7 has no compiler API, sonext buildtype-checks by running thetscCLI (experimental.useTypeScriptCli), which checks every file its tsconfig includes rather than only the app's module graph — the build therefore readstsconfig.build.json(inheritstsconfig.json, drops*.test.ts(x)) and catches type errors inscripts/and in unimportedlib/modules, which the old checker missed.yarn typecheckrunstsc --noEmitdirectly againsttsconfig.jsoncovering all files in the repository (production code, scripts, and all*.test.ts(x)files) with zero exclusions or ratchets. The baseexcludedropstest/setup/(the Vitest setup files). And silently, TypeScript resolves a wildcardincludeto one extension per basename, so afoo.test.tsxsitting beside afoo.test.tsis dropped from every program while Vitest still runs it — a live test file no compiler reads.lib/testFileTypeCoverage.test.tsguards that last one.incrementalisfalsein every tsconfig on purpose: TypeScript 7.0'stscserves stale diagnostics from.tsbuildinfoafter a global.d.tschanges (the microsoft/typescript-go#4664 class of bug), and a full check takes ~2s.- TypeScript is on the
7.xline — the native compiler, which ships a CLI and no JavaScript compiler API (require('typescript')exposes only{ version }; a new, different API is expected in 7.1). Nothing in the repo may depend on that API, which is why lint is Oxlint rather than ESLint + typescript-eslint (peer<6.1.0, and it throws on load under 7.x — typescript-eslint#10940),scripts/run.cjsboots with tsx rather than@swc-node/register(peer<7),lib/clientModuleBoundary.test.tsparses with@swc/core, andnext buildtype-checks through thetscCLI (see theyarn typecheckbullet above). Two traps worth knowing before changing any of this: Next resolves the CLI from the package namedtypescriptand needs itsbin.tsc, so aliasing that package for a side-by-side TypeScript 6 install (typescript: npm:@typescript/typescript6) makesnext buildrunyarn add --dev typescriptitself and rewritepackage.jsonmid-build; and TypeScript 7.0'stscserves stale diagnostics from.tsbuildinfoafter a global.d.tschanges (the microsoft/typescript-go#4664 class of bug), soincrementalstaysfalseeverywhere. Type-aware lint rules were never enabled here; if they are ever wanted, the TypeScript 7-native route isoxlint --type-aware(tsgolint), not a return to typescript-eslint. yarn migrateapplies every pending migration with Kysely's migrator (scripts/database/migrate.ts, which prints the database it resolved before it does anything);yarn migrate:statuslists the applied and pending migrations, the Knex handover state and a held SQLite migration lock without writing anything (it creates no table and no SQLite file);yarn migrate:downrolls back the last migration, never the baseline;yarn migrate:unlockreleases the SQLite migration lock a killed run left held;yarn migrate:make <name>createsmigrations/<timestamp>_<name>.tsfrommigrations/migration.stub. Always create migrations withyarn migrate:make, then register the new module inmigrations/index.tsand its name inmigrations/names.ts— the runner reads that static map, not the directory, the startup check reads the names without loading the modules,yarn typecheckfails when the map and the names disagree, andlib/database/migrate/index.test.tsfails when they and the files do. A migration exportsup(db)(anddown(db)) taking aKysely<any>; each runs in its own transaction on both backends unless it exportsconfig = { transaction: false }. The first migration,20261014000000_baseline, is the Knex handover (see Keeping the reference schema dumps in sync below and the handover section in docs/maintenance.md); the 181 Knex migrations it stands for ran in v1.192.34 and earlier releases and are not in this checkout.- Local database is local-only. For development and tests, use either SQLite on
localhost(ACTIVITIES_DATABASE_CLIENT=better-sqlite3with a local*.sqlite3file, or theACTIVITIES_DATABASEJSON equivalent) or the PostgreSQL in the docker-compose stack atactivities.local. Never run the dev server, migrations, or tests against a remote/shared/production database (e.g. a non-localACTIVITIES_DATABASE_PG_HOSTsuch as<remote-db-host>). Verify the resolved database target is local before migrating or starting the app. When working in a git worktree, do not copy a main-checkout.env.localthat points at a remote DB; create a worktree-local SQLite config instead. - Creating test/mock users is allowed for local verification (for example, to log in and check UI changes), but only against a local database as defined above — never against a remote/shared/production database.
- Supported backends: SQLite (
docs/sqlite-setup.md) and PostgreSQL (docs/postgresql-setup.md). The clients arebetter-sqlite3andpg; no other client is supported. - Local SQLite is the simplest for development; run
yarn migrateafter updating schema or migrations.
There are two committed reference schema dumps, one per supported backend. Use the one that matches the database you are reasoning about:
migrations/schema.sql— the PostgreSQL schema (apg_dump). Use it when inspecting the schema for PostgreSQL deployments.migrations/schema.sqlite.sql— the SQLite schema (asqlite3 .schemadump). Use it when inspecting the schema for SQLite — which is what local dev and the Vitest test suite use (tests run against in-memory SQLite). Because the two backends use different SQL dialects (e.g.character varying/jsonb/timestamp with time zonevsvarchar/json/datetime), the Postgres dump cannot be loaded into SQLite and vice versa — always read the file for the right backend.
"In lockstep" means they describe the same migration set, not that every column has the same type in both. A migration may deliberately be backend-conditional, and then the dumps legitimately disagree: the 20260207223000_fix_attachments_media_id_type migration returned early unless the client was pg, so for a while attachments.mediaId was integer on PostgreSQL and varchar(255) on SQLite. That is not drift — do not "reconcile" it or regenerate the dumps over it. Check the migration before treating a per-column difference as a bug. (The 20261012100000_attachments_media_id_integer_sqlite migration has since rebuilt the SQLite table with mediaId integer, so the two dumps agree on that column now.)
The app (yarn migrate) runs the migrations, but the test suite does not — createTestDatabase (lib/database/testing/) builds every test database directly from these dumps (see Testing Guidelines in CONTRIBUTING.md). If the dumps drift from the migrations, tests run against a stale schema, so keeping them in lockstep is load-bearing, not just hygiene. They are gitignored by the blanket *.sql rule and re-included by explicit ! negations in .gitignore.
-
The baseline is frozen.
migrations/baseline/postgres.sqlandmigrations/baseline/sqlite.sqlare the schema the 181 Knex migrations built (the dumps at the handover, without the Knex bookkeeping tables);yarn migrateloads the right one into an empty database. Never edit or regenerate them — a schema change is a new migration on top. The PostgreSQL baseline must keep loading on PostgreSQL 14 (CI loads it onpostgres:14). -
Any PR that adds, edits, or removes a migration in
migrations/MUST regenerate BOTHmigrations/schema.sqlandmigrations/schema.sqlite.sqlin the same PR, and then the Kysely DB types (see Regenerating the Kysely DB types below). Keep them in lockstep — they must always describe the same migration set. CI's schema drift checks (run in the first PostgreSQL test shard) regenerate both reference dumps from the migrations on every pull request and push tomainand fail on drift. -
Regenerate them canonically rather than hand-editing — run every migration against a fresh database of each type and dump the result. In both cases verify
SELECT count(*) FROM kysely_migrationequals the number ofmigrations/[0-9]*_*.tsfiles first (the baseline is one of them). The dumps include the migrator's ownkysely_migrationandkysely_migration_locktables; the Knex tables appear only in a database the Knex migrations built, never in a fresh one.Pass the DB settings inline on the
yarn migrateline — do not write a.env.local(you'd clobber an existing one, and the cleanup would delete it). Becauseyarn migrateloads.env*files withdotenv-flow, which never overrides variables already in the environment, each inline value wins over the same variable in.env.local— but only that one:.env.localstill supplies whatever the line leaves unset, and anACTIVITIES_DATABASEJSON configuration wins over every individualACTIVITIES_DATABASE_*variable. So start every line with an emptyACTIVITIES_DATABASE=, or a JSON configuration in.env.localwould redirectyarn migrateto that database. For the same reason, run in a shell with no otherACTIVITIES_DATABASE*vars exported (a stray one would be merged in and could target a remote DB — checkenv | grep ACTIVITIES_DATABASE).PostgreSQL (
migrations/schema.sql):-
Start a local PostgreSQL 17 — e.g. a throwaway
postgres:17Docker container — and wait until it accepts connections (docker run -dreturns beforeinitdbfinishes; loop onpg_isready). Never point at a remote/shared/production DB. To use the docker-compose stack's PostgreSQL instead (atactivities.local; its port and credentials come from your local, gitignoreddocker-compose.yml), substitute its host/port/credentials in the step-2 environment variables, runpsql/pg_dumpvia the compose service (e.g.docker compose exec postgres …) rather thandocker exec anext-schema-pg, and skip the cleanup step.docker run -d --name anext-schema-pg \ -e POSTGRES_USER=activities \ -e POSTGRES_PASSWORD=activities \ -e POSTGRES_DB=activities \ -p 127.0.0.1:55432:5432 postgres:17 # Wait for readiness before continuing. until docker exec anext-schema-pg pg_isready -U activities -q; do sleep 1; done
-
Run migrations with the settings inline (the leading empty
ACTIVITIES_DATABASE=neutralises a JSON configuration in.env.local):ACTIVITIES_DATABASE= \ ACTIVITIES_DATABASE_CLIENT=pg \ ACTIVITIES_DATABASE_PG_HOST=127.0.0.1 \ ACTIVITIES_DATABASE_PG_PORT=55432 \ ACTIVITIES_DATABASE_PG_USER=activities \ ACTIVITIES_DATABASE_PG_PASSWORD=activities \ ACTIVITIES_DATABASE_PG_DATABASE=activities \ yarn migrate
Sanity check that every migration ran — the
kysely_migrationrow count must equal the number ofmigrations/[0-9]*_*.tsfiles:docker exec anext-schema-pg \ psql -U activities -d activities -tAc 'SELECT count(*) FROM kysely_migration;' ls migrations/[0-9]*_*.ts | wc -l
-
Dump schema only, without ownership/grants, from the PG 17 server so the dump matches that version:
docker exec anext-schema-pg \ pg_dump -U activities -d activities --schema-only --no-owner --no-privileges \ > /tmp/schema_raw.sql
-
Strip pg_dump's noise to match the existing pure-DDL file: the
\restrict/\unrestrictsession token (non-deterministic — never commit it), the-- …comment headers, and theSET default_tablespace/SET default_table_access_methodlines. Keep the leadingSET/SELECT pg_catalog.set_config(...)block and allCREATE/ALTERDDL.awk ' /^SET statement_timeout/ { started = 1 } !started { next } /^--/ { next } /^\\(un)?restrict/ { next } /^SET default_tablespace/ { next } /^SET default_table_access_method/ { next } { print } ' /tmp/schema_raw.sql | cat -s > migrations/schema.sql
-
Clean up the throwaway container:
docker rm -f anext-schema-pg.
SQLite (
migrations/schema.sqlite.sql):-
Run migrations against a throwaway file DB with the settings inline, then sanity check that every migration ran — the
kysely_migrationrow count must equal the number ofmigrations/[0-9]*_*.tsfiles:ACTIVITIES_DATABASE= \ ACTIVITIES_DATABASE_CLIENT=better-sqlite3 \ ACTIVITIES_DATABASE_SQLITE_FILENAME=./schema-dump.sqlite3 \ yarn migrate sqlite3 schema-dump.sqlite3 'SELECT count(*) FROM kysely_migration;' # == ls migrations/[0-9]*_*.ts | wc -l
-
Dump the schema and strip SQLite's auto-managed internal tables, which it recreates on its own and which must NOT be in the file: the
CREATE TABLE sqlite_sequence(...)line, and the FTS5 shadow tables (CREATE TABLE IF NOT EXISTS '<name>_fts_(data|idx|docsize|config|content)'). Keep theCREATE VIRTUAL TABLE … USING fts5(…)statement and its triggers — those are real.sqlite3 schema-dump.sqlite3 '.schema' \ | grep -vE "^CREATE TABLE sqlite_sequence" \ | grep -vE "^CREATE TABLE IF NOT EXISTS '[A-Za-z_]+_fts_(data|idx|docsize|config|content)'" \ > migrations/schema.sqlite.sql
The committed dump is what CI's
sqlite3prints, which keepsCREATE TABLE IF NOT EXISTSfor a table a migration created with.ifNotExists(). Thesqlite3on macOS (and Homebrew's) prints those as plainCREATE TABLEand rewrites older rows the same way, so on a Mac compare the new lines with the existing ones and keep theIF NOT EXISTSspelling rather than committing the whole re-dump. -
Sanity-check that the result loads cleanly into a fresh database:
rm -f /tmp/roundtrip.sqlite3 sqlite3 /tmp/roundtrip.sqlite3 < migrations/schema.sqlite.sql && echo OK
-
Clean up the throwaway files:
rm -f schema-dump.sqlite3 /tmp/roundtrip.sqlite3.
After both dumps, only
migrations/schema.sqlandmigrations/schema.sqlite.sqlshould be left changed (pluslib/database/kysely/db.tsonce you regenerate the Kysely DB types). -
-
A Postgres regeneration is a full re-dump, so its diff can be large even for unchanged tables (formatting differs from older dumps). That is expected — do not try to reproduce the old line-by-line formatting by hand. Commit the schema regeneration as
none:when it is the only change (they are reference artifacts and ship nothing). -
Use only a local database for local dev/tests: SQLite on
localhost, or the docker-compose PostgreSQL atactivities.local. Never connect local dev, tests, or user creation to a remote/shared/production database. -
Tests use isolated SQLite in-memory databases for fast, parallel execution.
-
Docker users should persist data under
/opt/activities.next/data(bind-mount a host directory there and point the SQLite/media env vars into it). Do not bind-mount/opt/activities.nextitself — that directory contains the application (standaloneserver.js,.next/static, …), so a host-path mount shadows the app and the container cannot start (seedocs/setup.mdand the database setup guides).
lib/database/kysely/db.ts is the Kysely DB interface for every application table. It is generated, never hand-edited, by scripts/maintenance/generateDatabaseTypes.ts, which introspects a PostgreSQL database migrated to the latest migration (step 2 of the PostgreSQL dump above, before you remove the container) and the committed migrations/schema.sqlite.sql, so regenerate the SQLite dump first. Pass the same inline settings as yarn migrate; the script only reads the schema:
ACTIVITIES_DATABASE= ACTIVITIES_DATABASE_CLIENT=pg ACTIVITIES_DATABASE_PG_HOST=… ACTIVITIES_DATABASE_PG_PORT=… ACTIVITIES_DATABASE_PG_USER=… ACTIVITIES_DATABASE_PG_PASSWORD=… ACTIVITIES_DATABASE_PG_DATABASE=… node scripts/run.cjs scripts/maintenance/generateDatabaseTypes.tsTimestamp columns are typed as the branded EpochMs on read, so compare them only through timestampValue() from lib/database/kysely/dialect.ts; the brand stops bare numbers, not read-back values, which must also go through it. It types each column for what the Kysely driver returns on both backends and prints any column whose type differs between the two dumps in a way that changes what is read back (typed as either, and marked Mismatch in the file). CI's PostgreSQL schema drift check (run in the first PostgreSQL test shard) regenerates the file with --output and fails on drift.