Skip to content
FlagSwiftDocs

Self-hosting

Run FlagSwift Enterprise, the self-hosted edition, on your own infrastructure with PostgreSQL or MongoDB. If you would rather not run it, the hosted Commercial edition is described under Editions.

Set up#

bash
npm install
npx prisma generate            # PostgreSQL only
npx prisma migrate deploy      # PostgreSQL only; apply every pending migration
npm run build
npm start

If a required variable (DB_TYPE, JWT_SECRET, the connection string for your database or an email provider) is missing, the server still starts but serves only a setup screen listing the missing names, and answers the API and health checks with 503. Nothing else runs, including the schedulers. Set them and restart.

Choose the database with DB_TYPE (postgres or mongodb). MongoDB has no migrations, but its indexes are not built by the app: run npm run db:init-mongo once on a new database (and after an upgrade that changes an index). Moving an existing PostgreSQL install? See Switch from PostgreSQL to MongoDB.

Moving between PostgreSQL and MongoDB#

You can change database later, in either direction, with scripts that ship with the server. Each copy reads the old database only, writes only into an empty target, converts ids and every reference to them, can be run again if it stops, and ends by checking counts and references. Both start as a dry run; add -- --yes to write.

Database migration commands
CommandDescription
npx prisma migrate deployPostgreSQL. Creates and updates the tables. Run it on a new database and on every upgrade.
npm run db:init-mongoMongoDB. Creates the collections and syncs their indexes. Run it on a new database and after an upgrade that changes an index. --dry-run previews it.
npm run db:copy-postgres-to-mongoCopies a PostgreSQL install into an empty MongoDB database. Options: --yes, --only=, --skip=, --include-rate-limits.
npm run db:copy-mongo-to-postgresThe reverse: copies a MongoDB install into an empty PostgreSQL database, after the migrations have created the tables.

Only the configuration moves with an export and import (projects, environments, segments, flags and custom roles); the copy scripts move everything. See PostgreSQL to MongoDB and MongoDB to PostgreSQL.

Environment variables#

Only a handful of settings are variables. Limits, lifetimes, retention, the password rule and the bcrypt cost are built in and the same on every install (see Fixed values below). On start the server logs env.missing for each required variable that is not set.

Required settings
VariableDescription
DB_TYPE*postgres or mongodb.
DATABASE_URL*Required when DB_TYPE=postgres. The connection string the app uses.
DIRECT_URL*Required when DB_TYPE=postgres. The direct connection used for migrations, not a pooler.
MONGODB_URI*Required when DB_TYPE=mongodb. The connection string. Name the database in it (…/fs-enterprise); without a name MongoDB uses a database called test.
MONGODB_DBMongoDB only, optional. The database name, for when the connection string does not carry one.
JWT_SECRET*Signs console sessions and password reset links. The server refuses to sign in without it. Changing it signs everyone out.
APP_URL*Strongly recommended (a startup warning, not a setup-screen check). The public address of the console, used in invitation, password reset and email verification links. Sign-up verification and password reset links are only built from it, so without it new accounts cannot be verified.
Optional settings
VariableDescription
RESEND_API_KEY, MAIL_FROM, MAIL_REPLY_TO*Required (one of Resend or SMTP; MAIL_REPLY_TO is optional): set up Resend or SMTP, or the server refuses to start and shows a setup screen. With Resend, verify your sending domain first; MAIL_FROM must use it. Sends sign-up verification links (nobody can sign in to a new account until they open one, so email must deliver), invitations, approvals, failed releases, alerts, kill switch notices, password resets and account security notices.
SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, SMTP_FROMEmail through your own SMTP server instead (one of Resend or SMTP is required) (needs the nodemailer package). A secure connection is used when the port is 465. MAIL_FROM is used when SMTP_FROM is not set. Resend is used when RESEND_API_KEY is set, otherwise SMTP when SMTP_HOST is set.
API_KEY_ENCRYPTION_KEYA long random string (16+ characters). When set, new API keys are also stored encrypted so administrators can copy them. Changing it makes stored keys uncopyable; keys keep working.
ALERT_WEBHOOK_URLReceives a JSON post (with a Slack and Discord compatible text field) when an alert fires or resolves.
METRICS_TOKENEnables /api/prometheus and is the bearer token it requires.
ALLOWED_ORIGINSExtra origins allowed to make changing requests to the console API (comma separated). The console's own address is always allowed.
CSP_CONNECT_SRC, CSP_IMG_SRCExtra hosts the console may connect to or load images from (space separated).
LOG_LEVELdebug, info (default), warn, error or silent.
METRICS_ENABLEDCount evaluations and errors. Default true.
STREAM_ENABLEDReal-time flag updates over Server-Sent Events. Default true. Set false and SDKs fall back to polling. Behind a reverse proxy, do not buffer text/event-stream responses.
SCHEDULER_ENABLEDRuns the release and alert schedulers in this process. Default true; set false on instances that should not run them.
DELIVERY_SYNC_INTERVAL_SECONDSRunning more than one instance? How often each one checks the database for changes made on another, so a change takes effect everywhere within seconds instead of after the cache time. Default 5; 0 turns it off, which is fine for a single instance.
ALLOW_SELF_APPROVALLets a proposer approve their own release. Default false.
RATE_LIMIT_API_STOREWhere the per-key API limiter and the bad-key limiter count. Default memory (this process), so an SDK request costs no database write. Set shared to count in the database across instances.
RATE_LIMIT_STORESet memory to count every limiter in this process instead of the database. Use it in development; with several instances each one counts on its own.
RATE_LIMIT_LOGIN_ATTEMPTS, RATE_LIMIT_SIGNUP_PER_HOUR, RATE_LIMIT_KEY_FAILURES_PER_MINUTE, RATE_LIMIT_API_PER_MINUTETune the limits: failed sign-ins per 15 minutes (default 10), sign-ups per hour (5), bad API keys per minute (30) and requests per API key per minute (600). Positive whole numbers; anything else uses the default.
RATE_LIMIT_ENABLEDTurns every rate limit on or off. Default true; leave it on for a public server.
ANALYTICS_ENABLEDRecords exposures and outcomes for conversion by variant. Default false; it keeps a keyed hash per person.

