Integrating with Your Website

This guide will show you how to integrate AiSEOTrack content with your existing website. You can use our API and JavaScript SDK to fetch and display content seamlessly.

Note: This integration guide assumes you have already set up schemas and created content in AiSEOTrack.

Step 1: Include the SDK

Add the AiSEOTrack SDK to your website by including the following script in your HTML head or before the closing body tag:

<script src="https://aiseotrack.com/js/content-api.js"></script>

Step 2: Initialize the Client

Create a new instance of the ContentClient with your AiSEOTrack installation URL:

const contentClient = new ContentClient({
    projectUrl: 'https://aiseotrack.com',
    apiVersion: 'v1'
});

Step 3: Fetch and Display Content

Example 1: Display a Blog Post

<!-- HTML structure -->
<div id="blog-post">Loading...</div>

<script>
    // Fetch a specific blog post by ID
    contentClient.getDocument(123)
        .then(post => {
            // Create HTML for the blog post
            const html = `
                

{{ post.data.title }}

By {{ post.data.author }} {{ new Date(post.data.publishedAt).toLocaleDateString() }}
{{ post.data.content }}
`; // Update the DOM document.getElementById('blog-post').innerHTML = html; }) .catch(error => { console.error('Error fetching blog post:', error); document.getElementById('blog-post').innerHTML = 'Failed to load blog post'; }); </script>

Example 2: List Multiple Posts

<!-- HTML structure -->
<div id="blog-list">Loading posts...</div>

<script>
    // Fetch all published blog posts
    contentClient.getDocuments({ 
        schema: 'blog',
        published: true,
        limit: 10
    })
    .then(result => {
        const posts = result.data;
        
        if (posts.length === 0) {
            document.getElementById('blog-list').innerHTML = 'No posts found';
            return;
        }
        
        // Create HTML for each post
        const postsHtml = posts.map(post => `
            

{{ post.data.title }}

{{ post.data.excerpt || post.data.content.substring(0, 150) + '...' }}
{{ new Date(post.data.publishedAt).toLocaleDateString() }}
`).join(''); // Update the DOM document.getElementById('blog-list').innerHTML = postsHtml; }) .catch(error => { console.error('Error fetching blog posts:', error); document.getElementById('blog-list').innerHTML = 'Failed to load blog posts'; }); </script>

Example 3: Navigation Menu from Content

<!-- HTML structure -->
<nav id="main-nav">Loading menu...</nav>

<script>
    // Fetch navigation items
    contentClient.getDocuments({ 
        schema: 'navigation',
        published: true
    })
    .then(result => {
        // Assuming a single navigation document with items array
        const navigation = result.data[0];
        
        if (!navigation || !navigation.data.items) {
            return;
        }
        
        // Create menu HTML
        const menuHtml = `
            
    {{ navigation.data.items.map(item => \`
  • \${item.label}
  • \`).join('') }}
`; // Update the DOM document.getElementById('main-nav').innerHTML = menuHtml; }) .catch(error => { console.error('Error fetching navigation:', error); }); </script>

Step 4: Add Dynamic Content to Existing Pages

For a more integrated approach, you can enhance your existing pages with dynamic content from AiSEOTrack:

<!-- In your existing HTML page -->
<div class="page-content">
    <h1>Welcome to Our Website</h1>
    
    <p>This is static content from your existing website.</p>
    
    <!-- Dynamic content section -->
    <div id="featured-products" class="products-grid">Loading products...</div>
</div>

<script>
    // Initialize the client (once per page)
    const contentClient = new ContentClient({
        projectUrl: 'https://aiseotrack.com',
        apiVersion: 'v1'
    });
    
    // Fetch featured products
    contentClient.query({
        schema: 'product',
        filter: {
            published: true,
            'data.featured': true
        },
        sort: { 'data.price': 'asc' },
        limit: 4
    })
    .then(result => {
        const products = result.data;
        
        // Create HTML for products
        const productsHtml = products.map(product => `
            
{{ product.data.name }}

{{ product.data.name }}

${{ product.data.price.toFixed(2) }}

`).join(''); // Update the DOM document.getElementById('featured-products').innerHTML = productsHtml; // Add event listeners to buttons document.querySelectorAll('.add-to-cart').forEach(button => { button.addEventListener('click', function() { const productId = this.getAttribute('data-product-id'); // Your existing cart functionality console.log('Adding product', productId, 'to cart'); }); }); }) .catch(error => { console.error('Error fetching products:', error); document.getElementById('featured-products').innerHTML = 'Failed to load products'; }); </script>

Step 5: Handle Content Updates

When you update content in AiSEOTrack, your website will automatically show the latest content on the next page load. For more dynamic updates, you can implement polling or websockets.

Implementing a Simple Cache

// Simple caching helper
const contentCache = {
    data: {},
    maxAge: 60 * 1000, // 1 minute cache
    
    async get(key, fetchFn) {
        const cached = this.data[key];
        
        // Return cached data if it's still fresh
        if (cached && (Date.now() - cached.timestamp) < this.maxAge) {
            return cached.data;
        }
        
        // Fetch new data
        try {
            const data = await fetchFn();
            
            // Save to cache
            this.data[key] = {
                data,
                timestamp: Date.now()
            };
            
            return data;
        } catch (error) {
            // If we have stale data, return it on error
            if (cached) {
                console.warn('Returning stale data due to fetch error');
                return cached.data;
            }
            throw error;
        }
    }
};

// Usage example
async function loadHomepageContent() {
    const homeData = await contentCache.get('homepage', () => 
        contentClient.getDocument(1) // Homepage content
    );
    
    document.getElementById('hero-title').textContent = homeData.data.heroTitle;
    document.getElementById('hero-subtitle').textContent = homeData.data.heroSubtitle;
}

Advanced Integration

Using AiSEOTrack with a React Application

// ContentProvider.js
import React, { createContext, useContext, useState, useEffect } from 'react';

// Create context
const ContentContext = createContext();

// Content provider component
export function ContentProvider({ children }) {
    const [client, setClient] = useState(null);
    const [loading, setLoading] = useState(true);
    
    useEffect(() => {
        // Initialize client
        const contentClient = new ContentClient({
            projectUrl: 'https://aiseotrack.com',
            apiVersion: 'v1'
        });
        
        setClient(contentClient);
        setLoading(false);
    }, []);
    
    return (
        
            {{ children }}
        
    );
}

// Hook for accessing the content client
export function useContent() {
    const context = useContext(ContentContext);
    
    if (!context) {
        throw new Error('useContent must be used within a ContentProvider');
    }
    
    return context;
}

// Example Blog component
function BlogPost({ postId }) {
    const { client, loading } = useContent();
    const [post, setPost] = useState(null);
    const [error, setError] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    
    useEffect(() => {
        if (loading || !client) return;
        
        async function fetchPost() {
            try {
                const data = await client.getDocument(postId);
                setPost(data);
            } catch (err) {
                setError(err.message);
            } finally {
                setIsLoading(false);
            }
        }
        
        fetchPost();
    }, [client, loading, postId]);
    
    if (loading || isLoading) return 
Loading...
; if (error) return
Error: {{ error }}
; if (!post) return
Post not found
; return (

{{ post.data.title }}

By {{ post.data.author }}
); }

Need Help?

If you have questions about integrating AiSEOTrack with your website, feel free to reach out to our support team or check out the API Documentation.