All products

StrapiOfficial

Headless BitaKit plugin for Strapi 5: content, Users & Permissions authentication, uploads and a shared query cache.

bitakit · Plugin for every BitaKit app

Type
Package
Needs a build
Kind
Plugin
BitaKit
Works with
Any app
Every BitaKit app
Versions
2
versions
Publisher
bitakit
Official

Preview

1 picture

Strapi

About

@bitakit/strapi

A headless BitaKit plugin for Strapi 5: every content type with all standard REST operations, custom endpoints per model, typed filters, Users & Permissions authentication (password, providers, refresh tokens) as BitaKit's auth contract, uploads and typed errors. Reads are cached in the shared @bitakit/query client. It is built on the official @strapi/client and qs, has no UI and runs in the browser and in Node.

npm install @bitakit/strapi
// src/configs/strapi.ts — plain data; everything here reaches the browser
export default {
  url: 'http://localhost:1337',
  prefix: '/api', // Strapi's rest.prefix
  token: undefined, // optional API token, read-only if it ships to a browser
  auth: {
    contract: true, // provide BitaKit's `auth`; false when another provider owns it
    session: 'local', // 'local' | 'session' | 'memory'
    jwtManagement: 'legacy', // 'refresh' for refresh tokens, sessions and server logout
    paths: { signIn: '/login', afterSignIn: '/', afterSignOut: '/' },
  },
  cache: { staleTime: 30_000 }, // or false: every read goes to Strapi
  defaults: { locale: undefined, status: undefined }, // applied to every content call
};

With discovery, that is the whole setup. Without it: createRuntime({ plugins: [queryPlugin(), strapiPlugin({ url })] }) from @bitakit/query and @bitakit/strapi.

Content by name

const content = services.strapi.content; // or getService(services, strapiContent)

await content.collection('articles').find({ filters: { title: { $containsi: 'bitakit' } } });
await content.collection('articles').findOne(documentId, { populate: ['author'] });
await content.single('homepage').get();
await content.request({ method: 'GET', path: '/stats/summary', query: { year: 2026 } });
await content.contentTypes(); // Content-type Builder schemas (needs that permission)
await content.locales(); // i18n locales

A collection offers find, findOne, findFirst, count, findAll (async iteration over pages), create, update, delete, publish, localize and watch; a single type get, update, delete and watch. Strapi 5 has no PATCH: update sends PUT, which is a partial update. Unpublishing needs a custom route on the Strapi side.

Models with custom endpoints

A model is a subclass in your feature folder. this.http calls routes under /api/<name>, cached keeps a custom read in the model's cache scope, and write invalidates the model and emits strapi.changed.

// src/plugins/blog/strapi/articles.ts
import { StrapiCollection, type StrapiDocument } from '@bitakit/strapi';

export interface Article extends StrapiDocument {
  title: string;
  slug: string;
  views: number;
}

export class Articles extends StrapiCollection<Article> {
  static contentName = 'articles';
  static invalidates = ['authors']; // cached reads that a write here also changes

  bySlug(slug: string) {
    return this.findFirst({ filters: { slug: { $eq: slug } }, populate: ['author'] });
  }
  trending(days: number) {
    return this.cached(['trending', days], () =>
      this.http.get<Article[]>('/trending', { query: { days } }),
    );
  }
  like(documentId: string) {
    return this.write(() => this.http.post<{ likes: number }>(`/${documentId}/like`), {
      operation: 'like',
      documentId,
    });
  }
}

const articles = services.strapi.content.model(Articles); // one instance per class

Filters and queries

Queries are Strapi's own REST parameters, typed against the model: every operator ($eq, $eqi, $ne, $nei, $lt, $lte, $gt, $gte, $in, $notIn, $contains, $notContains, $containsi, $notContainsi, $null, $notNull, $between, $startsWith(i), $endsWith(i)), $and / $or / $not, nested relation filters, populate, fields, sort, pagination, status and locale. Anything in the Strapi documentation can be copied in.

await articles.find({
  filters: {
    $and: [
      { $or: [{ category: { slug: { $eq: 'news' } } }, { featured: { $eq: true } }] },
      { publishedAt: { $between: ['2026-01-01', '2026-12-31'] } },
      { $not: { author: { id: { $null: true } } } },
    ],
  },
  populate: { author: { fields: ['name'] }, cover: true },
  sort: ['publishedAt:desc', 'title'],
  pagination: { page: 1, pageSize: 20 },
});

Cache and React

Reads go through the shared TanStack Query client: repeated reads are deduplicated and cached for cache.staleTime; { fresh: true } skips the cache. Every write invalidates the model's reads (plus invalidates) and emits strapi.changed with { model, operation, documentId?, locale? }. Reads of the previous user are removed when the signed-in user changes.

