Skip to main content

Overview

This guide walks you through deploying the FitAiid backend API to Railway, a modern cloud platform that provides zero-config infrastructure for Node.js applications.
Estimated Time: 15 minutes
Difficulty: ⭐⭐ (Very Easy)

Prerequisites

1

Code on GitHub

Ensure your code is pushed to a GitHub repository with the backend in the backend/ directory.
2

MongoDB Atlas Ready

Your MongoDB Atlas cluster should be created and connection string available.
3

Environment Variables

Have all required API keys and credentials ready (see Environment Variables).

Railway Setup

1. Create Railway Account

1

Sign Up

Navigate to railway.app and click “Start for free”
2

Connect GitHub

Choose GitHub as your login method and authorize Railway to access your repositories.
3

Verify Account

Complete the verification process. You’ll receive $5 in free credits per month.

2. Create New Project

1

New Project

In your Railway dashboard, click “New Project”
2

Deploy from GitHub

Select “Deploy from GitHub repo” and choose your FitAidd repository
3

Configure Root Directory

IMPORTANT: Set the Root Directory to backend/This tells Railway to only deploy the backend folder, not the entire monorepo.
4

Enable Auto-Deploy

Toggle Auto-deploy to ON so Railway automatically deploys on every GitHub push to main branch.
If you forget to set the Root Directory, Railway will try to deploy the entire repository and fail. Always specify backend/ as the root.

Configure Environment Variables

Railway needs access to your environment variables to connect to external services.

Add Variables in Railway Dashboard

  1. In your Railway project, navigate to the Variables tab
  2. Add each variable from the list below
  3. Click “Add Variable” after each entry
# Server Configuration
PORT=5000
NODE_ENV=production

# Database
MONGODB_URI=mongodb+srv://username:[email protected]/FitAiid?retryWrites=true&w=majority

# JWT Authentication
JWT_SECRET=your-super-secure-jwt-secret-minimum-32-characters
JWT_EXPIRES_IN=24h

# Firebase Admin SDK (paste entire JSON)
FIREBASE_ADMIN_SDK={"type":"service_account","project_id":"...","private_key":"..."}

# OpenAI API
OPENAI_API_KEY=sk-proj-...

# Stripe Payments
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

# Email (Gmail App Password)
EMAIL_USER=[email protected]
EMAIL_PASS=your-app-specific-password

# Web Push Notifications (VAPID)
VAPID_PUBLIC_KEY=BH5NRoA1tucvywFDHTef...
VAPID_PRIVATE_KEY=iYatNX1EcokCuw3ZNs4dg...
VAPID_EMAIL=mailto:[email protected]

# CORS Origins (comma-separated)
CORS_ORIGINS=https://fitaiid.vercel.app,http://localhost:3000
See the complete Environment Variables guide for details on obtaining each credential.

MongoDB Atlas Network Configuration

Critical Step: Railway uses dynamic IPs, so you must whitelist all IPs in MongoDB Atlas.
1

Open MongoDB Atlas

Log in to MongoDB Atlas and select your cluster
2

Network Access

Go to Network Access in the left sidebar
3

Add IP Address

Click “Add IP Address” and enter:
  • IP Address: 0.0.0.0/0
  • Description: “Railway Production (All IPs)“
Using 0.0.0.0/0 allows access from any IP. This is required for Railway but ensure your MongoDB credentials are secure.
4

Confirm

Click “Confirm” and wait 1-2 minutes for changes to propagate.

Deploy to Railway

1

Trigger Deployment

After adding all environment variables, Railway will automatically start building your application.
2

Monitor Build Logs

Click on Deployments → Select the active deployment → View LogsYou should see:
npm install --omit=dev
Building application...
 Build successful
Starting server...
🚀 Server running on port 5000
 MongoDB Atlas connected
3

Get Your URL

Once deployed, Railway generates a public URL:
https://fitaiid-api.railway.app
Copy this URL - you’ll need it for the frontend configuration.

Backend Architecture

Dockerfile Configuration

Railway automatically detects and uses your Dockerfile:
# Use lightweight Node.js image
FROM node:18-slim

# Create working directory
WORKDIR /app

# Copy dependency files
COPY package*.json ./

# Install production dependencies only
RUN npm install --omit=dev

# Copy application code
COPY . .

# Expose port
EXPOSE 5000

# Start server
CMD ["node", "src/server.js"]

Database Connection

The backend uses Mongoose with optimized connection settings:
backend/src/config/database.js
const mongoose = require('mongoose');

const connectDB = async () => {
  const options = {
    maxPoolSize: 10,                // Max 10 concurrent connections
    serverSelectionTimeoutMS: 5000, // 5 second timeout
    socketTimeoutMS: 45000,         // 45 second socket timeout
    family: 4                       // Use IPv4
  };

  const conn = await mongoose.connect(process.env.MONGODB_URI, options);
  
  console.log('✅ MongoDB Atlas connected');
  console.log(`📍 Host: ${conn.connection.host}`);
  console.log(`🗃️  Database: ${conn.connection.name}`);
};

Verify Deployment

Test API Health

Open your browser and test the API endpoint:
https://fitaiid-api.railway.app/api/estadisticas/69a05da571820e5d373c8a21
{
  "error": "Token no proporcionado",
  "code": 401
}
This is correct! The 401 error means the API is working but requires authentication.

Test MongoDB Connection

Check Railway logs for MongoDB connection confirmation:
 MongoDB Atlas connected successfully
📍 Host: cluster0.voa5ykf.mongodb.net
🗃️  Database: FitAiid

Troubleshooting

Cause: Missing dependency in package.jsonSolution:
  1. Check Railway build logs for the missing module
  2. Add to package.json dependencies:
npm install <missing-module> --save
  1. Commit and push to GitHub
Cause: IP not whitelisted or incorrect connection stringSolution:
  1. Verify MongoDB Atlas Network Access has 0.0.0.0/0
  2. Check MONGODB_URI format:
mongodb+srv://username:[email protected]/FitAiid
  1. Ensure username/password don’t contain special characters (URL encode if needed)
Cause: Build timeout or memory limit exceededSolution:
  1. Check Railway logs for timeout errors
  2. Optimize dependencies by removing unused packages
  3. Use npm ci instead of npm install for faster builds
  4. Consider upgrading Railway plan for more resources
Cause: Frontend URL not in CORS whitelistSolution:
  1. Add your Vercel URL to Railway environment variables:
CORS_ORIGINS=https://fitaiid.vercel.app,http://localhost:3000
  1. Update backend/src/app.js CORS config:
const corsOptions = {
  origin: process.env.CORS_ORIGINS.split(','),
  credentials: true
};
app.use(cors(corsOptions));
Cause: Variables not saved or deployment not restartedSolution:
  1. Go to Railway Variables tab
  2. Verify all variables are present
  3. Click Redeploy to restart with new variables
  4. Check logs for “undefined” errors

Post-Deployment Tasks

1

Copy Railway URL

Save your Railway URL for frontend configuration:
https://fitaiid-api.railway.app
2

Test All Endpoints

Use Swagger documentation at:
https://fitaiid-api.railway.app/api-docs
3

Monitor Performance

Set up monitoring in Railway Dashboard → Metrics to track:
  • CPU usage
  • Memory consumption
  • Request latency
  • Error rates
4

Configure Custom Domain (Optional)

Add a custom domain in Railway Settings → Domains:
api.fitaiid.com → fitaiid-api.railway.app

Next Steps

Deploy Frontend

Now that your backend is live, deploy the frontend to Vercel and connect it to your Railway API.

Build docs developers (and LLMs) love