@headless-blog/sdk
v1.3.1
Published
[](https://www.npmjs.com/package/@headless-blog/sdk) [](https://www.typescriptlang.
Readme
Headless Blog Javascript/Typescript SDK
Welcome to the Headless Blog Javascript/Typescript SDK (@headless-blog/sdk). This SDK provides a high-performance, strictly typed, and completely database-agnostic interface for the Headless Blog API.
Table of Contents
- Introduction
- Installation
- Getting Started
- Error Handling
- Class Structures & Usage Examples
- Schema Validation & TypeScript Definitions
- Local Development & Contributing
- License
Introduction
The @headless-blog/sdk simplifies interacting with the https://api.headless.blog/v1/... suite. It empowers developers to build decoupled applications such as Next.js frontends, mobile applications, or third-party integrations with ease.
By leveraging this SDK, your frontend operates as a pure headless consumer. Complex business logic, multi-tenant security, taxonomy grouping, hybrid semantic vector searches, and data aggregation are securely and efficiently handled by the backend.
Who is this SDK for?
This SDK is fully compatible with both JavaScript and TypeScript projects. It exports both CommonJS and ECMAScript Modules (ESM) and provides full TypeScript definitions (.d.ts), giving you autocomplete and type-safety out of the box regardless of the language you choose.
It is ideal for:
- Server-Side Frameworks: Works perfectly with Next.js (App Router / Server Components), Remix, SvelteKit, Nuxt, Astro, and others.
- Node.js Backends: Easily integrate into Express, NestJS, Fastify, or plain Node.js serverless functions.
- Mobile Applications: Use it in React Native or Expo apps (where secrets are managed securely).
Why Use This SDK?
- Development Speed: Provides pre-built resource classes, methods, and full TypeScript support. Automatically inferring types from Zod schemas means you spend less time writing boilerplate HTTP requests and more time shipping features.
- Security & Multi-Tenancy: Built-in strict token authentication seamlessly isolates data for your specific tenant. The underlying API intrinsically maps requests via your API token without domain-fallback risks.
- Upgradeability & Future-Proofing: The SDK abstracts underlying API logic. If the Headless Blog API scales or alters underlying endpoints, upgrading the SDK ensures your frontend code remains clean and backward compatible.
- Hybrid Caching & Edge Ready: Seamlessly handles Next.js CDN integrations, optimized image paths (e.g., automated WebP compression and scaling), and standardizes robust error handling for rate limits (429) and network failures.
[!SECURITY ADVICE] Important Security Note for Frontend Applications (React/Vue/Vite) The SDK requires you to pass your
apiKeyinto theHeadlessBlogClient. If you use this SDK in a pure client-side application (like a standard React Single Page Application without a server), your API key will be exposed in the browser's source code and network tabs.Therefore, it is highly recommended to only use this SDK on the server-side or in secure backend environments to keep your API key safe.
Installation
Install the package via your preferred package manager:
npm install @headless-blog/sdk
# or
yarn add @headless-blog/sdk
# or
pnpm add @headless-blog/sdkGetting Started
Initialize the client with your API key. The API key must be generated from your Headless Blog SaaS Dashboard.
import { HeadlessBlogClient } from "@headless-blog/sdk";
const client = new HeadlessBlogClient({
apiKey: "your_api_token_here", // Required
// baseUrl: "https://api.headless.blog", // Optional, defaults to official API
// version: "v1" // Optional, defaults to "v1"
});Error Handling
The SDK exposes distinct error classes for granular, intelligent error handling in your application.
import {
BadRequestError,
UnauthorizedError,
ForbiddenError,
RateLimitError,
InternalServerError,
HeadlessBlogApiError
} from "@headless-blog/sdk";
try {
await client.posts.list();
} catch (error) {
if (error instanceof RateLimitError) {
console.log("Too many requests. Please respect the sliding window limits.");
} else if (error instanceof UnauthorizedError) {
console.log("Missing or invalid API key.");
} else if (error instanceof HeadlessBlogApiError) {
console.error(`API Error ${error.statusCode}:`, error.message, error.details);
}
}Class Structures & Usage Examples
The HeadlessBlogClient is divided into intuitive, modular resources that map directly to the API's architecture.
1. Initialization (client.init())
Delivers foundational categories, tags, and multi-dimensional taxonomies in one go. Ideal for building drawer navigation and filter menus on app launch to minimize requests.
const initData = await client.init();
console.log("Categories:", initData.categories);
console.log("Taxonomies:", initData.taxonomies);2. Website Settings (client.settings)
Retrieve general website configuration, such as SEO data, URLs, and AI feature toggles.
const settings = await client.settings.get();
console.log(`Blog Name: ${settings.websiteName}`);
console.log(`Base URL: ${settings.websiteBaseUrl}`);3. Homepage Data (client.home)
Aggregates all homepage sections (hero, recent, featured, favorite) to build a full landing page in a single request, preventing UI waterfall loading.
const homeData = await client.home.get();
console.log("Hero Post:", homeData["section-hero"]?.title);
homeData["section-recent"]?.forEach(post => console.log(post.title));4. Search (client.search())
Executes a hybrid search across published posts. Intelligently chooses between next-generation Semantic Vector Search and Classic Keyword Search based on your dashboard settings.
const results = await client.search("How to bake bread");
results.forEach(post => console.log(post.title));5. Posts (client.posts)
Fetch and filter your blog posts with pagination and taxonomy support.
List Posts
const postsResponse = await client.posts.list({
page: 1,
limit: 12,
category: "recipes",
// tag: "baking",
// taxonomyGroup: "difficulty",
// taxonomyTerm: "easy",
// postType: "default"
});
console.log(`Total Posts: ${postsResponse.pagination.totalItems}`);
console.log(`First Post Title: ${postsResponse.posts[0].title}`);Get Post Details
Fetch comprehensive details, including dynamically injected HTML content (via Edge CDN), authors, SEO metadata, FAQs, and intelligent recommendations.
// Fetch by UUID
const post = await client.posts.getById("uuid-1234");
// Fetch by Slug (Recommended for SEO)
const postBySlug = await client.posts.getBySlug("understanding-headless");
console.log(postBySlug.content);
console.log(postBySlug.recommendations); // Array of related contentPoll New Posts
Useful for notification badges or polling for updates without downloading the entire post list.
// Must be an ISO-8601 string, valid, and newer than July 1st 2026.
const newPosts = await client.posts.getNewPostsSince("2026-07-12T12:00:00Z");
console.log(`New posts since last check: ${newPosts.new_posts_since}`);6. Comments (client.comments)
Manage post comments natively. Supports nested/threaded chronological layouts.
List Comments
const comments = await client.comments.list("post-uuid");
comments.forEach(comment => console.log(comment.content));Create Comment
const newComment = await client.comments.create("post-uuid", {
content: "Great read! Thanks for sharing.",
authorName: "Jane Doe",
authorEmail: "[email protected]",
// parentId: "reply-to-uuid" // Include to thread replies
});7. Taxonomies (client.categories, client.tags, client.taxonomies, client.postTypes, client.contentTypes)
Query precise metadata objects dynamically for building custom landing pages or taxonomy hubs.
Categories & Tags
const allCategories = await client.categories.list();
const specificCategory = await client.categories.getBySlug("technology");
const allTags = await client.tags.list();
const specificTag = await client.tags.getBySlug("typescript");Custom Taxonomies
const allTaxonomies = await client.taxonomies.list();
const difficultyGroup = await client.taxonomies.getGroup("difficulty");
const easyTerm = await client.taxonomies.getTerm("difficulty", "easy");Content & Post Types
const postTypes = await client.postTypes.list();
const contentTypes = await client.contentTypes.list(); // e.g. markdown, rich-text8. Newsletter (client.newsletter)
Register a subscriber to your tenant's mailing list.
await client.newsletter.subscribe({
email: "[email protected]",
name: "John Smith" // Optional
});
console.log("Subscribed successfully!");9. Sitemap (client.sitemap)
Dynamically generate standard sitemap data for decoupled frontends, ensuring search engines always index your latest content.
const sitemap = await client.sitemap.list();
sitemap.forEach(item => {
console.log(`${item.url} (Modified: ${item.lastModified}, Priority: ${item.priority})`);
});Schema Validation & TypeScript Definitions
Under the hood, all payloads and responses strictly map to Zod schemas (e.g., PostSnippetSchema, SettingsSchema). The SDK automatically infers types from these schemas ensuring both runtime and compile-time safety.
A number of convenient aliases are provided and exported out of the box for typing your frontend components:
BlogPostBlogPostListResponseBlogCategoryBlogTagBlogTaxonomyBlogSettingsBlogPostTypeBlogContentType
import { BlogPost } from "@headless-blog/sdk";
const myComponent = (post: BlogPost) => {
return `<h1>${post.title}</h1>`;
}Local Development & Contributing
We welcome contributions! If you're looking to build upon, extend, or fix bugs within the SDK itself, follow these steps to set up your local development environment.
1. Setup Environment
Clone the repository and install the required dependencies (using npm, matching the existing package-lock.json).
git clone <repository-url>
cd npm-headless-blog-sdk
npm install2. Development Commands
The SDK uses tsup for rapid, zero-config bundling and vitest for testing.
npm run dev: Startstsupin watch mode. It will instantly rebuild your changes into thedist/folder as you edit files insrc/. Ideal for local development.npm run build: Creates a production-ready build. Outputs CommonJS, ESM, and.d.tsdefinitions into thedist/folder.npm run test: Runs the unit test suite usingvitest.npm run typecheck: Runstsc --noEmitto validate TypeScript typings across the project without compiling.
3. Guidelines for Extending the SDK
- Updating Data Models: If the upstream Headless API adds new fields, you must update the corresponding Zod schemas inside
src/schema.ts. The TypeScript interfaces will automatically infer from these schemas. - Adding Endpoints: Add new API routes by creating or updating resource classes in
src/resources/. - Client Registration: Remember to instantiate any newly created resources inside the
HeadlessBlogClientconstructor located insrc/index.ts.
License
ISC
