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

# Admin Extensions

> Build custom admin panel extensions with Synapse

## Overview

Admin extensions add custom functionality to the Shopify admin panel. Create order action buttons, product bulk actions, custom dashboards, and workflow automations.

## Extension Types

<CardGroup cols={2}>
  <Card title="Product Actions" icon="box">
    Add bulk actions to product lists

    * Tag products automatically
    * Generate SEO descriptions
    * Update pricing
    * Sync to external systems
  </Card>

  <Card title="Order Actions" icon="file-invoice">
    Add actions to order details

    * Send custom notifications
    * Create shipment labels
    * Apply custom fulfillment
    * Export to warehouse
  </Card>

  <Card title="Customer Actions" icon="users">
    Enhance customer management

    * Segment customers
    * Bulk email campaigns
    * Loyalty program enrollment
    * Custom tagging
  </Card>

  <Card title="Custom Pages" icon="window">
    Add new pages to admin

    * Analytics dashboards
    * Inventory management
    * Custom reports
    * Integration settings
  </Card>
</CardGroup>

## Admin Extension Targets

Available extension points:

| Target                                 | Location              | Use Case                   |
| -------------------------------------- | --------------------- | -------------------------- |
| `admin.product-details.action.render`  | Product page actions  | Single product operations  |
| `admin.product-index.action.render`    | Product list actions  | Bulk product operations    |
| `admin.order-details.action.render`    | Order page actions    | Single order operations    |
| `admin.order-index.action.render`      | Order list actions    | Bulk order operations      |
| `admin.customer-details.action.render` | Customer page actions | Single customer operations |
| `admin.customer-index.action.render`   | Customer list actions | Bulk customer operations   |

## Example: Product SEO Generator

Generate an admin extension that creates SEO-optimized descriptions:

<Steps>
  <Step title="Describe Your Extension">
    ```
    Create an admin extension that appears on product pages. 
    Add a button that uses AI to generate SEO-optimized product 
    descriptions based on the product title and vendor. Update 
    the product description field automatically.
    ```
  </Step>

  <Step title="Review Generated Code">
    Synapse creates:

    * Action button in product details
    * GraphQL queries for product data
    * Mutation to update description
    * Loading/success states
    * Error handling
  </Step>

  <Step title="Deploy & Test">
    * Automatic validation and deployment
    * Available immediately in admin
    * Test on sample products
  </Step>

  <Step title="Use in Admin">
    1. Go to Products → \[Any Product]
    2. Click "More actions"
    3. Select your custom action
    4. Watch it process and update
  </Step>
</Steps>

## Generated Extension Structure

```
extensions/seo-generator/
├── src/
│   ├── ActionExtension.tsx    # Main component
│   ├── api.ts                # API calls
│   └── run.graphql           # GraphQL
├── shopify.extension.toml    # Config
└── package.json
```

### Main Component

```tsx theme={null}
import {
  reactExtension,
  useApi,
  Button,
  Text,
} from '@shopify/ui-extensions-react/admin';

export default reactExtension(
  'admin.product-details.action.render',
  () => <Extension />
);

function Extension() {
  const { data } = useApi<'admin.product-details.action.render'>();
  const [loading, setLoading] = useState(false);
  
  const generateSEO = async () => {
    setLoading(true);
    
    // Call your API
    const description = await fetch('/api/generate-seo', {
      method: 'POST',
      body: JSON.stringify({
        title: data.product.title,
        vendor: data.product.vendor
      })
    }).then(r => r.json());
    
    // Update product
    await updateProductDescription(data.product.id, description);
    
    setLoading(false);
  };
  
  return (
    <Button onPress={generateSEO} loading={loading}>
      Generate SEO Description
    </Button>
  );
}
```

## Common Admin Patterns

