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

# Fly.io Setup

> Configure Fly.io for automatic deployment

## Overview

Fly.io hosts and executes your Shopify extension deployments. Each generation triggers a Fly.io build that compiles your code and deploys it to Shopify.

## Why Fly.io?

<CardGroup cols={2}>
  <Card title="Zero Config" icon="wand-magic-sparkles">
    Automatic setup

    * Detects build tools
    * Configures environment
    * Manages dependencies
    * Handles secrets
  </Card>

  <Card title="Fast Builds" icon="bolt">
    Quick deployments

    * Cached layers
    * Parallel builds
    * Instant rollback
    * Hot reloading
  </Card>

  <Card title="GitHub Integration" icon="github">
    Seamless connection

    * Auto-detects pushes
    * Branch deployments
    * PR previews
    * Commit tracking
  </Card>

  <Card title="Shopify CLI" icon="shopify">
    Built-in tools

    * Shopify CLI installed
    * Deploy commands
    * Extension bundling
    * Version management
  </Card>
</CardGroup>

## Setup Process

<Steps>
  <Step title="Create Fly.io Account">
    Sign up for Fly.io:

    1. Go to [fly.io](https://fly.io)
    2. Click "Start a New Project"
    3. Sign in with GitHub
    4. Authorize Fly.io app
  </Step>

  <Step title="Generate Fly.io Token">
    Create API token:

    1. Go to Account Settings → Tokens
    2. Click "Create New Token"
    3. Name it "Synapse Deployment"
    4. Copy the token
  </Step>

  <Step title="Add Token to Synapse">
    Configure in dashboard:

    1. Go to Settings → Integrations
    2. Find Fly.io section
    3. Paste API token
    4. Click "Connect Fly.io"
  </Step>

  <Step title="Project Created">
    Synapse automatically creates:

    * Fly.io project per user
    * Service per generation
    * Environment variables
    * GitHub integration
  </Step>
</Steps>

## Fly.io paid planject Structure

Your Fly.io setup:

```
Fly.io paid planject: synapse-user-{userId}
├── Service: gen-abc123-delivery-estimate
│   ├── Source: GitHub (user-xxx/synapse-extensions:gen-abc123)
│   ├── Build: buildpacks
│   ├── Environment: Production
│   └── Variables: SHOPIFY_*, RAILWAY_*
├── Service: gen-def456-volume-discount
│   ├── Source: GitHub (user-xxx/synapse-extensions:gen-def456)
│   ├── Build: buildpacks
│   ├── Environment: Production
│   └── Variables: SHOPIFY_*, RAILWAY_*
└── Shared Variables
    ├── SHOPIFY_CLI_PARTNERS_TOKEN
    ├── SHOPIFY_CLIENT_ID
    ├── SHOPIFY_CLIENT_SECRET
    └── SHOPIFY_DEV_STORE_URL
```

## How Fly.io Builds Work

<Steps>
  <Step title="GitHub Push">
    Code pushed to repository triggers Fly.io
  </Step>

  <Step title="Build Detection">
    Fly.io uses buildpacks to detect:

    * Language (Node.js, Rust, etc.)
    * Package manager (npm, pnpm, yarn)
    * Build commands
    * Start commands
  </Step>

  <Step title="Dependency Install">
    Installs packages:

    ```bash theme={null}
    # For UI extensions
    npm install

    # For Rust functions
    cargo fetch

    # Shopify CLI
    npm install -g @shopify/cli
    ```
  </Step>

  <Step title="Extension Build">
    Compiles extension:

    ```bash theme={null}
    # UI extensions
    npm run build

    # Rust functions
    cargo build --release
    shopify app function build
    ```
  </Step>

  <Step title="Shopify Deploy">
    Deploys to Shopify:

    ```bash theme={null}
    shopify app deploy --force
    shopify app release --version=latest --force
    ```
  </Step>

  <Step title="Completion">
    Extension live in your dev store
  </Step>
</Steps>

## Environment Variables

Fly.io automatically configures:

| Variable                     | Description            | Source         |
| ---------------------------- | ---------------------- | -------------- |
| `SHOPIFY_CLIENT_ID`          | App client ID          | Synapse config |
| `SHOPIFY_CLIENT_SECRET`      | App client secret      | Synapse config |
| `SHOPIFY_CLI_PARTNERS_TOKEN` | Partners API token     | Synapse config |
| `SHOPIFY_DEV_STORE_URL`      | Development store      | User profile   |
| `FLY_REGION`                 | Deployment environment | Fly.io         |
| `FLY_APP_NAME`               | Service identifier     | Fly.io         |
| `FLY_APP_ID`                 | Project identifier     | Fly.io         |

### Adding Custom Variables

Add your own environment variables:

<Tabs>
  <Tab title="Via Fly.io Dashboard">
    1. Open your Fly.io project
    2. Select service
    3. Go to Variables tab
    4. Click "New Variable"
    5. Enter name and value
    6. Click "Add"
    7. Redeploy service
  </Tab>

  <Tab title="Via Fly.io CLI">
    ```bash theme={null}
    # Install Fly.io CLI
    brew install flyctl

    # Login
    flyctl auth login

    # Link to project
    flyctl apps list

    # Add variable
    flyctl secrets set API_KEY=your-key

    # Or from file
    flyctl secrets set --file .env
    ```
  </Tab>

  <Tab title="Via fly.toml">
    Configure in repository:

    ```json theme={null}
    {
      "build": {
        "builder": "nixpacks"
      },
      "deploy": {
        "numReplicas": 1,
        "restartPolicyType": "ON_FAILURE"
      },
      "env": {
        "NODE_ENV": "production",
        "LOG_LEVEL": "info"
      }
    }
    ```
  </Tab>
</Tabs>

## buildpacks Build Configuration

Fly.io uses buildpacks for builds. Customize in `fly.toml`:

```json theme={null}
{
  "build": {
    "builder": "nixpacks",
    "buildCommand": "npm run build:custom",
    "watchPatterns": [
      "extensions/**/*.tsx",
      "extensions/**/*.rs"
    ]
  },
  "deploy": {
    "startCommand": "./deploy.sh",
    "restartPolicyType": "ON_FAILURE",
    "restartPolicyMaxRetries": 10,
    "numReplicas": 1,
    "healthcheckPath": "/health",
    "healthcheckTimeout": 300
  }
}
```

## Viewing Logs

Monitor deployments in real-time:

<Tabs>
  <Tab title="Fly.io Dashboard">
    1. Open Fly.io project
    2. Select service
    3. Click "Deployments" tab
    4. Click specific deployment
    5. View build and runtime logs

    **Log output:**

    ```
    Building...
    [nixpacks] Detecting builder...
    [nixpacks] Using Node.js builder
    [nixpacks] Installing dependencies...
    [nixpacks] Running build command...
    Building extension: delivery-estimate
    ✓ Built in 12.3s
    Deploying to Shopify...
    ✓ Deployed version 2024.10.30.1
    ✓ Released to dev store
    Deployment complete!
    ```
  </Tab>

  <Tab title="Fly.io CLI">
    ```bash theme={null}
    # View logs
    flyctl logs

    # Follow logs
    flyctl logs --follow

    # Filter by deployment
    flyctl logs --deployment <deployment-id>

    # Export logs
    flyctl logs > deployment.log
    ```
  </Tab>
</Tabs>

## Managing Services

<AccordionGroup>
  <Accordion title="View All Services" icon="list">
    See all deployed services:

    ```bash theme={null}
    # Via CLI
    flyctl apps list

    # Via dashboard
    # Open project → View all services
    ```

    Each generation gets its own service for isolation
  </Accordion>

  <Accordion title="Restart Service" icon="rotate">
    Manually restart a service:

    ```bash theme={null}
    # Via CLI
    flyctl apps restart

    # Via dashboard
    # Service → Settings → Restart Service
    ```

    Useful for applying new environment variables
  </Accordion>

  <Accordion title="Delete Service" icon="trash">
    Remove unused services:

    ```bash theme={null}
    # Via CLI
    flyctl apps destroy <service-id>

    # Via dashboard
    # Service → Settings → Delete Service
    ```

    Frees up project resources
  </Accordion>

  <Accordion title="Service Metrics" icon="chart-line">
    Monitor performance:

    * CPU usage
    * Memory consumption
    * Network traffic
    * Build duration
    * Deployment frequency

    Available in Fly.io dashboard under Metrics tab
  </Accordion>
</AccordionGroup>

## Deployment Strategies

<Tabs>
  <Tab title="Instant Deploy (Default)">
    Every push triggers immediate deployment:

    **Pros:**

    * Fast feedback
    * Always up-to-date
    * No manual steps

    **Cons:**

    * May deploy broken code
    * No review process

    **Best for:** Development, rapid iteration
  </Tab>

  <Tab title="Manual Deploy">
    Approve deployments manually:

    ```json theme={null}
    // fly.toml
    {
      "deploy": {
        "requireApproval": true
      }
    }
    ```

    **Pros:**

    * Review before deploy
    * Controlled releases
    * Prevent mistakes

    **Cons:**

    * Slower deployment
    * Manual intervention

    **Best for:** Production, sensitive changes
  </Tab>

  <Tab title="PR Previews">
    Deploy pull requests to preview environments:

    Automatically enabled for PR branches

    **Pros:**

    * Test before merge
    * Isolated testing
    * Share previews

    **Cons:**

    * Uses more resources
    * Additional services

    **Best for:** Team collaboration, QA
  </Tab>
</Tabs>

## Cost Management

Fly.io pricing and optimization:

### Free Tier

* \$5 free credit per month
* Pauses after 500 hours
* Shared resources
* Community support

### Pro Plan (\$20/month)

* \$20 credit included
* Usage-based billing
* Dedicated resources
* Priority support

### Optimization Tips

<CardGroup cols={2}>
  <Card title="Remove Unused Services" icon="trash">
    Delete old generation services to save resources
  </Card>

  <Card title="Use Sleep Mode" icon="moon">
    Configure services to sleep when inactive
  </Card>

  <Card title="Optimize Builds" icon="bolt">
    Cache dependencies, minimize build time
  </Card>

  <Card title="Monitor Usage" icon="gauge">
    Track resource consumption in dashboard
  </Card>
</CardGroup>

## Advanced Configuration

<AccordionGroup>
  <Accordion title="Custom Dockerfile">
    Use custom Docker build instead of buildpacks:

    ```dockerfile theme={null}
    # Dockerfile
    FROM node:20-alpine

    # Install Shopify CLI
    RUN npm install -g @shopify/cli

    # Copy extension code
    WORKDIR /app
    COPY . .

    # Install dependencies
    RUN npm install

    # Build extension
    RUN npm run build

    # Deploy to Shopify
    CMD ["shopify", "app", "deploy", "--force"]
    ```

    Fly.io automatically detects and uses Dockerfile
  </Accordion>

  <Accordion title="Multi-Stage Builds">
    Optimize image size:

    ```dockerfile theme={null}
    # Build stage
    FROM node:20 AS builder
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    COPY . .
    RUN npm run build

    # Deploy stage
    FROM node:20-alpine
    RUN npm install -g @shopify/cli
    WORKDIR /app
    COPY --from=builder /app/extensions ./extensions
    COPY shopify.app.toml .
    CMD ["shopify", "app", "deploy", "--force"]
    ```
  </Accordion>

  <Accordion title="Webhooks">
    Trigger actions on deployment events:

    1. Service → Settings → Webhooks
    2. Add webhook URL
    3. Select events:
       * Deployment started
       * Deployment succeeded
       * Deployment failed
    4. Receive JSON payload

    ```json theme={null}
    {
      "event": "deployment.succeeded",
      "project": "synapse-user-123",
      "service": "gen-abc123",
      "deployment": "dep-xyz789",
      "timestamp": "2025-10-30T12:00:00Z"
    }
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Build Failed">
    **Error:** Build fails during npm install or compilation

    **Causes:**

    * Missing dependencies
    * Node version mismatch
    * Memory limit exceeded

    **Solutions:**

    * Check package.json
    * Specify Node version in package.json:
      ```json theme={null}
      {
        "engines": {
          "node": "20.x"
        }
      }
      ```
    * Review build logs for specific errors
    * Upgrade to Pro plan for more resources
  </Accordion>

  <Accordion title="Deployment Timeout">
    **Error:** Deployment exceeds time limit

    **Causes:**

    * Large extension bundle
    * Slow Shopify API
    * Network issues

    **Solutions:**

    * Optimize bundle size
    * Retry deployment
    * Increase timeout in fly.toml:
      ```json theme={null}
      {
        "deploy": {
          "healthcheckTimeout": 600
        }
      }
      ```
  </Accordion>

  <Accordion title="Environment Variables Missing">
    **Error:** SHOPIFY\_CLIENT\_ID not found

    **Causes:**

    * Variables not configured
    * Service not linked to project

    **Solutions:**

    * Verify variables in dashboard
    * Re-add via Fly.io CLI:
      ```bash theme={null}
      flyctl secrets set SHOPIFY_CLIENT_ID=xxx
      ```
    * Redeploy service
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="GitHub Integration" icon="github" href="/deployment/github-integration">
    Configure GitHub connection
  </Card>

  <Card title="Deployment Pipeline" icon="diagram-project" href="/concepts/deployment-pipeline">
    Understand the full pipeline
  </Card>

  <Card title="Debugging" icon="bug" href="/advanced/debugging">
    Debug deployment issues
  </Card>

  <Card title="Best Practices" icon="star" href="/advanced/best-practices">
    Optimize your workflow
  </Card>
</CardGroup>
