Your Business Name

Advanced CMS Topics

Master advanced CMS concepts including hierarchical content, headless CMS integration, and custom implementations

Take your CMS implementation to the next level with advanced patterns, integrations, and customizations.

Hierarchical Content Patterns

Multi-Level Hierarchies

Create complex content structures with unlimited nesting:

/docs/                          # Level 1: Root Hub
├── /docs/getting-started/      # Level 2: Sub-hub
│   ├── /docs/getting-started/installation/
│   └── /docs/getting-started/quickstart/
├── /docs/api/                  # Level 2: Another sub-hub
│   ├── /docs/api/authentication/
│   ├── /docs/api/endpoints/
│   └── /docs/api/webhooks/
│       ├── /docs/api/webhooks/creating/    # Level 3: Deep nesting
│       └── /docs/api/webhooks/testing/
└── /docs/guides/
    └── /docs/guides/best-practices/

Parent-Child Relationships

Define relationships via folder structure:

# Folder-based hierarchy (NO parent field needed):
src/content/cms/api/index.md          # Hub page
src/content/cms/api/authentication.md  # Child (URL: /cms/api/authentication/)
src/content/cms/api/endpoints.md       # Child (URL: /cms/api/endpoints/)

Frontmatter:
---
title: API Authentication
order: 1 # Optional: Sort order within folder
---

Automatic Archive Pages

Folder index pages (index.md) automatically become archive pages when the folder contains other files. No manual configuration needed!

Content Organization Strategies

Documentation Sites

/docs/
├── overview (landing page)
├── getting-started/ (hub)
├── api-reference/ (hub)
├── guides/ (hub)
└── troubleshooting/ (hub)

Knowledge Base

/kb/
├── categories/
│   ├── billing/
│   ├── technical/
│   └── account/
└── search results page

Multi-Product Site

/products/
├── product-a/
│   ├── features/
│   ├── pricing/
│   └── docs/
└── product-b/
    ├── features/
    ├── pricing/
    └── docs/

Headless CMS Integration

WordPress Integration

The CMS architecture supports seamless WordPress integration:

Step 1: Install Loader

npm install @astro-cms/wordpress-loader

Step 2: Configure

// src/config/cms.js
export default {
  source: 'wordpress',
  wordpress: {
    endpoint: 'https://your-site.com/wp-json/wp/v2',
    cache: true,
    ttl: 3600,
  },
};

Step 3: Update Collection

// src/content/config.ts
import { wordPressLoader } from '@astro-cms/wordpress-loader';

const cms = defineCollection({
  loader: wordPressLoader(cmsConfig.wordpress),
  schema: cmsSchema,
});

Data Mapping

WordPress data automatically maps to CMS schema:

  • Posts → CMS entries
  • Categories → Categories
  • Tags → Tags
  • Custom fields → Frontmatter
  • Featured images → Hero images
  • Hierarchical pages → Parent-child

Other Headless CMS

The same pattern works for:

  • Sanity: sanityLoader()
  • Contentful: contentfulLoader()
  • Strapi: strapiLoader()
  • Any REST API: Custom loader

Hybrid Mode

Run multiple content sources simultaneously:

const cmsLocal = defineCollection({
  loader: glob({ pattern: '**/*.md' }),
});

const cmsWordPress = defineCollection({
  loader: wordPressLoader({ endpoint: '...' }),
});

// Use both!
export const collections = {
  cms: mergeSources([cmsLocal, cmsWordPress]),
};

Use Cases:

  • Migration period (gradual transition)
  • Static + dynamic content mix
  • Backup/fallback strategy
  • Multi-source aggregation

Custom Implementations

Custom Archive Layouts

Create your own archive layout:

---
// src/components/cms/archives/CustomArchive.astro
import { calculateReadingTime } from '../../../lib/cms.js';

export interface Props {
  items: any[];
  // ... other props
}
---

<div class="custom-archive">
  {items.map(item => (
    <!-- Your custom layout -->
  ))}
</div>

Register in routing:

{archiveLayout === 'custom' && <CustomArchive items={paginatedChildren} />}

Custom Single Layouts

Follow the same pattern for single pages:

// src/components/cms/singles/CustomLayout.astro

Custom Components

Create reusable components:

// src/components/ui/CustomComponent.astro