<Tabs>
  <Tab title="Bulk Product Tagger">
    **Use Case:** Auto-tag products based on attributes

    **Target:** `admin.product-index.action.render`

    **Features:**

    * Select multiple products
    * Analyze titles/descriptions
    * Apply relevant tags
    * Show progress

    **Prompt Example:**

    ```
    "Create a bulk action for products that automatically adds 
    relevant tags based on product titles. For example, products 
    with 'cotton' get 'natural-fiber' tag. Show progress bar."
    ```
  </Tab>

  <Tab title="Order Export">
    **Use Case:** Export orders to external system

    **Target:** `admin.order-index.action.render`

    **Features:**

    * Select orders to export
    * Format for warehouse system
    * Send via API
    * Mark as exported

    **Prompt Example:**

    ```
    "Add a bulk action to export selected orders to our warehouse 
    management system. Send order number, items, quantities, and 
    shipping address. Add 'exported' tag to orders."
    ```
  </Tab>

  <Tab title="Customer Segmentation">
    **Use Case:** Segment customers for marketing

    **Target:** `admin.customer-index.action.render`

    **Features:**

    * Bulk select customers
    * Apply segment tags
    * Add to email lists
    * Track segmentation

    **Prompt Example:**

    ```
    "Create a bulk action that tags customers as 'high-value' if 
    their lifetime spend is over $500. Also add them to the VIP 
    email list. Show confirmation when complete."
    ```
  </Tab>

  <Tab title="Inventory Alert">
    **Use Case:** Alert on low stock

    **Target:** `admin.product-details.action.render`

    **Features:**

    * Check stock levels
    * Send notifications
    * Create purchase orders
    * Update reorder points

    **Prompt Example:**

    ```
    "Add an action to product pages that checks if inventory is 
    below reorder point. If so, send email to purchasing team 
    with product details and suggested order quantity."
    ```
  </Tab>
</Tabs>

## UI Components for Admin

<AccordionGroup>
  <Accordion title="Actions" icon="hand-pointer">
    * `<Button>` - Primary/secondary actions
    * `<ActionList>` - Multiple action options
    * `<Modal>` - Confirmation dialogs
    * `<Toast>` - Success/error messages
  </Accordion>

  <Accordion title="Forms" icon="input-text">
    * `<TextField>` - Text inputs
    * `<Select>` - Dropdowns
    * `<Checkbox>` - Boolean options
    * `<Form>` - Form container
  </Accordion>

  <Accordion title="Feedback" icon="spinner">
    * `<Spinner>` - Loading indicator
    * `<ProgressBar>` - Progress tracking
    * `<Banner>` - Info/warnings
    * `<Badge>` - Status indicators
  </Accordion>

  <Accordion title="Data Hooks" icon="hook">
    * `useApi()` - Access admin data
    * `useData()` - Current resource
    * `useSessionToken()` - Authentication
    * `useLocale()` - Internationalization
  </Accordion>
</AccordionGroup>

## Making API Calls

Admin extensions can call external APIs and Shopify Admin API:

<Tabs>
  <Tab title="External API">
    Call your own backend:

    ```tsx theme={null}
    const { data } = useApi();
    const sessionToken = await getSessionToken();

    const response = await fetch('https://your-api.com/endpoint', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${sessionToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        productId: data.product.id,
        action: 'generate-seo'
      })
    });

    const result = await response.json();
    ```
  </Tab>

  <Tab title="Admin API">
    Use GraphQL to update Shopify data:

    ```tsx theme={null}
    const PRODUCT_UPDATE = `
      mutation productUpdate($input: ProductInput!) {
        productUpdate(input: $input) {
          product {
            id
            descriptionHtml
          }
          userErrors {
            field
            message
          }
        }
      }
    `;

    const result = await adminApiClient.request(PRODUCT_UPDATE, {
      variables: {
        input: {
          id: data.product.id,
          descriptionHtml: newDescription
        }
      }
    });
    ```
  </Tab>

  <Tab title="Bulk Operations">
    Process multiple items:

    ```tsx theme={null}
    const { selectedResources } = useApi();

    // Process in batches
    const batchSize = 10;
    for (let i = 0; i < selectedResources.length; i += batchSize) {
      const batch = selectedResources.slice(i, i + batchSize);
      
      await Promise.all(
        batch.map(resource => processResource(resource))
      );
      
      // Update progress
      setProgress((i + batchSize) / selectedResources.length);
    }
    ```
  </Tab>
</Tabs>

## Best Practices

### Performance

* **Batch Operations**: Process bulk actions in chunks
* **Background Jobs**: Use webhooks for long operations
* **Caching**: Cache API responses where appropriate
* **Rate Limits**: Respect Shopify API rate limits

### UX Guidelines

* **Clear Feedback**: Show progress and results
* **Confirmation**: Ask before destructive actions
* **Error Handling**: Graceful failure with retry options
* **Undo**: Provide undo for reversible actions

### Security

* **Authentication**: Always verify session tokens
* **Validation**: Validate all inputs
* **Permissions**: Check user permissions
* **Audit Logs**: Log all actions for compliance