Fixed values#

These are built in and cannot be changed with a variable.

Fixed values
SettingValueDescription
Password rule (new passwords)6+ charactersMust include a number, a symbol, and both upper and lower case letters, and be at most 72 bytes. Applies to sign-up, accepting an invitation, changing a password and resetting one. Signing in only asks for 6 characters, so older passwords still work.
Console session60 minutesThe console asks whether you are still there near the end and renews the session if you are.
Password reset link30 minutesWorks once. Needs APP_URL and an email provider.
Email verification link24 hoursSent at sign-up. Needs APP_URL and an email provider. Only the mailbox is checked; no identity (KYC) verification is performed.
bcrypt cost12Existing hashes keep working.
Approval requestsExpire after 72 hoursA request nobody reviews is cancelled and audited.
Metrics history30 daysHourly evaluation and API counts.
Analytics history90 daysExposures and outcomes, when analytics is on.
Audit export10,000 rowsMost rows one export holds.
Streams100 per key, 5,000 per instanceEach stream lasts 5 minutes, then the SDK reconnects.
Caches30 s and 10 sKeys and configuration are cached for 30 seconds; role lookups for 10 seconds.
Security headersAlways onThe content security policy is enforced, and HSTS is sent in production.
Rate limit storeDatabaseCounts are shared by every instance. If the database cannot be reached a request is counted in that instance alone.

Rate limits#

Each limit is a fixed window counted per client address (taken from X-Forwarded-For, so make your proxy set it). A request over the limit gets 429 with a Retry-After header in seconds. Sign-in, sign-up and password limiters count in the database by default, so every instance shares them. The per-key API limiters count in each process unless RATE_LIMIT_API_STORE=shared, which keeps SDK traffic off the database. RATE_LIMIT_ENABLED turns them all off.

Rate limits
LimitValueDescription
Failed sign-ins, per address and email10 per 15 minutesA successful sign-in clears the count.
Failed sign-ins, per address50 per 15 minutesFive times the limit per address and email.
Sign-up and invitation acceptance, per address5 per hourSign-up and accepting an invitation are counted separately.
Forgot password, per address and email3 per hourRequests for the same email from the same address. Every request counts, whether or not an account exists, so the answer never reveals who is registered.
Forgot password, per address20 per hourRequests for any email from one address. It stops one source sweeping many mailboxes.
Verification emails, per address and email5 per hourSign-up, Resend email and refused sign-ins on an unverified account all count. Past it the email is not sent.
Verification emails, per address20 per hourAcross all emails from one address.
Verify email (submitting a verification link), per address10 per 15 minutesCounted on every submission, good or bad.
Reset password (submitting a reset link), per address10 per 15 minutesCounted on every submission, good or bad.
Wrong current password when changing it, per member5 per 15 minutesCounted per member.
Bad API keys, per address30 per minutePast it, even a good key from that address gets 429.
Requests, per API key600 per minuteEvery Evaluation and Automation request.

When a person says they never got the reset email

After the third request for one email in an hour, or the twentieth from one address, the forgot password page shows Too many reset requests. Try again later. and the server sends no email. The window starts at the first request and the Retry-After header says how long is left. Everyone behind one shared address (an office, a VPN) shares the 20 an hour and the 10 per 15 minutes for reset links. RATE_LIMIT_ENABLED=false turns every limit above off, which you should not do on a public server.

Production checklist#

  • Serve the console and API over HTTPS. Sign-in cookies and bearer keys must never travel in clear text.
  • Use a strong JWT_SECRET and keep it, API_KEY_ENCRYPTION_KEY and METRICS_TOKEN in a secrets manager.
  • Point your load balancer at /health/ready and your process manager at /health/live.
  • If you run several instances behind a proxy, make sure it sets X-Forwarded-For. Rate limiting trusts it to tell callers apart.
  • Take database backups. Flags, keys, the audit log and metrics all live there.
  • On MongoDB, run npm run db:init-mongo on a new database and after an upgrade that changes an index. The app never builds Mongo indexes itself. Switching from PostgreSQL?
  • Scrape every instance with Prometheus; counters are per process.

Things to know with more than one instance

Each instance keeps its own caches. Every instance asks the database for recent changes (5 seconds by default, set with DELIVERY_SYNC_INTERVAL_SECONDS) and drops what changed, so a flag change, revoked key or kill switch reaches the others in about that long. The 30 second cache lifetime stays underneath as a safety net. Rate limits are counted in the database, so every instance shares them.