JavaScript Examples

AI agents & LLMs: read this documentation as Markdown at nextblog.ai/docs/javascript-examples.md or browse the per-section Markdown index.
Learn how to integrate NextBlog content into your websites using vanilla JavaScript.

Fetch All Blog Posts

// Fetch all blog posts for a project
async function fetchBlogPosts(projectId, apiKey) {
  try {
    const response = await fetch(`/api/blog/${projectId}`, {
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    });
    if (!response.ok) {
      throw new Error('Failed to fetch blog posts');
    }
    const data = await response.json();
    return data.blogs;
  } catch (error) {
    console.error('Error:', error);
    return [];
  }
}

// Display blog posts
function displayBlogPosts(blogs) {
  const container = document.getElementById('blog-posts');
  container.innerHTML = blogs.map(blog => `
    <article class="blog-post">
      <h2>${blog.title}</h2>
      <p>${blog.description}</p>
      <a href="/blog/${blog.slug}">Read more</a>
    </article>
  `).join('');
}

Fetch Single Blog Post

// Fetch a single blog post
async function fetchBlogPost(projectId, slug, apiKey) {
  try {
    const response = await fetch(`/api/blog/${projectId}/${slug}`, {
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    });
    if (!response.ok) {
      throw new Error('Failed to fetch blog post');
    }
    const data = await response.json();
    return data.blog;
  } catch (error) {
    console.error('Error:', error);
    return null;
  }
}

// Display single blog post with markdown
function displayBlogPost(blog) {
  const container = document.getElementById('blog-content');
  container.innerHTML = `
    <article class="blog-post">
      <h1>${blog.title}</h1>
      <div class="blog-meta">
        <time>${new Date(blog.created_at).toLocaleDateString()}</time>
      </div>
      <div class="blog-content">
        ${marked(blog.markdown)} <!-- Using marked.js for markdown rendering -->
      </div>
    </article>
  `;
}