@nitindhakad/strapisdk
v1.0.2
Published
A versatile, type-safe Strapi SDK for interacting with the Strapi API. This package provides a unified interface that supports vanilla JavaScript environments as well as dedicated hooks and context providers for React applications.
Readme
Strapi SDK
A versatile, type-safe Strapi SDK for interacting with the Strapi API. This package provides a unified interface that supports vanilla JavaScript environments as well as dedicated hooks and context providers for React applications.
Features
- Core Client: A standalone
StrapiClientclass for making API requests in any JavaScript/TypeScript environment. - React Support: Fully integrated with React using a custom
StrapiProviderand custom hooks. - Type-safe: Built with TypeScript, providing strong typing out of the box for responses and configuration.
- Flexible Configuration: Supports dynamic configuration of host URLs and Bearer tokens for authentication.
Installation
npm install @nitindhakad/strapisdk
# or
yarn add @nitindhakad/strapisdkVanilla JavaScript/TypeScript Usage
You can use the core StrapiClient class in any environment (Node.js, browser, etc.).
import { StrapiClient, strapiClient } from '@nitindhakad/strapisdk';
// 1. Create a new isolated instance
const myClient = new StrapiClient('https://api.examplestrapi.com', 'your-jwt-token-here');
// 2. Or use and configure the provided singleton instance
strapiClient.setHost('https://api.example.com');
strapiClient.setToken('your-jwt-token');
// Make requests
async function fetchArticles() {
try {
const data = await myClient.request('/api/articles');
console.log(data);
} catch (error) {
console.error('Request failed:', error);
}
}React Usage
The SDK provides built-in tools for React, making it extremely easy to query your Strapi backend while automatically managing loading and error states.
1. Setup the Provider
Wrap your application with the StrapiProvider and pass it your configured StrapiClient instance.
import React from 'react';
import { StrapiClient, StrapiProvider } from '@nitindhakad/strapisdk';
const client = new StrapiClient('https://api.example.com', 'your-jwt-token');
function App() {
return (
<StrapiProvider client={client}>
<YourAppComponents />
</StrapiProvider>
);
}2. Fetch Data using useStrapiQuery
Use the custom useStrapiQuery hook within any child component to easily request data.
import React from 'react';
import { useStrapiQuery } from '@nitindhakad/strapisdk';
interface ArticleData {
data: Array<{ id: number; attributes: { title: string } }>;
}
export function Articles() {
// Pass query parameters seamlessly using the special `params` option!
// Strapi SDK handles nested parameter stringification via `qs` for you.
const { data, loading, error, refetch } = useStrapiQuery<ArticleData>('/api/articles', {
params: {
populate: '*',
filters: { title: { $eq: 'test' } },
sort: ['createdAt:desc'],
}
});
if (loading) return <div>Loading articles...</div>;
if (error) return <div>Error loading articles: {error.message}</div>;
return (
<div>
<h1>Articles</h1>
<button onClick={refetch}>Refresh</button>
<ul>
{data?.data.map((article) => (
<li key={article.id}>{article.attributes.title}</li>
))}
</ul>
</div>
);
}Accessing the Client in React
If you need direct object methods (like setToken dynamically changing upon logging in), you can access the client context via useStrapiClient.
import { useStrapiClient } from '@nitindhakad/strapisdk';
function LoginButton() {
const client = useStrapiClient();
const handleLogin = () => {
// Authenticate and configure the token manually if required
client.setToken('new-user-token');
};
return <button onClick={handleLogin}>Log In</button>;
}API Reference
StrapiClient
Constructor: new StrapiClient(host?: string, token?: string)
setHost(host: string): Update the api host URI.setToken(token: string): Update the optional JWT Bearer token.getHost(): Returns the configured host.getToken(): Returns the configured token.request<T>(endpoint: string, options?: StrapiRequestOptions): Core async method resolving with mapped generic configuration data. The options optionally support aparams: Record<string, any>to automatically URL-stringify complex Strapi queries usingqs. Throws detailed error objects from the backend upon request failures.
useStrapiQuery<T>(endpoint: string, options?: StrapiRequestOptions)
Hook returning:
data: Typed response dataT | nullloading: Boolean state indicating a request is pending.error: Error instance (if any).refetch: Function to forcefully call the endpoint again.
License
ISC
