> ## 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.

# Debugging

> Debug and troubleshoot Shopify extensions and functions

## Overview

Comprehensive debugging guide for identifying and fixing issues in your Synapse-generated extensions and functions.

## Debugging Tools

<CardGroup cols={2}>
  <Card title="Browser DevTools" icon="browser">
    Debug UI extensions in checkout

    * Console logs
    * Network requests
    * React DevTools
    * Performance profiling
  </Card>

  <Card title="Shopify CLI" icon="terminal">
    Local development and logs

    * `shopify app dev`
    * Function logs
    * Extension preview
    * GraphQL introspection
  </Card>

  <Card title="Fly.io Logs" icon="train">
    Deployment and build logs

    * Build output
    * Deploy status
    * Runtime errors
    * Environment issues
  </Card>

  <Card title="MCP Validation" icon="check-circle">
    Synapse validation output

    * API compliance
    * Component usage
    * Type errors
    * Best practices
  </Card>
</CardGroup>

## Common Issues

<Tabs>
  <Tab title="Extension Not Showing">
    **Symptoms:**

    * Extension doesn't appear in checkout
    * Not visible in admin
    * Deployment succeeded but nothing shows

    **Debugging Steps:**

    <Steps>
      <Step title="Check Deployment Status">
        ```bash theme={null}
        shopify app versions list
        ```

        Verify extension is deployed and released
      </Step>

      <Step title="Verify Extension Configuration">
        Check `shopify.extension.toml`:

        ```toml theme={null}
        type = "ui_extension"
        name = "delivery-estimate"

        [[extensions.targeting]]
        target = "purchase.checkout.delivery-address.render-after"
        ```

        Ensure target matches checkout flow
      </Step>

      <Step title="Add to Checkout Editor">
        1. Settings → Checkout → Customize
        2. Find extension in left sidebar
        3. Drag into layout
        4. Save
      </Step>

      <Step title="Check Conditional Logic">
        Review your component for conditions that might hide it:

        ```tsx theme={null}
        // This might hide your extension!
        if (cartTotal < 50) return null;
        ```
      </Step>
    </Steps>

    **Common Causes:**

    * Wrong extension target
    * Not added to checkout editor
    * Conditional rendering hiding it
    * Extension not released (draft mode)
  </Tab>

  <Tab title="GraphQL Errors">
    **Symptoms:**

    * "Field not found" errors
    * Data not loading
    * Undefined values

    **Debugging Steps:**

    <Steps>
      <Step title="Check Console">
        Open browser DevTools console:

        ```
        Error: Field 'deliveryAddress' not found on type 'Cart'
        ```
      </Step>

      <Step title="Verify GraphQL Query">
        Check `run.graphql`:

        ```graphql theme={null}
        query RunInput {
          cart {
            deliveryAddress {  # ❌ Wrong
              country
            }
          }
        }
        ```

        Should be:

        ```graphql theme={null}
        query RunInput {
          cart {
            deliveryGroups {  # ✅ Correct
              deliveryAddress {
                country
              }
            }
          }
        }
        ```
      </Step>

      <Step title="Test Query in GraphiQL">
        Use Shopify GraphiQL to test:

        ```bash theme={null}
        shopify app graphiql
        ```

        Paste your query and verify it works
      </Step>

      <Step title="Check API Version">
        Ensure using correct API version in `shopify.app.toml`:

        ```toml theme={null}
        scopes = "write_products,read_customers"

        [app_proxy]
        prefix = "apps"
        ```
      </Step>
    </Steps>

    **Common Causes:**

    * Typo in field names
    * Wrong API version
    * Missing permissions
    * Incorrect query structure
  </Tab>

  <Tab title="Function Not Applying">
    **Symptoms:**

    * Discount/shipping/payment function not working
    * No errors but function doesn't execute
    * Function logs empty

    **Debugging Steps:**

    <Steps>
      <Step title="Check Function Logs">
        ```bash theme={null}
        shopify app function logs --watch
        ```

        See if function is being called
      </Step>

      <Step title="Verify Function is Active">
        For discount functions:

        1. Go to Discounts in admin
        2. Verify discount exists
        3. Check it's not expired
        4. Ensure it's active
      </Step>

      <Step title="Test Input/Output">
        Create test input file:

        ```json theme={null}
        {
          "cart": {
            "lines": [{
              "quantity": 5,
              "merchandise": {
                "id": "gid://shopify/ProductVariant/123"
              }
            }]
          }
        }
        ```

        Test locally:

        ```bash theme={null}
        cat test-input.json | shopify app function run
        ```
      </Step>

      <Step title="Check Return Value">
        Ensure function returns proper output:

        ```rust theme={null}
        // ❌ Wrong: empty operations
        Ok(FunctionRunResult {
            operations: vec![],
        })

        // ✅ Correct: returns discount
        Ok(FunctionRunResult {
            operations: vec![
                Operation::Discount(/* ... */)
            ],
        })
        ```
      </Step>
    </Steps>

    **Common Causes:**

    * Function not activated in admin
    * Logic always returns empty
    * Input query missing data
    * Function crashes (check logs)
  </Tab>

  <Tab title="Build Failures">
    **Symptoms:**

    * Fly.io build fails
    * TypeScript errors
    * Dependency issues

    **Debugging Steps:**

    <Steps>
      <Step title="Check Fly.io Logs">
        View build output in Fly.io dashboard:

        ```
        [error] Type 'string | undefined' is not assignable to type 'string'
        ```
      </Step>

      <Step title="Fix TypeScript Errors">
        Add proper type guards:

        ```tsx theme={null}
        // ❌ Wrong
        const country = address.country;

        // ✅ Correct
        const country = address?.country ?? 'US';
        ```
      </Step>

      <Step title="Verify Dependencies">
        Check package.json versions:

        ```json theme={null}
        {
          "dependencies": {
            "@shopify/ui-extensions-react": "^2024.10.0",
            "react": "^18.0.0"
          }
        }
        ```
      </Step>

      <Step title="Build Locally">
        Test build before pushing:

        ```bash theme={null}
        npm install
        npm run build
        ```

        Fix any errors locally first
      </Step>
    </Steps>

    **Common Causes:**

    * TypeScript type errors
    * Missing dependencies
    * Version conflicts
    * Syntax errors
  </Tab>
