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

# Platform Documentation

> Complete guide to building and deploying on Emergent.sh

## Understanding the Basics

### What is Preview vs Deployment?

| Feature                 | Preview                                                  | Deployment                                   |
| ----------------------- | -------------------------------------------------------- | -------------------------------------------- |
| **What it is**          | Your testing playground                                  | Your live app                                |
| **How long it lasts**   | Upto 30 minutes (if there is no interaction), then stops | Always online                                |
| **Resources (CPU/RAM)** | High (more powerful)                                     | Lower (optimized)                            |
| **URL looks like**      | yourapp.preview\.emergentagent.com                       | yourapp.emergent.cloud/yourapp.emergent.host |
| **Database**            | Preview database                                         | Production database                          |
| **Cost**                | Only development credits                                 | 50 credits (\$10) first time (starter tier)  |

<Info>
  **Simple Rule:** Preview and deployment are completely separate. When you make changes in preview, you must redeploy to see them live.
</Info>

### Machine Types in Preview (add more context - what and why does the user need to know)

| Machine     | Power          | When to Use            |
| ----------- | -------------- | ---------------------- |
| **Regular** | Standard power | Normal development     |
| **Large**   | Extra power    | Testing heavy features |

<Info>
  On paid tiers, the switch between machine types happens automatically. On basic tiers, the agent will stop and user must wake up the agent with a larger machine (simple button press)
</Info>

### Before You Deploy