## Advanced Features

<CardGroup cols={2}>
  <Card title="Webhooks" icon="webhook">
    Trigger on Shopify events:

    ```tsx theme={null}
    // Handle order creation
    app.post('/webhooks/orders/create', async (req, res) => {
      const order = req.body;
      
      // Custom processing
      await processNewOrder(order);
      
      res.status(200).send();
    });
    ```
  </Card>

  <Card title="Background Jobs" icon="clock">
    Long-running tasks:

    ```tsx theme={null}
    // Queue job
    await queue.add('process-bulk', {
      productIds: selectedIds,
      action: 'update-seo'
    });

    // Show progress
    return <Text>Processing in background...</Text>;
    ```
  </Card>

  <Card title="Custom Settings" icon="gear">
    Store app configuration:

    ```tsx theme={null}
    const settings = await getAppSettings();

    const apiKey = settings.external_api_key;
    const threshold = settings.low_stock_threshold;
    ```
  </Card>

  <Card title="Analytics" icon="chart-line">
    Track usage:

    ```tsx theme={null}
    await analytics.track('extension_used', {
      extension: 'seo-generator',
      resource: 'product',
      count: selectedIds.length
    });
    ```
  </Card>
</CardGroup>

## Example Prompts

<AccordionGroup>
  <Accordion title="Product Price Optimizer">
    ```
    Create an admin extension for product pages that analyzes 
    competitor prices and suggests optimal pricing. Show current 
    price, suggested price, and expected revenue impact. Add 
    button to apply suggested price with confirmation modal.
    ```
  </Accordion>

  <Accordion title="Order Fraud Check">
    ```
    Add an action to order details that checks for fraud signals 
    like mismatched billing/shipping addresses, high order value, 
    new customer. Display risk score and recommended action 
    (approve/review/cancel). Add note to order.
    ```
  </Accordion>

  <Accordion title="Inventory Sync">
    ```
    Create bulk action for products that syncs inventory levels 
    with our warehouse API. Send SKU and location, receive 
    available quantity, update Shopify inventory. Show progress 
    bar and sync status for each product.
    ```
  </Accordion>

  <Accordion title="Customer Lifetime Value">
    ```
    Add action to customer pages that calculates lifetime value, 
    average order value, and predicts next purchase date. Display 
    in a nice summary card with charts. Tag customer based on 
    value tier (bronze/silver/gold).
    ```
  </Accordion>
</AccordionGroup>

## Testing Admin Extensions

<Steps>
  <Step title="Deploy to Dev Store">
    Extensions automatically deploy to your development store's admin
  </Step>

  <Step title="Access Extension">
    Navigate to the admin page where your extension appears
  </Step>

  <Step title="Test Different Scenarios">
    * Single item actions
    * Bulk actions with multiple items
    * Error conditions
    * Edge cases
  </Step>

  <Step title="Verify Results">
    * Check data updates correctly
    * Confirm error handling works
    * Test loading states
    * Validate permissions
  </Step>
</Steps>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Extension Not Appearing">
    **Causes:**

    * Wrong extension target
    * Not installed in dev store
    * Permissions issue

    **Solutions:**

    * Verify target in shopify.extension.toml
    * Check Apps in admin settings
    * Review app scopes
    * Clear browser cache
  </Accordion>

  <Accordion title="API Calls Failing">
    **Causes:**

    * Session token expired
    * Missing permissions
    * Rate limit exceeded

    **Solutions:**

    * Refresh session token
    * Add required scopes to app
    * Implement rate limit handling
    * Check API error responses
  </Accordion>

  <Accordion title="Bulk Actions Slow">
    **Causes:**

    * Processing too many items at once
    * Not batching requests
    * Blocking UI thread

    **Solutions:**

    * Process in smaller batches
    * Use Promise.all for parallel requests
    * Show progress indicator
    * Consider background jobs
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Checkout Extensions" icon="shopping-cart" href="/guides/checkout-extensions">
    Build customer-facing checkout UI
  </Card>

  <Card title="Functions" icon="function" href="/essentials/functions">
    Add backend logic with Functions
  </Card>

  <Card title="Extension Standards" icon="shield-check" href="/guides/extension-standards">
    Quality guidelines and best practices
  </Card>

  <Card title="Debugging" icon="bug" href="/advanced/debugging">
    Debug and troubleshoot extensions
  </Card>
</CardGroup>
