Dosu LogoDosu Logo
Ask
Join our Discord
StrapiPublic
Strapi
DocumentsStrapi
client
client
Type
External
Status
Published
Created
Mar 5, 2026
Updated
Jun 29, 2026
Updated by
Dosu Bot
Source
View

Strapi Client#

The Strapi Client is a JavaScript library that simplifies interactions with your Strapi back end for fetching, creating, updating, and deleting content through collection(), single(), and files() methods.

The Strapi Client library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content. This guide walks you through setting up the Strapi Client, configuring authentication, and using its key features effectively.

Getting Started#

  • A Strapi project has been created and is running. If you haven't set one up yet, follow the Quick Start Guide to create one.
  • You know the URL of the Content API of your Strapi instance (e.g., http://localhost:1337/api).

Installation#

To use the Strapi Client in your project, install it as a dependency using your preferred package manager:

yarn add @strapi/client
npm install @strapi/client
  pnpm add @strapi/client

Basic configuration#

To start interacting with your Strapi back end, initialize the Strapi Client and set the base API URL:

With Javascript, import the strapi function and create a client instance:

import { strapi } from '@strapi/client';

const client = strapi({ baseURL: 'http://localhost:1337/api' });

With Typescript, import the strapi function and create a client instance with your Strapi API base URL:

import { strapi } from '@strapi/client';

const client = strapi({ baseURL: 'http://localhost:1337/api' });
If you're using the Strapi Client in a browser environment, you can include it using a `

The baseURL must include the protocol (http or https). An invalid URL will throw an error StrapiInitializationError.

Authentication#

The Strapi Client supports different authentication strategies to access protected resources in your Strapi back end.

If your Strapi instance uses API tokens, configure the Strapi Client as follows:

const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token-here',
});

This allows your requests to include the necessary authentication credentials automatically.
If the token is invalid or missing, the client will throw an error during initialization StrapiValidationError.

API Reference#

The Strapi Client provides the following key properties and methods for interacting with your Strapi back end:

ParameterDescription
baseURLThe base API URL of your Strapi back end.
fetch()A utility method for making generic API requests similar to the native fetch API.
collection()Manages collection-type resources (e.g., blog posts, products).
single()Manages single-type resources (e.g., homepage settings, global configurations).
files()Enables upload, retrieve and management of files directly to/from the Strapi Media Library.

General purpose fetch#

The Strapi Client provides access to the underlying JavaScript fetch function to make direct API requests. The request is always relative to the base URL provided during client initialization:

const result = await client.fetch('articles', { method: 'GET' });

Working with collection types#

Collection types in Strapi are entities with multiple entries (e.g., a blog with many posts). The Strapi Client provides a collection() method to interact with these resources, with the following methods available:

ParameterDescription
find(queryParams?)Fetch multiple documents with optional filtering, sorting, or pagination.
findOne(documentID, queryParams?)Retrieve a single document by its unique ID.
create(data, queryParams?)Create a new document in the collection.
update(documentID, data, queryParams?)Update an existing document.
delete(documentID, queryParams?)Delete an existing document.

Usage examples:

const articles = client.collection('articles');

// Fetch all english articles sorted by title
const allArticles = await articles.find({
  locale: 'en',
  sort: 'title',
});

// Fetch a single article
const singleArticle = await articles.findOne('article-document-id');

// Create a new article
const newArticle = await articles.create({ title: 'New Article', content: '...' });

// Update an existing article
const updatedArticle = await articles.update('article-document-id', { title: 'Updated Title' });

// Delete an article
await articles.delete('article-id');

Working with single types#

Single types in Strapi represent unique content entries that exist only once (e.g., the homepage settings or site-wide configurations). The Strapi Client provides a single() method to interact with these resources, with the following methods available:

ParameterDescription
find(queryParams?)Fetch the document.
update(documentID, data, queryParams?)Update the document.
delete(queryParams?)Remove the document.

Usage examples:

const homepage = client.single('homepage');

// Fetch the default homepage content
const defaultHomepage = await homepage.find();