</Tabs>

## Debugging Techniques

<AccordionGroup>
  <Accordion title="Console Logging" icon="terminal">
    Add debug logs to your extensions:

    ```tsx theme={null}
    function Extension() {
      const address = useShippingAddress();
      
      console.log('Extension rendered');
      console.log('Shipping address:', address);
      
      useEffect(() => {
        console.log('Address changed:', address);
      }, [address]);
      
      return <YourComponent />;
    }
    ```

    View in browser DevTools → Console
  </Accordion>

  <Accordion title="React DevTools" icon="react">
    Inspect component state and props:

    1. Install [React DevTools](https://react.dev/learn/react-developer-tools)
    2. Open checkout in browser
    3. Open DevTools → Components tab
    4. Find your extension component
    5. Inspect props, state, hooks

    **Useful for:**

    * Checking hook values
    * Verifying props
    * Testing renders
  </Accordion>

  <Accordion title="Network Debugging" icon="network-wired">
    Monitor API calls:

    1. Open DevTools → Network tab
    2. Filter by "Fetch/XHR"
    3. Look for GraphQL requests
    4. Inspect request/response

    **Check for:**

    * Query variables
    * Response data
    * Error messages
    * Status codes
  </Accordion>

  <Accordion title="Function Testing" icon="function">
    Test functions locally:

    ```bash theme={null}
    # Navigate to function
    cd extensions/my-function

    # Create test input
    cat > test.json << EOF
    {
      "cart": {
        "cost": {
          "subtotalAmount": {
            "amount": "150.00"
          }
        }
      }
    }
    EOF

    # Run function
    cargo run < test.json
    # or
    node src/run.js < test.json

    # View output
    ```
  </Accordion>
</AccordionGroup>

## Performance Debugging

<CardGroup cols={2}>
  <Card title="Slow Extension Load" icon="gauge">
    **Symptoms:** Extension takes long to appear

    **Debug:**

    * DevTools → Performance tab
    * Record page load
    * Look for long tasks
    * Check bundle size

    **Fixes:**

    * Reduce bundle size
    * Lazy load components
    * Optimize images
    * Remove unused deps
  </Card>

  <Card title="Function Timeout" icon="clock">
    **Symptoms:** Function exceeds 5ms limit

    **Debug:**

    * Check function logs for timing
    * Add timing code:

    ```rust theme={null}
    let start = std::time::Instant::now();
    // your logic
    eprintln!("Took {:?}", start.elapsed());
    ```

    **Fixes:**

    * Use Rust instead of JS
    * Minimize loops
    * Cache calculations
    * Reduce query surface
  </Card>

  <Card title="Memory Issues" icon="memory">
    **Symptoms:** Extension crashes, Fly.io OOM

    **Debug:**

    * DevTools → Memory tab
    * Take heap snapshots
    * Check for memory leaks

    **Fixes:**

    * Clean up event listeners
    * Avoid large data structures
    * Use React.memo
    * Optimize re-renders
  </Card>

  <Card title="Large Bundle" icon="box">
    **Symptoms:** Build size over 50KB

    **Debug:**

    ```bash theme={null}
    npm run build -- --stats
    npx webpack-bundle-analyzer dist/stats.json
    ```

    **Fixes:**

    * Remove unused imports
    * Use tree-shaking
    * Avoid large libraries
    * Code splitting
  </Card>
</CardGroup>

## Error Messages Reference

Common errors and solutions:

| Error                        | Cause                  | Solution                      |
| ---------------------------- | ---------------------- | ----------------------------- |
| `Extension target not found` | Invalid target in toml | Check extension targets docs  |
| `Field not found on type`    | GraphQL query error    | Verify field exists in schema |
| `Function execution timeout` | Function too slow      | Optimize logic, use Rust      |
| `Permission denied`          | Missing API scopes     | Add required scopes to app    |
| `Network request failed`     | API call failed        | Check network, retry logic    |
| `Component not found`        | Import error           | Verify component name/import  |
| `Type error`                 | TypeScript mismatch    | Add type guards, fix types    |
| `Build failed`               | Compilation error      | Check Fly.io logs, fix syntax |

## Advanced Debugging

<Tabs>
  <Tab title="Remote Debugging">
    Debug deployed extensions:

    1. Open checkout on device
    2. Connect via USB (mobile)
    3. Chrome → `chrome://inspect`
    4. Select device
    5. Inspect and debug
  </Tab>

  <Tab title="Source Maps">
    Debug minified code:

    ```javascript theme={null}
    // vite.config.ts
    export default {
      build: {
        sourcemap: true,  // Enable source maps
      },
    };
    ```

    Source maps allow debugging original TypeScript in production
  </Tab>

  <Tab title="Error Boundaries">
    Catch and log errors:

    ```tsx theme={null}
    import { ErrorBoundary } from '@shopify/ui-extensions-react/checkout';

    function Extension() {
      return (
        <ErrorBoundary
          onError={(error, errorInfo) => {
            console.error('Extension error:', error);
            console.error('Error info:', errorInfo);
            
            // Send to logging service
            logError({
              error: error.message,
              stack: error.stack,
              componentStack: errorInfo.componentStack,
            });
          }}
        >
          <YourComponent />
        </ErrorBoundary>
      );
    }
    ```
  </Tab>
</Tabs>

## Debugging Checklist

Before asking for help:

* [ ] Checked browser console for errors
* [ ] Verified extension is deployed and released
* [ ] Added extension to checkout editor (if UI extension)
* [ ] Tested GraphQL queries in GraphiQL
* [ ] Reviewed Fly.io build/deploy logs
* [ ] Checked function logs (if using functions)
* [ ] Tested locally with `shopify app dev`
* [ ] Verified environment variables are set
* [ ] Confirmed API permissions/scopes
* [ ] Checked for conditional logic hiding components
* [ ] Reviewed MCP validation output
* [ ] Tested with different data/scenarios

## Getting Help

<CardGroup cols={2}>
  <Card title="Synapse Support" icon="headset">
    Contact support:

    * Email: [support@synapsebuilder.org](mailto:support@synapsebuilder.org)
    * Include generation ID
    * Share error messages
    * Provide steps to reproduce
  </Card>

  <Card title="Shopify Community" icon="users">
    Community resources:

    * [Shopify Dev Forums](https://community.shopify.com/c/shopify-developers/ct-p/en-developers)
    * [Discord](https://discord.gg/shopifydevs)
    * [Stack Overflow](https://stackoverflow.com/questions/tagged/shopify)
  </Card>

  <Card title="Documentation" icon="book">
    Official docs:

    * [Shopify Extensions](https://shopify.dev/docs/api/checkout-ui-extensions)
    * [Shopify Functions](https://shopify.dev/docs/api/functions)
    * [GraphQL API](https://shopify.dev/docs/api/admin-graphql)
  </Card>

  <Card title="GitHub Issues" icon="github">
    Report bugs:

    * [Synapse GitHub](https://github.com/l3x3d/synapse/issues)
    * Include error logs
    * Provide minimal reproduction
    * Tag appropriately
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Best Practices" icon="star" href="/advanced/best-practices">
    Learn optimization techniques
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/advanced/troubleshooting">
    Common issues and solutions
  </Card>

  <Card title="Validation" icon="check-circle" href="/concepts/validation">
    Understand MCP validation
  </Card>

  <Card title="Self-Correction" icon="arrows-rotate" href="/concepts/self-correction">
    How errors are auto-fixed
  </Card>
</CardGroup>
