# Integration Patterns

> Source: https://agilitycms.com/docs/training-guide/architect-integrations

This guide covers integration patterns for Agility CMS, including frontend frameworks, third-party services, and custom integrations.

## Frontend Framework Integration

### Next.js Integration

**SDK**: `@agility/nextjs`

**Features:**
- React Server Components support
- Automatic caching
- Preview mode support
- TypeScript support

**Pattern:**
```typescript
import { getContentItem } from "@/lib/cms/getContentItem"

const { fields } = await getContentItem<IPost>({
  contentID: 204,
  languageCode: "en-us"
})
```

### Other Framework Integrations

**Gatsby:**
- Static site generation
- GraphQL support
- Plugin-based architecture

**Nuxt:**
- Vue.js support
- Server-side rendering
- Module-based integration

**Eleventy:**
- Static site generation
- Template-based rendering
- Simple integration

## API Integration Patterns

### RESTful API

**Pattern:**
- Standard HTTP methods
- JSON responses
- Query parameters for filtering

**Example:**
```bash
GET /{instance-guid}/fetch/{locale}/list/posts?take=10&skip=0
```

### GraphQL API

**Pattern:**
- GraphQL queries
- Type-safe queries
- Flexible data fetching

**Example:**
```graphql
query {
  contentList(referenceName: "posts") {
    items {
      contentID
      fields {
        heading
        slug
      }
    }
  }
}
```

### SDK Integration

**Pattern:**
- TypeScript SDK for type safety
- Automatic caching
- Preview mode support

**Example:**
```typescript
const sdk = await getAgilitySDK()
const items = await sdk.getContentList({ referenceName: "posts" })
```

## Third-Party Integrations

### Analytics Integration

**PostHog:**
- Feature flags
- Analytics tracking
- A/B testing

**Google Analytics:**
- Page view tracking
- Event tracking
- Custom dimensions

### Search Integration

**Algolia:**
- Full-text search
- Faceted search
- Search analytics

**Custom Search:**
- Build custom search
- Integrate with AI services
- Custom ranking

### AI Integration

**Azure OpenAI:**
- AI-powered search
- Content generation
- Chat interfaces

**Custom AI:**
- Integrate custom AI services
- Build AI features
- Custom prompts

## Webhook Integration

### Webhook Pattern

**Setup:**
1. Configure the webhook in Agility CMS (**Settings → Webhooks**)
2. Create your webhook endpoint
3. Enable **secure delivery** and verify the signature on every request
4. Process the event idempotently and return a 2xx quickly

**Event categories:**
- **Content Publish Events** — content or a page is published or unpublished
- **Content Save Events** — content or a page is saved or deleted
- **Content Workflow Events** — content is requested for approval, approved, or declined

**Delivery guarantees:**
- Success is any **2xx**; redirects count as failures and are not followed
- The delivery timeout is **30 seconds** — acknowledge fast, work in the background
- Delivery is **at-least-once**; use the `webhook-id` header as an idempotency key
- Retries are opt-in per webhook (1–8 attempts, fast / standard / slow backoff)

> ⚠️ **There is no webhook "security key."** `AGILITY_SECURITY_KEY` is the **preview** key and is never sent with a webhook, and custom headers cannot be configured. Secure delivery signs each request instead — Agility implements the open [Standard Webhooks](https://www.standardwebhooks.com) spec, so you verify with an off-the-shelf library. See [Verifying Signed Webhooks](/docs/developers/verifying-signed-webhooks).

### Webhook Handler

```typescript
import { Webhook } from 'standard-webhooks'

export async function POST(request: Request) {
  // Read the RAW body - re-serializing the JSON breaks verification
  const raw = await request.text()

  const wh = new Webhook(process.env.AGILITY_WEBHOOK_SIGNING_SECRET!)
  try {
    wh.verify(raw, {
      "webhook-id": request.headers.get("webhook-id")!,
      "webhook-timestamp": request.headers.get("webhook-timestamp")!,
      "webhook-signature": request.headers.get("webhook-signature")!,
    })
  } catch {
    return Response.json({ error: "Invalid signature" }, { status: 401 })
  }

  const event = JSON.parse(raw)
  // Process event (idempotently - key off the webhook-id header)
  // Revalidate cache
  return Response.json({ ok: true })
}
```

> Use each webhook's **History** view in Settings → Webhooks to see delivery attempts, response codes and errors when debugging an integration.

## Custom Integration Patterns

### Custom API Routes

Create custom API routes for:
- Custom business logic
- Third-party integrations
- Data transformations
- Custom workflows

### Middleware Integration

Use middleware for:
- Preview mode handling
- Redirect management
- Locale routing
- Authentication

## Best Practices

1. **Use SDKs**: Prefer SDKs over direct API calls
2. **Type Safety**: Use TypeScript for type safety
3. **Error Handling**: Handle errors gracefully
4. **Caching**: Leverage built-in caching
5. **Security**: Secure all integrations
6. **Monitoring**: Monitor integration health
7. **Documentation**: Document integration patterns