// Fetch the Spanish version of the homepage
const spanishHomepage = await homepage.find({ locale: 'es' });

// Update the homepage draft content
const updatedHomepage = await homepage.update(
  { title: 'Updated Homepage Title' },
  { status: 'draft' }
);

// Delete the homepage content
await homepage.delete();

Working with files#

The Strapi Client provides access to the Media Library via the files property. This allows you to retrieve and manage file metadata without directly interacting with the REST API.

The following methods are available for working with files. Click on the method name in the table to jump to the corresponding section with more details and examples:

MethodDescription
find(params?)Retrieves a list of file metadata based on optional query parameters
findOne(fileId)Retrieves the metadata for a single file by its ID
update(fileId, fileInfo)Updates metadata for an existing file
upload(file, options)Uploads a file (Blob or Buffer) with an optional options object for metadata
delete(fileId)Deletes a file by its ID

find#

The strapi.client.files.find() method retrieves a list of file metadata based on optional query parameters.

The method can be used as follows:

// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Find all file metadata
const allFiles = await client.files.find();
console.log(allFiles);

// Find file metadata with filtering and sorting
const imageFiles = await client.files.find({
  filters: {
    mime: { $contains: 'image' }, // Only get image files
    name: { $contains: 'avatar' }, // Only get files with 'avatar' in the name
  },
  sort: ['name:asc'], // Sort by name in ascending order
});