import { useMutation, useQuery } from '@tanstack/react-query';
import { useService } from '@bitakit/ui';

// Plugin pages and slots render once the runtime is ready, so the service exists there.
const articles = useService('strapi.content')!.model(Articles);
const { data } = useQuery(articles.queries.find({ pagination: { pageSize: 20 } }));
const remove = useMutation(articles.mutations.delete()); // lists refresh by themselves

watch(query) gives the same reactive read without React (getSnapshot, subscribe, refetch). With cache: false every read goes to Strapi and watch is unavailable; the queries / mutations descriptors still work with any TanStack Query client, and query keys come from strapiKeys, so other cache libraries can use the promises and the event.

Authentication

const auth = services.auth; // or getService(services, strapiAuth) when auth.contract is false

await auth.signInWithPassword({ identifier, password });
await auth.register({ username, email, password }); // { user, confirmationRequired }
await auth.forgotPassword(email);
await auth.resetPassword({ code, password, passwordConfirmation });
await auth.changePassword({ currentPassword, password, passwordConfirmation });
await auth.sendEmailConfirmation(email);
await auth.me({ populate: ['role'] });
await auth.signOut(); // { everywhere: true } with refresh tokens
auth.state.get(); // { status: 'pending' | 'anonymous' | 'authenticated', user, error }

Provider login (GitHub, Google, ... configured in Strapi): auth.signInWithProvider('github', { returnTo }) sends the browser to <api>/connect/github. On the page Strapi redirects back to, auth.completeProviderSignIn('github') exchanges the access_token from the URL for a session and returns the validated returnTo. With auth.provider: 'github', the contract's signIn starts that login, so useAuth().signIn() works directly.

The service implements BitaKit's auth contract, so useAuth, AuthBoundary, per-user Settings and every plugin that requires: [authService] work unchanged. Only one plugin may provide auth: set auth.contract: false when another provider such as Better Auth owns it. The snapshot is a rendering aid, not proof of identity; a server checks the JWT itself.

A stored session is restored with /users/me on start (pending meanwhile). A 401 with a user token refreshes once (jwtManagement: 'refresh') and retries, or ends the session and emits strapi.sessionExpired. Login and other public auth routes never send a stale user token.

Headless Actions for any UI binding: strapi.signIn, strapi.register, strapi.forgotPassword, strapi.resetPassword and strapi.signOut (visible while signed in). Strapi's messages ("Invalid identifier or password") are their failure feedback. auth.users covers /api/users (plain bodies, integer ids).

Uploads

const files = services.strapi.files;
await files.upload(file, {
  info: { alternativeText: 'Cover' },
  attachTo: { ref: 'api::article.article', refId: article.id, field: 'cover' },
});
await files.find({ filters: { mime: { $startsWith: 'image/' } } });
await files.findOne(id);
await files.update(id, { caption: 'New' });
await files.delete(id);

upload takes File/Blob values (in Node: new File([buffer], name, { type })).

Errors

Every failure rejects with a StrapiError (status, code = Strapi's error name, details, request), built from Strapi's { error: { status, name, message, details } } body:

| Class | When | | ------------------------- | -------------------------------------------------- | | StrapiUnauthorizedError | 401: not signed in, or the token expired | | StrapiForbiddenError | 403: the role or API token lacks the permission | | StrapiNotFoundError | 404 | | StrapiValidationError | 400 ValidationError, with fieldErrors | | StrapiRateLimitError | 429, with retryAfter | | StrapiNetworkError | no response: network, CORS or the client's timeout |

Cached reads retry network failures and 5xx responses twice, never 4xx.

Services, events and interceptors

| Service | Contract | Purpose | | ---------------- | ----------------------- | ------------------------------------------------ | | strapi.http | | @strapi/client instances and the session token | | strapi.auth | auth or strapi-auth | Users & Permissions | | strapi.content | strapi-content | every content type, the cache | | strapi.files | strapi-files | Upload plugin |

Events: strapi.changed, strapi.signedIn, strapi.signedOut, strapi.sessionExpired. Model classes call the flat methods of strapi.content (find(model, query), create(model, data), write(model, ...), ...), so one interceptor observes every model: defineInterceptor({ service: 'strapi.content', after: ({ method, args }) => audit(method, args[0]) }).

Limits

  • @strapi/client aborts a request after 10 seconds, so very large uploads can time out.
  • Refresh tokens kept in an HTTP-only cookie (sessions.httpOnly) are not supported; the plugin stores the refresh token with the session.
  • Email confirmation links point at Strapi directly and need no client call.

Information

Publisher
bitakit · Official
Type
PackageNeeds installation: add it to the app's code and build the app.
Kind
Plugin
Works with
Every BitaKit app
Categories
Content
Versions
0.3.20.3.1