<Check>
  * Agent is awake (deployment won't work if agent is asleep)
  * App works in preview (fix all errors before deploying)
  * Not using too much compute (app will shut down if it uses too much) - *have to explain what is compute*
  * *Optimize your queries - instruct the agent to write optimized code*
  * *Plan ahead if your database will be large - reach out in advance to ensure your app is deployed smoothly.*
</Check>

## Phase 1: Build Phase

### What Happens Here?

Your code gets compiled and prepared for production. Think of it like packing your app into a box ready to ship.

| **What Gets Built**       | **From Where**           |
| ------------------------- | ------------------------ |
| Frontend (what users see) | Your React code          |
| Backend (the server)      | Your Python/FastAPI code |
| JavaScript packages       | package.json file        |
| Python packages           | requirements.txt file    |

<Note>
  **Time:** \~5 minutes
</Note>

### The Big Problem: Heavy Libraries

| **In Preview**                             | **In Deployment**                      | **The Rationale**           |
| ------------------------------------------ | -------------------------------------- | --------------------------- |
| Heavy libraries work fine (high resources) | Heavy libraries fail (lower resources) | *why this is the way it is* |
| Example: Can use pandas, matplotlib        | Example: These will timeout or crash   |                             |

<Warning>
  **Why This Happens:** Deployment has less CPU and RAM than preview. What works in testing might not work when live.\
  \[\*\*Emergent allows users more freedom to create an app and then scale as you grow] \*\*
</Warning>

### The Solution: Use APIs Instead

| **Don't Install This**     | **Do This Instead**               |
| -------------------------- | --------------------------------- |
| pandas, matplotlib, plotly | Use external data analysis APIs   |
| Large AI/ML libraries      | Use OpenAI API, Hugging Face API  |
| Playwright, Selenium       | Use external automation services  |
| Heavy image tools          | Use Cloudinary or imgix API       |
| Big calculations           | Use AWS Lambda or Cloud Functions |

<Tip>
  **Simple Rule:** If a library is large, use an API service instead of installing it - *say why.*
</Tip>

### Some Examples of External Services You Can Integrate With

| **Service Type** | **Some Examples**               | **What It Does**           | **The Reason** |
| ---------------- | ------------------------------- | -------------------------- | -------------- |
| **File Storage** | Amazon S3, Google Cloud Storage | Store images, videos, PDFs |                |
| **Databases**    | Supabase, PostgreSQL            | Handle lots of data        |                |
| **File Hosting** | Cloudinary                      | Manage images and media    |                |

<Info>
  *What is the difference between a db and a storage service - why the investment is worth it to build serious apps.*
</Info>

### Some Common Build Errors

| **Error**          | **What It Means**                             | **How to Fix (What to tell the agent)** |
| ------------------ | --------------------------------------------- | --------------------------------------- |
| "Module not found" | Missing from package.json or requirements.txt | Add the missing package                 |
| "Build timeout"    | App is too heavy                              | Remove heavy libraries, use APIs        |
| "Syntax error"     | Code has mistakes                             | Fix the code error                      |
| "Out of memory"    | Using too much RAM                            | Optimize code, reduce packages          |

### How to Fix Build Problems (with the agent)

<Steps>
  <Step title="Share logs with agent">
    Use the one-click log sharing button \_\[add GIF] \_or copy logs and share in chat
  </Step>

  <Step title="Ask agent to optimize">
    Tell the agent to optimize your code
  </Step>

  <Step title="Agent identifies the relevant action">
    The agent will perform the fix and solve the error
  </Step>

  <Step title="Test again">
    Verify everything works in preview
  </Step>

  <Step title="Perform a one click Health Check">
    It is strongly recommended to ask the agent to perform a health check before attempting to deploy again. This ensures the app has a much better chance of a clean deployment.
  </Step>

  <Step title="Deploy Your App ">
    Once solved, attempt to deploy your app again.
  </Step>
</Steps>

## Phase 2: Database Migration

### What Happens Here?

Your data moves from preview to production. Like moving your furniture to a new house.

<Note>
  **Time:** 1-2 minutes
</Note>

### What is a Database?

| **Type**           | **How It Works**            | **How we handle it**               |
| ------------------ | --------------------------- | ---------------------------------- |
| **Relational**     | Data in tables (like Excel) | You can connect your own database. |
| **Non-Relational** | Data in flexible documents  | MongoDB by default                 |

<Info>
  **Emergent uses MongoDB by default**, which is flexible and easy to work with.
</Info>

### How Our Databases Work

| **What You Need to Know**     | **Details**                                                                                                                                              |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Shared hosting**            | Multiple users share the same cluster - *simplify*                                                                                                       |
| **Preview vs deployment**     | They are completely separate databases                                                                                                                   |
| **Built-in storage**          | Can store large amounts of text & limited files, images, PDFs in MongoDB - replace with a better explanation - \_why we suggest external connections. \_ |
| **Queries must be optimized** | Slow queries will fail during deployment                                                                                                                 |

<Warning>
  **Important:** The agent cannot see your deployed database unless you share logs. Preview and deployment are separate environments.
</Warning>

### When Databases Get Too Heavy

| **Problem**               | **Solution**                             |
| ------------------------- | ---------------------------------------- |
| Storing many large images | Use Amazon S3 or Google Cloud Storage    |
| Lots of videos or PDFs    | Use file hosting service like Cloudinary |
| Very large datasets       | Use Supabase or PostgreSQL               |
| High traffic app          | Get dedicated database (contact support) |

### Making Queries Optimized

| **Query Speed**         | **Result**                          | **What to Do**        |
| ----------------------- | ----------------------------------- | --------------------- |
| **Unoptimized queries** | Deployment may fail, or timeout     | Ask agent to optimize |
| **Optimized queries**   | Deployment has improved performance | Ready to go           |

<Tip>
  **How to Optimize:** Tell the agent "optimize my database queries" and it will rewrite them better.
</Tip>

### Common Database Errors (shows up in logs, share with agent to fix)

| **Error**           | **What It Means**         | **How to Fix (Ask the agent)** | **Simple Fix**              |
| ------------------- | ------------------------- | ------------------------------ | --------------------------- |
| "Connection failed" | Can't connect to database | Check MONGO\_URL in .env file  | Fork and Replace deployment |
| "Query timeout"     | Query too slow            | Ask agent to optimize queries  |                             |
| "Schema error"      | Data format is wrong      | Ask agent to fix               |                             |

### Connecting Your Own Database

<Steps>
  <Step title="Get credentials">
    Get URL and password from your database provider
  </Step>

  <Step title="Share with agent">
    Provide credentials to the Emergent agent
  </Step>

  <Step title="Agent configures">
    Agent sets up the connection
  </Step>

  <Step title="Test connection">
    Verify it works in preview
  </Step>

  <Step title="Deploy">
    Deploy with your custom database
  </Step>
</Steps>

## Phase 3: Exporting Secrets

### What Are Secrets?

Secrets are passwords, API keys, and settings your app needs. They go in the .env file.

<Note>
  **Time:** 1-2 minutes
</Note>

### Two Types of Secrets

| **Type**               | **Examples**                                         | **Who Provides** |
| ---------------------- | ---------------------------------------------------- | ---------------- |
| **Emergent gives you** | MongoDB URL, Backend URL, Port, CORS                 | Automatic        |
| **You provide**        | API keys, your database passwords, external services | You              |

### The Golden Rules

<CardGroup cols={2}>
  <Card title="Never put secrets in code" icon="ban">
    Anyone can see them (security risk)
  </Card>

  <Card title="Always use .env files" icon="file">
    Easy to change, stays private
  </Card>

  <Card title="Be very careful editing" icon="triangle-exclamation">
    One wrong character breaks everything
  </Card>

  <Card title="Must redeploy after changing" icon="rotate">
    Changes only work after you redeploy
  </Card>
</CardGroup>

### What Breaks Your App

| **If This is Wrong** | **This Happens**             |
| -------------------- | ---------------------------- |
| Port number          | App can't connect            |
| URL                  | You get 404 errors           |
| API key              | External services don't work |
| Database URL         | Can't load any data          |

<Warning>
  **Be careful!** Double-check everything before deploying.
</Warning>

### Common Secret Errors

| **Error**            | **What It Means**            | **How to Fix**             |
| -------------------- | ---------------------------- | -------------------------- |
| "Missing variable"   | You forgot to add it to .env | Add the missing variable   |
| "Invalid API key"    | Key is wrong or expired      | Get a new valid key        |
| "Connection refused" | URL or port is wrong         | Fix the URL or port number |

### Best Practices

<AccordionGroup>
  <Accordion title="Test API keys before deploying">
    Make sure they work by testing them in preview first
  </Accordion>

  <Accordion title="Keep a backup of .env file">
    Save a copy in case you need to restore settings
  </Accordion>

  <Accordion title="Name variables clearly">
    Use descriptive names so you know what each does
  </Accordion>

  <Accordion title="Update URLs after changing domains">
    External services need to know your new domain
  </Accordion>
</AccordionGroup>

## Phase 4: Deploy and Health Check

### Deploy: Setting Up Infrastructure

Your app is launched on servers and made available to the world.

**What Happens:**

* Servers are set up (Kubernetes)
* Your app is installed on servers
* Network connections are configured
* Resources (CPU/RAM) are assigned

<Note>
  **Time:** 3-5 minutes
</Note>

### Common Deploy Errors

| **Error**             | **What It Means**        | **How to Fix**                                          |
| --------------------- | ------------------------ | ------------------------------------------------------- |
| "Provisioning failed" | Server setup problem     | Wait and try again, contact support if it keeps failing |
| "Container crashed"   | App won't start          | Check logs, fix startup code                            |
| "Port conflict"       | Port already being used  | Check port settings                                     |
| "Out of resources"    | App needs too much power | Optimize app, use external APIs                         |

### Health Check: Is Everything Working?

After deployment, the system checks if your app is actually working.

**What Gets Checked:**

* App responds to requests
* APIs are working
* Frontend loads correctly
* Database is connected
* All services are running

<Note>
  **Time:** 1-2 minutes
</Note>

### If Health Check Fails

| **Problem**       | **What It Means**         | **How to Fix**             |
| ----------------- | ------------------------- | -------------------------- |
| "App crashed"     | Code error on startup     | Review logs, fix the error |
| "API error 500"   | Backend has problems      | Check backend code         |
| "White screen"    | Frontend won't load       | Check frontend build       |
| "Database failed" | Can't connect to database | Verify connection info     |
| "CORS error"      | Security settings wrong   | Fix CORS configuration     |

<Warning>
  **Important:** If health check fails, your app won't go live. This protects you from publishing a broken app.
</Warning>

### Total Deployment Time

| **All Phases Combined**                            | **Typical Time** |
| -------------------------------------------------- | ---------------- |
| Build + Database + Secrets + Deploy + Health Check | 10-15 minutes    |

## Understanding Deployment Costs

### How Much Does It Cost?

| **What**                       | **Cost**          | **When You Pay**       |
| ------------------------------ | ----------------- | ---------------------- |
| **First time you deploy**      | 50 credits (\$10) | Once per app           |
| **Update same app (redeploy)** | FREE              | Every time after first |
| **Deploy a new app**           | 50 credits (\$10) | Once per new app       |

### What Do You Get for 50 Credits?

<CardGroup cols={2}>
  <Card title="24/7 Uptime" icon="clock">
    Your app runs always online
  </Card>

  <Card title="Database Hosting" icon="database">
    Managed MongoDB included
  </Card>

  <Card title="Build Pipeline" icon="gear">
    All deployment steps included
  </Card>

  <Card title="Custom Domains" icon="globe">
    Auto-linking for your domains
  </Card>
</CardGroup>

<Tip>
  **Good News:** After paying once, you can update your app unlimited times for free.
</Tip>

### What Happens When You Redeploy?

| This Updates                     | This Stays the Same                   |
| -------------------------------- | ------------------------------------- |
| Your code (frontend and backend) | Your database (from first deployment) |

<Warning>
  **Important:** Redeploying updates your code but NOT your database.

  If you changed data in preview after your first deployment, that data won't appear in production. You need to manually move it.
</Warning>

## Replacing Existing Deployments

### Why Replace Instead of Deploy New?

**Scenario:** You forked your app, made it better, and want the new version to replace the old one WITHOUT paying another 50 credits.

### Your Options

| **Option**        | **When to Use**                | **What Happens to Data**      |
| ----------------- | ------------------------------ | ----------------------------- |
| **Fresh start**   | No important data to keep      | Old data deleted, start fresh |
| **Keep old data** | Users have important data      | Old data stays                |
| **Merge data**    | Want old AND new data together | Combines both databases       |

### Option 1: Fresh Start (Copies Preview Data)

<Steps>
  <Step title="Replace deployment">
    Click "Replace Existing Deployment"
  </Step>

  <Step title="Choose fresh database">
    Select "Fresh Database" option
  </Step>

  <Step title="Deploy">
    New app replaces old one
  </Step>
</Steps>

**Result:** Old app gone, new app live, no extra charge.

### Option 2: Merge Old and New Data

<Steps>
  <Step title="Request export">
    Email [support@emergent.sh](mailto:support@emergent.sh) to export data (up to 24 hours)
  </Step>

  <Step title="Download data">
    Get your data when ready (few minutes)
  </Step>

  <Step title="Share with agent">
    Give data to agent, ask to merge
  </Step>

  <Step title="Check for conflicts">
    Tell agent to verify no data conflicts
  </Step>

  <Step title="Deploy merged data">
    Deploy with combined database
  </Step>
</Steps>

**Result:** All data preserved, no extra charge.

### Option 3: Zero Risk Method (High Traffic Apps)

<Steps>
  <Step title="Export old data">
    Request from support (time only)
  </Step>

  <Step title="Deploy new app separately">
    Deploy as standalone (50 credits)
  </Step>

  <Step title="Add old data">
    Load exported data to new app
  </Step>

  <Step title="Verify everything">
    Check all data and features work
  </Step>

  <Step title="Turn off old app">
    Shut down old app (free)
  </Step>
</Steps>

**Result:** Zero downtime, zero data loss, but costs 50 credits.

## Working with URLs and Domains

### The Three Types of URLs

| **URL Type**    | **Looks Like**                 | **When It's Online** | **Power** |
| --------------- | ------------------------------ | -------------------- | --------- |
| **Preview**     | app.preview\.emergentagent.com | 30 minutes only      | High      |
| **Deployed**    | app.emergent.host              | Always               | Normal    |
| **Your domain** | yourdomain.com                 | Always               | Normal    |

### Adding Your Own Domain

<Steps>
  <Step title="Buy a domain">
    Purchase from GoDaddy, Namecheap, etc (right away)
  </Step>

  <Step title="Change DNS settings">
    Update at your domain provider (right away)
  </Step>

  <Step title="Auto-link in Emergent">
    Use Emergent dashboard (5-10 minutes)
  </Step>

  <Step title="Wait for propagation">
    DNS spreads worldwide automatically (10 min to 2 hours)
  </Step>
</Steps>

<Warning>
  **After You Link Domain:** Update all external services (APIs, payment processors, OAuth) to use your new domain instead of the old emergent.host URL.
</Warning>

## Troubleshooting Guide

### Quick Problem Solver

| **Problem**             | **Quick Fix**                                     |
| ----------------------- | ------------------------------------------------- |
| **Build fails**         | Share logs with agent, check for missing packages |
| **Database fails**      | Check MONGO\_URL, ask agent to optimize queries   |
| **Deploy fails**        | Check logs, contact support if it keeps happening |
| **App won't start**     | Check .env file for wrong values                  |
| **Domain doesn't work** | Wait 10 min to 2 hours for DNS to update          |
| **APIs stop working**   | Update URLs at external service providers         |
| **Preview shuts down**  | Use Large machine or make app lighter             |
| **Can't deploy**        | Wake up the agent first                           |

### When to Share Logs

| **Problem**    | **What Logs Show**                   |
| -------------- | ------------------------------------ |
| Build fails    | What packages are missing            |
| Database fails | What queries are slow                |
| Deploy fails   | What infrastructure problem occurred |
| App crashes    | What code error happened             |

<Tip>
  **How:** Click the one-click log share button, send to agent, agent tells you how to fix.
</Tip>

### When to Email Support

Email [**support@emergent.sh**](mailto:support@emergent.sh) when:

| **Problem**                  | **What to Include**              |
| ---------------------------- | -------------------------------- |
| Same error keeps happening   | Job ID, logs, what you tried     |
| Server/infrastructure issues | Job ID, error message            |
| Need to export database      | Job ID, how big your database is |
| Want dedicated database      | How much traffic you have        |
| Domain problems              | Your domain name, DNS settings   |

## Pre-Deployment Checklist

<Check>
  * Works perfectly in preview (catch problems early)
  * Database queries are fast (prevent timeouts)
  * Using APIs instead of heavy libraries (avoid crashes)
  * All packages listed in config files (prevent build errors)
  * API keys work (make sure integrations function)
  * Secrets in .env file, not code (security)
  * Agent is awake (can't deploy if agent is asleep)
</Check>

## Quick Reference

### Key Terms Simple Guide

| **Term**          | **What It Means**                                         |
| ----------------- | --------------------------------------------------------- |
| **Preview**       | Testing area, stops after 30 min, high power              |
| **Deployment**    | Live app, always on, normal power                         |
| **Redeploy**      | Update your code for free (same app)                      |
| **Job ID**        | Your app's unique number                                  |
| **Heavy library** | Big package that works in preview but fails when deployed |
| **External API**  | Service you connect to instead of installing locally      |
| **.env file**     | Where you store passwords and keys                        |
| **Agent**         | AI helper that builds and fixes your app                  |