findOne {#findone}#

The strapi.client.files.findOne() method retrieves the metadata for a single file by its id.

The method can be used as follows:

// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Find file metadata by ID
const file = await client.files.findOne(1);
console.log(file.name);
console.log(file.url); 
console.log(file.mime); // The file MIME type

update#

The strapi.client.files.update() method updates metadata for an existing file, accepting 2 parameters, the fileId, and an object containing options such as the name, alternative text, and caption for the media.

The methods can be used as follows:

// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Update file metadata
const updatedFile = await client.files.update(1, {
  name: 'New file name',
  alternativeText: 'Descriptive alt text for accessibility',
  caption: 'A caption for the file',
});

upload {#upload}#

The Strapi Client provides media file upload functionality through the FilesManager, accessible through the strapi.client.files.upload() method. The method allows you to upload media files (such as images, videos, or documents) to your Strapi backend.

The method supports uploading files as Blob (in browsers or Node.js) or as Buffer (in Node.js only). The method also supports attaching metadata to the uploaded file, such as alternativeText and caption.

Method Signature#
async upload(file: Blob, options?: BlobUploadOptions): Promise<MediaUploadResponse>
async upload(file: Buffer, options: BufferUploadOptions): Promise<MediaUploadResponse>
  • For Blob uploads, options is optional and may include fileInfo for metadata.
  • For Buffer uploads, options must include filename and mimetype, and may include fileInfo.

The response is an array of file objects, each containing details such as id, name, url, size, and mime source.

You can upload a file use through the browser as follows:

const client = strapi({ baseURL: 'http://localhost:1337/api' });

const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

try {
  const result = await client.files.upload(file, {
    fileInfo: {
      alternativeText: 'A user uploaded image',
      caption: 'Uploaded via browser',
    },
  });
  console.log('Upload successful:', result);
} catch (error) {
  console.error('Upload failed:', error);
}

With Node.js, you can either upload a blob or a buffer, as in the following examples:

import { readFile } from 'fs/promises';

const client = strapi({ baseURL: 'http://localhost:1337/api' });

const filePath = './image.png';
const mimeType = 'image/png';
const fileContentBuffer = await readFile(filePath);
const fileBlob = new Blob([fileContentBuffer], { type: mimeType });

try {
  const result = await client.files.upload(fileBlob, {
    fileInfo: {
      name: 'Image uploaded as Blob',
      alternativeText: 'Uploaded from Node.js Blob',
      caption: 'Example upload',
    },
  });
  console.log('Blob upload successful:', result);
} catch (error) {
  console.error('Blob upload failed:', error);
}
import { readFile } from 'fs/promises';

const client = strapi({ baseURL: 'http://localhost:1337/api' });

const filePath = './image.png';
const fileContentBuffer = await readFile(filePath);

try {
  const result = await client.files.upload(fileContentBuffer, {
    filename: 'image.png',
    mimetype: 'image/png',
    fileInfo: {
      name: 'Image uploaded as Buffer',
      alternativeText: 'Uploaded from Node.js Buffer',
      caption: 'Example upload',
    },
  });
  console.log('Buffer upload successful:', result);
} catch (error) {
  console.error('Buffer upload failed:', error);
}
Response Structure#

The strapi.client.files.upload() method returns an array of file objects, each with fields such as:

{
  "id": 1,
  "name": "image.png",
  "alternativeText": "Uploaded from Node.js Buffer",
  "caption": "Example upload",
  "mime": "image/png",
  "url": "/uploads/image.png",
  "size": 12345,
  "createdAt": "2025-07-23T12:34:56.789Z",
  "updatedAt": "2025-07-23T12:34:56.789Z"
}

:::note Additional response fields
The upload response includes additional fields beyond those shown above. See the complete FileResponse interface in the for all available fields.
:::

delete#

The strapi.client.files.delete() method deletes a file by its ID.

The method can be used as follows:

// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Delete a file by ID
const deletedFile = await client.files.delete(1);
console.log('File deleted successfully');
console.log('Deleted file ID:', deletedFile.id);
console.log('Deleted file name:', deletedFile.name);

Handling Common Errors#

The following errors might occur when sending queries through the Strapi Client:

ErrorDescription
Permission ErrorsIf the authenticated user does not have permission to upload or manage files, a FileForbiddenError is thrown.
HTTP ErrorsIf the server is unreachable, authentication fails, or there are network issues, an HTTPError is thrown.
Missing ParametersWhen uploading a Buffer, both filename and mimetype must be provided in the options object. If either is missing, an error is thrown.

:::strapi Additional information
More details about the Strapi Client may be found in the .
:::

Documents
Admin Form Validation
Admin Homepage Date Serialization
Admin Modal Management
Admin Panel Locale Management
admin-panel
internationalization
setting-up-admin-panel
Auth Error Classification
AWS S3 Upload Provider
amazon-s3
media-library
Blocks Editor URL Validation
Content Manager List Configuration
Content Manager Mobile Actions Drawer
Content Manager Pagination
Content Manager Query Persistence
Content Manager RBAC
rbac
Content Manager Save State
Content Manager Status Attributes
Content Manager URL & Filter State
admin-panel-api
Content Releases
Data Transfer Streaming
Database Migration Concurrency and Idempotency
deployment
step-by-step
Date Field Serialization
Directory Export
Discard-Drafts Migration
Document ID Migration
document-service
introduction-and-faq
step-by-step
Document Service Clone & Relation Handling
Document Service Input Types
Document Service Populate Concurrency
Document Service Relation Queries
Draft & Publish Relation Synchronization
do-not-update-repeatable-components-with-document-service-api
lifecycle-hooks-document-service
publishedat-always-set-when-dandp-disabled
relations
status
status
DynamicZone Stability
components-and-dynamic-zones-do-not-return-id
components-dynamic-zones
no-shared-population-strategy-components-dynamic-zones
Enterprise License Validation
Entity String Length Validation
Error Class Identity
GraphQL Abort Signal Propagation
GraphQL Filter Pipeline
i18n Locale Validation
locale
locale
i18n Locale-Scoped Operations
crud
database-columns
document
i18n-content-manager-locale
internationalization
locale
locale
locale
no-locale-all
relations
Koa Type Augmentation
MariaDB Schema Synchronization
Media Library Asset Replace
media-library
Media Library Permissions
Media Library Thumbnails
Monorepo Module Resolution
Nested Relation Modal Navigation
OpenAPI Specification Generation
Polymorphic Relations
populate
Private Attribute Populate Validation
Query Builder Parameter Handling
Relation Modal State Management
relations
Relations Field Ordering & Pagination
Remote Asset Export
Rich Text Blocks Validation
Strapi Admin Module Loading
Strapi Attribute Typing
Strapi Content Publishing
content-manager
draft-and-publish
internationalization
parameters
releases
Strapi Data Transfer
deployment
Strapi Project Scaffolding
cli
create-a-plugin
deployment
How can I create my first Strapi project on a brand new MacBook with no prior coding experience, including all necessary terminal commands and setup steps?
quick-start
templates
Strapi TypeScript Build Performance
Strapi v5 Plugin API
admin-panel-rbac-store-updated
admin-permissions-for-plugins
breaking-changes
get-where-removed
helper-plugin
helper-plugin-deprecated
inject-content-manager-component
introduction
model-config-path-uses-uid
pass-data-from-server-to-admin
plugins-migration
rbac
redux-content-manager-app-state
remove-webhook-populate-relations
strapi-imports
Transaction Callback Promise Handling
Upload Storage Consistency
Users & Permissions OAuth Flow
new-provider-guide
users-permissions
Users-Permissions Cookie Authentication
Users-Permissions Session Management
Vite Build Configuration
vite
webpack-aliases-removed
Content Manager Mobile and Tablet UI Improvements
FilesManager API Reference
Focal Point Picker in Strapi Media Library
Nested Route File Structure for Strapi Plugins
Plugin-Specific Handling in the Strapi JavaScript Client
Strapi SDK Initialization and Architecture Guide
access-cast-environment-variables
access-configuration-values
adding-support-to-existing-project
admin-panel
admin-panel-customization
advanced-policies
advanced-queries
api
api-tokens
attributes-and-content-types-names-reserved
audit-logs
auth-zero
authentication
aws-cognito
backend-customization
bulk-operations
bundlers
cas
cli
client
cloudinary
community
configurations
configure-sso
content-api
content-history
content-manager-apis
content-type-builder
controllers
core-service-methods-use-document-service
create-components-for-plugins
cron
custom-fields
customization
data-management
database
database-identifiers-shortened
database-migrations
database-transactions
default-index-removed
default-input-validation
design-system
developing-plugins
development
discord
discord
docker
documentation
documents-and-entries
edit-view-layout-and-list-view-layout-rewritten
email
email-custom-providers
email-nodemailer
entity-service
entity-service-deprecated
environment
error-handling
examples
extension
facebook
faq
favicon
features
fetch
fields
filter
filtering
filters
filters
from-entity-service-to-document-service
functions
github
github
google
google
graphql
graphql
graphql-api-updated
guides
homepage
host-port-path
instagram
installation
installing-plugins-via-marketplace
interactive-query-builder
intro
intro
is-supported-image-removed
keycloak
keycloak
koa-body-v6
license-only
linkedin
local-upload
locales-translations
logos
mailgun-provider-variables
media-library-providers
microsoft
middlewares
middlewares
middlewares
middlewares
models
mysql5-unsupported
new-response-format
no-find-page-in-document-service
no-upload-at-entry-creation
okta
only-better-sqlite3-for-sqlite
only-mysql2-package-for-mysql
openapi
order-pagination
order-pagination
patreon
plugin-sdk
plugin-structure
plugins
plugins-extension
policies
policies
populate
populate-creator-fields
populate-select
populating
preview
project-structure
publication-state-removed
query-engine
react-router-dom-6
reddit
register-allowed-fields
removed-support-for-some-env-options
requests-responses
rest
review-workflows
routes
routes
sentry
server
server-api
server-default-log-level
server-proxy
services
services-and-controllers
setup-deployment
single-operations
sort-by-id
sort-pagination
sort-pagination
sso
store-and-access-data
strapi-container
strapi-utils-refactored
strict-requirements-config-files
templates
testing
theme-extension
twitch
twitter
typescript
typescript
understanding-populate
upgrade-to-apollov4
upgrade-tool
upgrades
upload
usage-information
use-document-id
users-and-permissions-providers
vk
webhooks
wysiwyg-editor
yarn-not-default