export interface Props { // Define props }

<!-- Component markup -->

Use in markdown:

{/_ custom
prop1: "value"
prop2: "value"
_/}

Advanced Routing

Custom URL Patterns

Override default routing:

// src/pages/custom/[category]/[slug].astro
export async function getStaticPaths() {
  // Custom path generation
}

Redirects

Set up redirects for legacy URLs:

// astro.config.mjs
export default defineConfig({
  redirects: {
    '/old-path': '/new-path',
    '/blog/[...slug]': '/cms/[...slug]',
  },
});

Dynamic Routing Rules

Implement custom routing logic:

// Route based on content type
if (entry.data.contentType === 'product') {
  return `/products/${entry.slug}`;
} else {
  return `/${entry.slug}`;
}

Performance Optimization

Build Optimization

Speed up builds with:

  • Incremental builds
  • Content caching
  • Parallel processing
  • Smart pagination

Runtime Optimization

Enhance performance with:

  • Image lazy loading
  • Component code splitting
  • CSS purging
  • JavaScript tree shaking

CDN Integration

Optimize delivery:

  • Asset preloading
  • Edge caching
  • Geographic distribution
  • Smart invalidation

Content Workflows

Editorial Workflow

Set up content stages:

status: draft | review | published

Version Control

Track content changes:

version: 2
previousVersions:
  - slug: post-v1
    date: 2025-01-15

Scheduled Publishing

Publish content at specific times:

publishDate: 2025-02-01T09:00:00Z
expiryDate: 2025-03-01T00:00:00Z

API & Webhooks

Content API

Expose content via API:

// src/pages/api/content.json.ts
export async function GET() {
  const content = await getCMSContent();
  return new Response(JSON.stringify(content));
}

Webhook Integration

Trigger rebuilds on content changes:

// Netlify webhook
POST https://api.netlify.com/build_hooks/YOUR_HOOK_ID

Preview Mode

Enable draft previews:

if (Astro.url.searchParams.has('preview')) {
  // Show draft content
}

Security Considerations

Content Validation

Validate frontmatter:

schema: z.object({
  title: z.string().max(100),
  description: z.string().max(200),
  // Prevent XSS
  dangerousHtml: z.never(),
});

Access Control

Restrict content access:

if (entry.data.private && !isAuthenticated) {
  return Astro.redirect('/login');
}

Rate Limiting

For API-based sources:

wordpress: {
  rateLimit: {
    requests: 100,
    period: 60000 // 1 minute
  }
}

Monitoring & Analytics

Build Analytics

Track build performance:

  • Build duration
  • Content processed
  • Error rates
  • Cache hit rates

Content Analytics

Monitor content performance:

  • Page views
  • Reading time
  • Engagement metrics
  • Search terms

Error Tracking

Implement error handling:

try {
  const content = await getContent();
} catch (error) {
  console.error('Content load failed:', error);
  // Fallback behavior
}

Migration Strategies

From WordPress

  1. Export WordPress content
  2. Convert to markdown
  3. Map custom fields
  4. Update image paths
  5. Test routing
  6. Deploy

To Headless CMS

  1. Choose CMS platform
  2. Install loader
  3. Update configuration
  4. Test integration
  5. Migrate content
  6. Deploy

Gradual Migration

Use hybrid mode during transition:

  • Keep existing content in markdown
  • Add new content to CMS
  • Migrate old content gradually
  • Maintain both sources until complete

Troubleshooting

Common Issues

Build failures:

  • Check content schema validation
  • Verify parent relationships
  • Review frontmatter syntax

Routing conflicts:

  • Check for duplicate slugs
  • Verify parent paths
  • Review catch-all route priority

Performance issues:

  • Enable content caching
  • Implement pagination
  • Optimize images
  • Review build logs

Best Practices

  1. Content Structure: Plan hierarchy before implementation
  2. Schema Design: Use strict validation
  3. Performance: Monitor build times
  4. Testing: Test all layouts and features
  5. Documentation: Document custom implementations
  6. Version Control: Commit content with code

Resources

Headless CMS Integration

Learn how to integrate headless CMS platforms with your Astro site while maintaining the same content layer API and all existing features.

#headless #cms
CMS Documentation Team Jan 19 • 8 min read