Deploy to Railway

Deploy your Next.js application to Railway with PostgreSQL.

Prerequisites#

Quick Deploy#

Via Railway Dashboard#

  1. Go to railway.app/new
  2. Select Deploy from GitHub repo
  3. Select your repository
  4. Railway auto-detects Next.js and configures build

Via CLI#

1# Install Railway CLI 2npm install -g @railway/cli 3 4# Login 5railway login 6 7# Initialize project 8railway init 9 10# Link to existing project 11railway link 12 13# Deploy 14railway up

Database Setup#

Add PostgreSQL#

# Add PostgreSQL to project railway add --plugin postgresql # Get connection URL railway variables

Configure Prisma#

// prisma/schema.prisma datasource db { provider = "postgresql" url = env("DATABASE_URL") }

Environment Variables#

Railway automatically sets DATABASE_URL when you add PostgreSQL.

Project Configuration#

railway.json#

1{ 2 "$schema": "https://railway.app/railway.schema.json", 3 "build": { 4 "builder": "NIXPACKS", 5 "buildCommand": "npm run build" 6 }, 7 "deploy": { 8 "startCommand": "npm run start", 9 "healthcheckPath": "/api/health", 10 "healthcheckTimeout": 300, 11 "restartPolicyType": "ON_FAILURE", 12 "restartPolicyMaxRetries": 3 13 } 14}

Nixpacks Configuration#

1# nixpacks.toml 2[phases.setup] 3nixPkgs = ["nodejs_20", "openssl"] 4 5[phases.install] 6cmds = ["npm ci"] 7 8[phases.build] 9cmds = ["npx prisma generate", "npm run build"] 10 11[start] 12cmd = "npx prisma migrate deploy && npm start"

Environment Variables#

Set Variables via CLI#

# Set single variable railway variables set NEXT_PUBLIC_APP_URL=https://your-app.railway.app # Set from .env file railway variables set < .env.production

Required Variables#

1# Database (auto-set by Railway) 2DATABASE_URL=postgresql://... 3 4# Authentication 5NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_... 6CLERK_SECRET_KEY=sk_... 7 8# Payments 9STRIPE_SECRET_KEY=sk_... 10NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_... 11 12# App 13NEXT_PUBLIC_APP_URL=https://your-app.railway.app 14NODE_ENV=production

Custom Domain#

Add Domain#

  1. Go to project settings
  2. Click Settings > Domains
  3. Add your custom domain
  4. Configure DNS records

DNS Configuration#

TypeNameValue
CNAME@your-project.up.railway.app
CNAMEwwwyour-project.up.railway.app

Health Check Endpoint#

1// app/api/health/route.ts 2import { prisma } from '@/lib/prisma'; 3import { NextResponse } from 'next/server'; 4 5export async function GET() { 6 try { 7 // Check database connection 8 await prisma.$queryRaw`SELECT 1`; 9 10 return NextResponse.json({ 11 status: 'healthy', 12 timestamp: new Date().toISOString(), 13 database: 'connected', 14 }); 15 } catch (error) { 16 return NextResponse.json( 17 { 18 status: 'unhealthy', 19 timestamp: new Date().toISOString(), 20 database: 'disconnected', 21 error: error instanceof Error ? error.message : 'Unknown error', 22 }, 23 { status: 503 } 24 ); 25 } 26}

CI/CD with GitHub Actions#

1# .github/workflows/railway.yml 2name: Deploy to Railway 3 4on: 5 push: 6 branches: [main] 7 8jobs: 9 test: 10 runs-on: ubuntu-latest 11 steps: 12 - uses: actions/checkout@v4 13 - uses: actions/setup-node@v4 14 with: 15 node-version: '20' 16 cache: 'npm' 17 - run: npm ci 18 - run: npm test 19 - run: npm run lint 20 21 deploy: 22 needs: test 23 runs-on: ubuntu-latest 24 steps: 25 - uses: actions/checkout@v4 26 27 - name: Install Railway CLI 28 run: npm install -g @railway/cli 29 30 - name: Deploy 31 env: 32 RAILWAY_TOKEN: ${{ secrets.RAILWAY_TOKEN }} 33 run: railway up --service ${{ secrets.RAILWAY_SERVICE_ID }}

Multiple Services#

Web + Worker Architecture#

1// railway.json for web service 2{ 3 "build": { 4 "buildCommand": "npm run build" 5 }, 6 "deploy": { 7 "startCommand": "npm start" 8 } 9}
1// railway-worker.json for worker service 2{ 3 "build": { 4 "buildCommand": "npm run build:worker" 5 }, 6 "deploy": { 7 "startCommand": "npm run worker" 8 } 9}

Redis for Queues#

# Add Redis railway add --plugin redis # Access in code const redis = new Redis(process.env.REDIS_URL);

Scaling#

Horizontal Scaling#

In Railway dashboard:

  1. Go to service settings
  2. Enable Replicas
  3. Set number of instances

Vertical Scaling#

# Set resource limits railway variables set RAILWAY_MEMORY_MB=512 railway variables set RAILWAY_CPU_MILLICORES=500

Logs and Monitoring#

1# View logs 2railway logs 3 4# Follow logs 5railway logs -f 6 7# View specific service logs 8railway logs --service web

Database Backups#

# Create backup railway run pg_dump $DATABASE_URL > backup.sql # Restore railway run psql $DATABASE_URL < backup.sql

Rollback#

# List deployments railway deployments # Rollback railway rollback <deployment-id>

Cost Optimization#

Sleep Inactive Services#

In dashboard, enable Sleep for development environments.

Optimize Database#

-- Add indexes for common queries CREATE INDEX CONCURRENTLY idx_users_email ON users(email); -- Vacuum and analyze VACUUM ANALYZE;