npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@atomic-solutions/wordpress-api-client

v0.1.0

Published

Type-safe WordPress REST API client (platform-agnostic)

Readme

@atomic-solutions/wordpress-utils

Type-safe WordPress REST API client (platform-agnostic)

⚛️ React users: This is a platform-agnostic client. If you're using React or React Native, use @atomic-solutions/react-wordpress instead for React Query hooks and context providers.

Features

  • 🔒 Type-safe: Full TypeScript support with Zod schema validation
  • 🌐 Platform-agnostic: Works in Node.js, browsers, React, React Native
  • 🔐 JWT Authentication: Support for JWT Authentication plugin
  • 📄 Pagination: Automatic handling of WordPress pagination headers
  • 🎯 Error Handling: Built-in error classes with optional error reporter injection

Installation

pnpm add @atomic-solutions/wordpress-utils

For React/React Native projects, install react-wordpress instead:

pnpm add @atomic-solutions/react-wordpress

Peer Dependencies

pnpm add axios zod

Quick Start

React users: See @atomic-solutions/react-wordpress for React Query hooks and provider.

Basic Usage (Platform-agnostic)

import { createClient } from '@atomic-solutions/wordpress-utils';

// Create a client
const client = createClient({
  baseURL: 'https://example.com/wp-json',
  jwtToken: {
    get: () => AsyncStorage.getItem('wp_jwt_token'),
  },
});

// Use the API directly
const posts = await client.posts.list({ per_page: 10 });
const post = await client.posts.get(123);
const categories = await client.categories.list();

API Reference

Client Configuration

interface WordPressConfig {
  baseURL: string;           // WordPress wp-json URL
  jwtToken?: JwtTokenAdapter; // Optional JWT token provider
  queryKeyPrefix?: string[];  // Query key prefix (default: ['wordpress'])
  timeout?: number;           // Request timeout (default: 30000)
  headers?: Record<string, string>; // Custom headers
  errorReporter?: ErrorReporter; // Optional error reporter for tracking (default: console.error)
  onRequest?: (config) => config;   // Request interceptor
  onResponse?: (response) => response; // Response interceptor
  onError?: (error) => void;  // Error handler
}

Client API Methods

The client provides direct access to all WordPress REST API endpoints:


// Posts
const posts = await client.posts.list({ per_page: 10 });
const post = await client.posts.get(123);
const postBySlug = await client.posts.getBySlug('hello-world');

// Categories
const categories = await client.categories.list();
const category = await client.categories.get(5);

// Media
const media = await client.media.get(456);

// Users (requires authentication)
const currentUser = await client.users.me();

// Auth
const token = await client.auth.login({ username: 'user', password: 'pass' });
const isValid = await client.auth.validateToken();

Error Handling

import { WordPressError } from '@atomic-solutions/wordpress-utils';

try {
  await client.posts.get(999);
} catch (error) {
  if (error instanceof WordPressError) {
    console.log(error.userMessage); // User-friendly message
    console.log(error.wpCode);      // WordPress error code
    console.log(error.retryable);   // Whether to retry
    console.log(error.isAuthError); // Authentication error?
    console.log(error.isNotFoundError); // 404 error?
  }
}

Error Reporter Integration

You can integrate with error tracking services like Sentry:

import * as Sentry from '@sentry/react-native';
import { createClient } from '@atomic-solutions/wordpress-utils';

const client = createClient({
  baseURL: 'https://example.com/wp-json',
  errorReporter: {
    report: (error) => Sentry.captureException(error),
  },
});

Integration Testing

The package provides testing utilities for consumer projects to verify WordPress API connectivity in CI/CD pipelines.

Quick Health Check

import { createClient } from '@atomic-solutions/wordpress-utils';
import { runHealthCheck, assertHealthy } from '@atomic-solutions/wordpress-utils/testing';

test('WordPress API is healthy', async () => {
  const client = createClient({ baseURL: process.env.WP_API_URL! });
  const report = await runHealthCheck(client);

  assertHealthy(report); // Throws if any check fails
  expect(report.overall).toBe(true);
}, 30000);

Health Checker Factory

import { createHealthChecker } from '@atomic-solutions/wordpress-utils/testing';

const checkHealth = createHealthChecker({
  baseURL: process.env.WP_API_URL!,
});

test('WordPress API responds', async () => {
  const report = await checkHealth();
  expect(report.summary.failed).toBe(0);
});

Full Test Suite

For comprehensive integration testing, use the pre-built test suite:

// wordpress-api.integration.test.ts
import { createWordPressTestSuite } from '@atomic-solutions/wordpress-utils/testing';

createWordPressTestSuite({
  config: {
    baseURL: process.env.WP_API_URL || 'https://example.com/wp-json',
  },
  timeout: 30000,
  skipMedia: false, // Set true if site has no media
  skipAuth: true,   // Set false if testing JWT auth
});

This runs tests for:

  • Health check (connectivity, schema validation)
  • Posts API (list, single, slug lookup, pagination)
  • Categories API (list, single)
  • Media API (featured images)
  • Auth API (JWT validation, if enabled)

Health Check Report

interface HealthCheckReport {
  baseURL: string;
  timestamp: string;
  overall: boolean;        // true if all checks passed
  results: HealthCheckResult[];
  summary: {
    passed: number;
    failed: number;
    total: number;
  };
}

Tree-shaking Support

Import only what you need for optimal bundle size:

// Import just the client
import { createClient } from '@atomic-solutions/wordpress-utils/client';

// Import just schemas
import { PostSchema, CategorySchema } from '@atomic-solutions/wordpress-utils/schemas';

// Import just HTTP utilities
import { calculatePagination } from '@atomic-solutions/wordpress-utils/http';

// Import just query keys utility
import { createQueryKeys } from '@atomic-solutions/wordpress-utils/utils';

Migration from v1.x

If you were using React hooks from v1.x, follow these steps:

1. Install react-wordpress

pnpm add @atomic-solutions/react-wordpress

2. Update Imports

// Before (v1.x)
import { usePosts, WordPressProvider } from '@atomic-solutions/wordpress-utils';

// After (v2.x)
import { usePosts, WordPressProvider } from '@atomic-solutions/react-wordpress';

3. Update Dependencies

{
  "dependencies": {
    "@atomic-solutions/wordpress-utils": "^2.0.0",
    "@atomic-solutions/react-wordpress": "^1.1.0"
  }
}

That's it! The API is identical - only the package name changed.

What Changed in v2.0.0

  • Removed: React hooks (usePosts, useCategories, etc.) - now in react-wordpress
  • Removed: WordPressProvider and WordPressContext - now in react-wordpress
  • Removed: React and React Query peer dependencies
  • Added: /schemas export path for tree-shaking
  • Added: /utils export path for query keys utility
  • Improved: Test coverage (112+ tests)

If You're NOT Using React

No breaking changes! Just update the version:

{
  "dependencies": {
    "@atomic-solutions/wordpress-utils": "^2.0.0"
  }
}

Architecture

schemas (Zod schemas)
       ↓
wordpress-utils (platform-agnostic API client)
       ↓
react-wordpress (React Query hooks + provider)
       ↓
React / React Native apps

License

MIT