> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy on Railway

> Deploy a GatoJS app to Railway step by step: Postgres, production variables, prisma migrate deploy as a pre-deploy command, the healthcheck, and creating the first accounts with railway run.

[Railway](https://railway.com) is the default host for GatoJS projects. A production setup is one Railway project with two services, the app (built from the [Dockerfile](https://docs.gatojs.com/deployment/docker.md)) and PostgreSQL, plus a bucket or volume if you use the `uploads` module. Mail goes through Resend and logs go to an external OTLP collector.

Every deploy runs the same way:

```mermaid theme={null}
flowchart TD
    push["Push to the connected branch"] --> build["Railway builds the image from Dockerfile"]
    build --> pre["Pre-deploy command:<br/>npx prisma migrate deploy"]
    pre -->|"non-zero exit"| stop["Deploy stops"]
    pre -->|"exit 0"| start["Container starts: node server.js"]
    start --> hc{"/api/healthcheck<br/>returns 2xx in time?"}
    hc -->|"no"| fail["Deploy fails,<br/>traffic stays on the old version"]
    hc -->|"yes"| live["Traffic switches to the new version"]
```

## `railway.toml`

The project ships the intended Railway settings in `railway.toml`:

```toml railway.toml theme={null}
[build]
builder = "DOCKERFILE"
dockerfilePath = "Dockerfile"

[deploy]
preDeployCommand = "npx prisma migrate deploy"
startCommand = "node server.js"

healthcheckPath = "/api/healthcheck"
healthcheckTimeout = 10

restartPolicyType = "ON_FAILURE"
restartPolicyMaxRetries = 3
```

| Field | Effect |
| - | - |
| `builder`, `dockerfilePath` | Build from the root `Dockerfile`. |
| `preDeployCommand` | Runs between build and start, in a separate container from the same image, on the project's private network, with the service's variables. A non-zero exit stops the deploy. |
| `startCommand` | Same as the image's `CMD`. |
| `healthcheckPath`, `healthcheckTimeout` | Railway polls the path until it gets a 2xx, for at most 10 seconds. Traffic switches only after a successful check. It runs only during deploys, not as ongoing monitoring. |
| `restartPolicyType`, `restartPolicyMaxRetries` | Restart on crash, at most 3 times. |

> [!WARNING]
>
> **Enter these settings in the Railway dashboard.** Railway is phasing out `railway.toml` ("Config as Code") in favor of "Infrastructure as Code", and new services don't read it. Without the file, Railway still builds the Dockerfile and starts `node server.js`, so the deploy looks successful, but **migrations never run** and your database has no tables. Copy the values into the service settings yourself (step 4 below). If a deploy is rejected with a message that Config as Code is deprecated, clear the config-file path in the service settings.

## Before you start

You need:

* the project in a GitHub repository;
* a [Resend](https://resend.com) account with an API key and a verified sender domain;
* an OTLP collector for logs (see [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md));
* a local checkout after `npm install`, and the [Railway CLI](https://docs.railway.com/guides/cli) logged in with `railway login`.

## First deploy

**1. Commit your migrations**

The kit doesn't ship migrations. If `prisma/migrations/` is empty, create one and commit the whole folder:

```bash theme={null}
npx prisma migrate dev --name init
git add prisma/migrations
git commit -m "chore: initial migration"
```

Check with `git ls-files prisma/migrations`: it should list `migration_lock.toml` and at least one `migration.sql`.

**2. Create the Railway project**

Create a project with a **PostgreSQL** service and an app service connected to your GitHub repository. Railway deploys the app on every push to the connected branch.

**3. Add a domain and variables**

In the app service's networking settings, generate a Railway domain or attach your own. Then set the variables from the [table below](#production-variables), with `APP_URL` set to that domain including `https://`.

If you use the `uploads` module, set up storage now: a bucket or a volume. See [File storage](https://docs.gatojs.com/deployment/file-storage.md).

Keep `AUTH_PUBLIC_SIGNUP` unset or `false` until you've created the accounts in step 7. See [why](#why-sign-up-stays-closed).

**4. Configure deploy settings**

In the app service's settings, enter the values from `railway.toml`:

* **Pre-deploy command:** `npx prisma migrate deploy`
* **Healthcheck path:** `/api/healthcheck`, timeout 10 seconds
* **Restart policy:** on failure, max 3 retries

You can leave the start command empty: the image's `CMD` is `node server.js`.

**5. Deploy**

Trigger a deploy or push to the connected branch.

**6. Check the migration log**

Open the deploy logs and find the output of `prisma migrate deploy`. You want `All migrations have been successfully applied.` or `No pending migrations to apply.`

If you see `No migration found in prisma/migrations`, the migrations didn't reach the image. The command exits `0` and the healthcheck passes on an empty database, so this is easy to miss. Go back to step 1. For other errors (`P3005`, `P3018`), see [Migrations on deploy](https://docs.gatojs.com/deployment/docker.md#migrations-on-deploy).

**7. Create the accounts**

Right after the first successful deploy, create the first accounts with `railway run`, as described in [Create the first accounts](#create-the-first-accounts).

**8. Check it by hand**

The healthcheck only proves the process started and reached the database. Open the app at `APP_URL` and:

* **sign in** with an account from step 7. This confirms `APP_URL` matches the address you use; better-auth rejects requests from other origins;
* **open a default-locale URL without a prefix**, such as `/sign-in`, and confirm it renders instead of redirecting in a loop;
* **request a password reset** and confirm the email arrives. This checks `RESEND_API_KEY` and `EMAIL_FROM`;
* **confirm log export.** Sign-in and page views don't log anything, so trigger an action that does: as the service account, use **Sign in as** on the client admin's row on the **Users** page, then **Back to my account**. Your collector should show `[USERS] Impersonation started` and `[USERS] Impersonation stopped`.

Every later deploy repeats steps 5 and 6. A new migration reaches production with the commit that added it.

## Production variables

Set these on the app service. The server validates them at startup and exits if anything is wrong, so a new value only takes effect after a redeploy. Full reference: [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md).

| Variable | Required | Value |
| - | - | - |
| `DATABASE_URL` | Yes | A reference variable: `${{Postgres.DATABASE_URL}}`, where `Postgres` is your database service's name. This is the private-network address. |
| `BETTER_AUTH_SECRET` | Yes | Random, at least 32 characters, for example from `openssl rand -base64 32`. Different from `.env.example` and from your local value. |
| `APP_URL` | Yes | Full `https://` URL users open. |
| `EMAIL_FROM` | Yes | Sender on a domain verified in Resend, for example `Acme <noreply@acme.com>`. |
| `RESEND_API_KEY` | Yes | Resend API key. Required in production even if `SMTP_URL` is set. |
| `API_KEY_PEPPER` | With `api-keys` | Random, at least 32 characters. **Never** the `.env.example` value, which `gato create` leaves in `.env`. Changing it later invalidates every API key. |
| `STORAGE_PROVIDER`, `STORAGE_LOCAL_PATH`, `S3_*` | With `uploads` | See [File storage](https://docs.gatojs.com/deployment/file-storage.md). |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Not enforced, but set it | Base URL of your OTLP/HTTP collector, without `/v1/logs`. Without it, production logs are discarded. |
| `OTEL_EXPORTER_OTLP_HEADERS` | If the collector needs auth | `key=value` pairs, comma-separated. |
| `OTEL_SERVICE_NAME`, `GIT_COMMIT_SHA` | Optional | Service name and version in exported telemetry. Railway exposes the deployed commit as `RAILWAY_GIT_COMMIT_SHA`, which the kit doesn't read; you can reference it from `GIT_COMMIT_SHA`. |
| `AUTH_PUBLIC_SIGNUP`, `MULTI_ORG`, `ADMIN_IMPERSONATION` | Optional | `true` or `false`. Any other value, such as `1`, fails validation. |
| `DATABASE_POOL_MAX` | Optional | Max `pg` pool connections. Default `10`. |

Don't set:

* **`SMTP_URL`**: if present, it wins over Resend, also in production.
* **`NODE_ENV`, `PORT`, `HOSTNAME`**: the Dockerfile sets them and Railway injects `PORT`. If you set `PORT` yourself, Railway uses it for the healthcheck too.
* **`ADMIN_EMAIL`, `ADMIN_PASSWORD`**: only `admin:create` reads them, and on the service they'd leak into every `railway run`.
* **`LOG_LEVEL`**: it has no effect.

> [!NOTE]
>
> **When variables are wrong**, the new container prints a report to stderr (`Nieprawidłowe zmienne środowiskowe (N):` followed by one line per problem) and exits with code 1. The healthcheck fails and traffic stays on the previous version. Restarts won't help, since each start fails the same way. The report goes through `console.error`, so it shows up in the deploy logs even without OTLP export.

## Create the first accounts

The image doesn't include `scripts/` or dev dependencies, so `admin:create` can't run in the container. Instead, `railway run <command>` runs a command **on your machine** with the service's variables. The script uses your local checkout, `node_modules` and Prisma client.

The app's `DATABASE_URL` points to Railway's private network (`*.railway.internal`), which your machine can't reach. Give the script the database's public URL:

**1. Enable public access to Postgres**

In the PostgreSQL service's networking settings, enable public networking. Railway creates a TCP proxy and a `DATABASE_PUBLIC_URL` variable on the database service. Traffic through it is billed as egress.

**2. Reference it from the app service**

On the app service, add `DATABASE_PUBLIC_URL` with the value `${{Postgres.DATABASE_PUBLIC_URL}}`. `railway run` only loads one service's variables, so without this reference the variable is empty.

**3. Match your checkout to production**

Check out the commit that runs in production and generate the Prisma client with `npm install` (or `npm run db:generate` if dependencies didn't change). The client is built from the local schema, which must match the database.

**4. Check where the password comes from**

The script loads `.env.local` and `.env` with dotenv, which doesn't override variables already set. Railway's values win, but anything the service lacks is read from your local files. A non-empty `ADMIN_PASSWORD` in your local `.env` would become the production password. Leave it empty to get a generated one.

**5. Run admin:create**

From the project root, linked to the app service with `railway link`:

```bash theme={null}
railway run sh -c 'DATABASE_URL="$DATABASE_PUBLIC_URL" npm run admin:create -- --email you@example.com'
```

Put options such as `--role superadmin` and `--org-name "Acme"` after `--email`, inside the single quotes. The script prints the generated password once; sign in with it before you close the terminal.

**6. Close public access**

When you no longer need outside access, remove the `DATABASE_PUBLIC_URL` reference and disable public networking on the database.

For a client project, create a service account and the client's admin account in that order. See [Handover](https://docs.gatojs.com/deployment/handover.md) for the exact commands.

| Error | Cause |
| - | - |
| `Nieprawidłowe zmienne środowiskowe: DATABASE_URL: Too small: expected string to have >=1 characters` | `$DATABASE_PUBLIC_URL` is empty. Add the reference from step 2. |
| `Nieprawidłowe zmienne środowiskowe: ...` with another variable | The variable exists neither on the service nor locally. |
| Connection error to `*.railway.internal` | You ran `railway run npm run admin:create` without `sh -c '...'`, so the script got the private URL. |

### Why sign-up stays closed

Until `admin:create` runs, the database has no organization. What happens if someone signs up before that:

| `AUTH_PUBLIC_SIGNUP` | `MULTI_ORG` | Sign-up before `admin:create` |
| - | - | - |
| `false` or unset | any | `403`, sign-up disabled. There are no invitations yet, so nobody can register. |
| `true` | `false` or unset | Error asking you to run `npm run admin:create`; no account is created. |
| `true` | `true` | **Succeeds.** The stranger creates an organization and becomes its `owner`. It is the oldest organization, so `admin:create` then adds your accounts to it and ignores `--org-name`. |

Keep `AUTH_PUBLIC_SIGNUP=false` until the accounts exist, then set the final flags.

## CI and deploys

Railway deploys on push regardless of CI results. To gate deploys on CI, enable Railway's **Wait for CI** option on the service: the deploy waits for the GitHub Actions workflows triggered for that commit and is skipped if any fail. See [CI workflows](https://docs.gatojs.com/deployment/ci.md).

## Related

> [card] [Handover](https://docs.gatojs.com/deployment/handover.md)
>
> Service accounts, client admin, and ending support access.

> [card] [File storage](https://docs.gatojs.com/deployment/file-storage.md)
>
> Railway Bucket or volume for the uploads module.

> [card] [Docker](https://docs.gatojs.com/deployment/docker.md)
>
> What the image contains and how migrations run.

> [card] [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md)
>
> Full variable reference.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.