Docs
Client
Documentation

Client

Complete reference for the AutoBlogWriter client — configuration, methods, and usage.

Client

The createAutoBlogWriterClient function creates a client instance for fetching published blog posts from the AutoBlogWriter API.

Creating a Client

import { createAutoBlogWriterClient } from "@autoblogwriter/sdk";
 
const client = createAutoBlogWriterClient({
  apiUrl: "https://api.autoblogwriter.app",
  apiKey: process.env.AUTOBLOGWRITER_API_KEY!,
  workspaceSlug: process.env.AUTOBLOGWRITER_WORKSPACE_SLUG!,
});

Configuration

The AutoBlogWriterClientConfig interface accepts these options:

OptionTypeRequiredDefaultDescription
apiUrlstringYesAutoBlogWriter API base URL
apiKeystringYesYour workspace API key
workspaceSlugstring*Workspace slug for public endpoints
workspaceIdstring*Workspace ID (alternative to slug)
authMode"bearer" | "x-api-key"No"bearer"Authentication header format
fetchtypeof fetchNoglobalThis.fetchCustom fetch implementation
headersRecord<string, string>No{}Additional headers for every request
timeoutMsnumberNo10000Request timeout in milliseconds

* You must provide either workspaceSlug or workspaceId. The workspaceSlug is required for fetching posts via the public API.

Configuration Validation

The client validates configuration at creation time and throws a ConfigError if:

  • apiKey is missing or empty
  • Neither workspaceId nor workspaceSlug is provided
  • apiUrl is missing
import { createAutoBlogWriterClient, ConfigError } from "@autoblogwriter/sdk";
 
try {
  const client = createAutoBlogWriterClient({
    apiUrl: "https://api.autoblogwriter.app",
    apiKey: "", // Will throw
    workspaceSlug: "my-blog",
  });
} catch (error) {
  if (error instanceof ConfigError) {
    console.error("Invalid config:", error.message);
  }
}

Methods

getPosts(params?)

Fetches a paginated list of published blog posts.

const { posts, nextCursor } = await client.getPosts({
  limit: 10,
  cursor: undefined,
});

Parameters:

ParamTypeDefaultDescription
limitnumber20Number of posts per page
cursorstringPage cursor from a previous nextCursor
cacheRequestCacheFetch API cache mode
next{ revalidate?, tags? }Next.js cache options

Returns: PostsResponse

interface PostsResponse {
  posts: BlogPost[];
  nextCursor?: string; // Pass to next call for pagination
}

Example: Paginated Fetching

// First page
const page1 = await client.getPosts({ limit: 10 });
console.log(page1.posts); // First 10 posts
 
// Next page (if available)
if (page1.nextCursor) {
  const page2 = await client.getPosts({ limit: 10, cursor: page1.nextCursor });
  console.log(page2.posts); // Next 10 posts
}

Example: With Next.js Cache Tags

const { posts } = await client.getPosts({
  limit: 20,
  next: { tags: ["blog-posts"] },
});

getPostBySlug(slug, options?)

Fetches a single published post by its URL slug. Returns null if not found.

const post = await client.getPostBySlug("my-first-post");
 
if (post) {
  console.log(post.title);
  console.log(post.content); // Markdown string
}

Parameters:

ParamTypeDescription
slugstringThe post's URL slug (required)
options.cacheRequestCacheFetch API cache mode
options.next{ revalidate?, tags? }Next.js cache options

Returns: BlogPost | null

  • Returns the full BlogPost object if found.
  • Returns null if the post doesn't exist or is not published.
  • Throws ApiError for other HTTP errors (5xx, network failures).

Example: With Error Handling

import { ApiError } from "@autoblogwriter/sdk";
 
try {
  const post = await client.getPostBySlug("my-post");
  if (!post) {
    // Post not found — show 404 page
  }
} catch (error) {
  if (error instanceof ApiError) {
    console.error(`API error ${error.status}: ${error.message}`);
  }
}

getSitemapEntries()

Fetches all published posts for sitemap generation. Automatically paginates through all pages.

const entries = await client.getSitemapEntries();
// [{ slug: "first-post", updatedAt: "2025-01-15T..." }, ...]

Returns: Array<{ slug: string; updatedAt: string }>

This method fetches all posts in batches of 100 and returns a flat array of slugs and update timestamps — ideal for passing to buildSitemap().

BlogPost Type

interface BlogPost {
  id: string;
  title: string;
  slug: string;
  excerpt?: string;
  content: string;                    // Markdown
  status: "DRAFT" | "PUBLISHED" | "HIDDEN";
  seo?: {
    title?: string;
    description?: string;
    keywords?: string[];
  };
  metadata?: {
    canonicalUrl?: string;
    ogImageUrl?: string;
    readingTimeMinutes?: number;
    wordCount?: number;
  };
  publishedAt?: string;               // ISO 8601
  updatedAt: string;                  // ISO 8601
}

Debug Mode

Enable debug logging by setting the AUTOBLOGWRITER_DEBUG environment variable:

AUTOBLOGWRITER_DEBUG=true

This logs request/response details to the console:

[autoblogwriter] response { method: 'GET', url: '...', status: 200, durationMs: 142 }

Custom Fetch

You can provide a custom fetch implementation for testing or environments without native fetch:

import { createAutoBlogWriterClient } from "@autoblogwriter/sdk";
 
const client = createAutoBlogWriterClient({
  apiUrl: "https://api.autoblogwriter.app",
  apiKey: "test",
  workspaceSlug: "demo",
  fetch: myCustomFetch,
});

Next Steps