Documents
Strapi SDK Initialization and Architecture Guide
Strapi SDK Initialization and Architecture Guide
Type
Document
Status
Published
Created
Feb 4, 2026
Updated
Feb 4, 2026
Updated by
Dosu Bot

Strapi SDK Initialization and Architecture Guide#

1. Overview#

The Strapi Client SDK (@strapi/client) is the official JavaScript/TypeScript client library for interacting with Strapi's Content API. It provides a type-safe, promise-based interface for managing content, files, and authentication.

2. Initialization Process#

2.1 Main Entry Point#

The SDK uses a factory pattern with the strapi() function as the primary initialization method, which internally creates a StrapiClient instance.

TypeScript:

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

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

JavaScript:

const { strapi } = require('@strapi/client');

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

Browser (UMD):

<script src="https://cdn.jsdelivr.net/npm/@strapi/client"></script>
<script>
  const client = strapi.strapi({ baseURL: 'http://localhost:1337/api' });
</script>

2.2 Advanced Initialization#

For advanced use cases, the StrapiClient class can be instantiated directly:

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

const client = new StrapiClient({
  baseURL: 'http://example.com/api',
  auth: {
    strategy: 'api-token',
    options: { token: 'test_token' },
  },
  headers: {
    'Accept-Language': 'en-US',
  }
});

3. Configuration Options#

3.1 Simple Configuration Interface (Config)#

The strapi() function accepts a Config interface with the following options:

ParameterTypeRequiredDescription
baseURLstringYesThe base URL of the Strapi Content API (must include protocol)
authstringNoAPI token for authentication (automatically configured as Bearer token)
headersRecord<string, string>NoCustom headers included with every request

3.2 Advanced Configuration Interface (StrapiClientConfig)#

The StrapiClient class uses a more detailed StrapiClientConfig interface:

interface StrapiClientConfig {
  baseURL: string;
  auth?: AuthConfig;
  headers?: Record<string, string>;
}

interface AuthConfig<T = unknown> {
  strategy: string;
  options?: T;
}

3.3 Configuration Validation#

The SDK validates configuration during initialization using a dedicated StrapiConfigValidator:

  • Base URL validation: Must be a valid HTTP/HTTPS URL
  • Auth token validation: Must be a non-empty string when provided
  • Headers validation: Must be an object with string values

Invalid configurations throw a StrapiInitializationError wrapping the underlying validation error.

4. Internal Architecture#

4.1 Component Overview#

The Strapi SDK architecture consists of three core components that work together:

  1. HttpClient - Handles HTTP request execution and interceptor management
  2. AuthManager - Manages authentication lifecycle and provider coordination
  3. AuthProviderFactory - Creates and registers authentication providers
Loading diagram...

4.2 HttpClient#

The HttpClient class is the core HTTP client that provides methods for making HTTP requests to Strapi's API.

Key Responsibilities:

Key Methods:

4.3 AuthManager#

The AuthManager class manages authentication by coordinating different authentication providers and strategies.

Key Responsibilities:

Key Methods:

4.4 AuthProviderFactory#

The AuthProviderFactory class is a factory responsible for creating and managing authentication providers.

Key Responsibilities:

Key Methods:

4.5 Component Interaction Flow#

Initialization Flow:

  1. StrapiClient creates instances of AuthManager and HttpClient
  2. AuthManager creates an AuthProviderFactory and registers default providers
  3. If auth config is provided, AuthManager uses the factory to create a provider

Request Interception Flow:

  1. Auth interceptors are registered on HttpClient's request interceptors
  2. ensurePreAuthentication interceptor checks if authentication is needed and calls AuthManager.authenticate()
  3. AuthManager.authenticate() creates an interceptor-free HttpClient clone to avoid infinite loops
  4. authenticateRequests interceptor calls AuthManager.authenticateRequest() which injects headers from the current provider

Response Interception Flow:

  1. notifyOnUnauthorizedResponse interceptor detects 401 errors
  2. Calls AuthManager.handleUnauthorizedError() to reset authentication state

5. Authentication Strategies#

5.1 Supported Strategies#

The Strapi SDK supports two built-in authentication strategies:

API Token Authentication#

Users & Permissions Authentication#

5.2 Authentication Provider Interface#

All authentication providers implement the AuthProvider interface and extend AbstractAuthProvider:

interface AuthProvider {
  name: string;
  headers: Record<string, string>;
  authenticate(httpClient: HttpClient): Promise<void>;
  preflightValidation(): void;
}

5.3 Configuration Options#

API Token Strategy#

Configuration Interface: ApiTokenAuthProviderOptions

OptionTypeRequiredDescription
tokenstringYesThe Strapi API token (must be non-empty)

Usage Example (TypeScript):

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

// Advanced API
const client = new StrapiClient({
  baseURL: 'http://localhost:1337/api',
  auth: {
    strategy: 'api-token',
    options: { token: 'your-api-token-here' }
  }
});

Usage Example (JavaScript):

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

Users & Permissions Strategy#

Configuration Interface: UsersPermissionsAuthProviderOptions

OptionTypeRequiredDescription
identifierstringYesThe unique user identifier (email or username)
passwordstringYesThe user's password

Usage Example (TypeScript):

const client = new StrapiClient({
  baseURL: 'http://localhost:1337/api',
  auth: {
    strategy: 'users-permissions',
    options: { 
      identifier: 'user@example.com', 
      password: 'password123' 
    }
  }
});

// Make authenticated requests
const articles = await client.collection('articles').find();

Usage Example (JavaScript):

const client = new StrapiClient({
  baseURL: 'http://localhost:1337/api',
  auth: {
    strategy: 'users-permissions',
    options: { 
      identifier: 'user@example.com', 
      password: 'password123' 
    }
  }
});

5.4 Default Provider Registration#

The AuthManager automatically registers both default providers during initialization:

this._authProviderFactory
  .register(
    ApiTokenAuthProvider.identifier,
    (options: ApiTokenAuthProviderOptions) => new ApiTokenAuthProvider(options)
  )
  .register(
    UsersPermissionsAuthProvider.identifier,
    (options: UsersPermissionsAuthProviderOptions) => new UsersPermissionsAuthProvider(options)
  );

6. Usage Examples#

6.1 Basic Initialization Examples#

TypeScript with API Token:

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

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

// Fetch content
const articles = await client.collection('articles').find();

JavaScript with API Token:

const { strapi } = require('@strapi/client');

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

client.collection('articles').find()
  .then(articles => console.log(articles))
  .catch(error => console.error(error));

TypeScript with Custom Headers:

const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token-here',
  headers: {
    'X-Custom-Header': 'value',
    'Accept-Language': 'en-US',
  },
});

6.2 Advanced Authentication Examples#

Users & Permissions Authentication:

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

const client = new StrapiClient({
  baseURL: 'http://localhost:1337/api',
  auth: {
    strategy: 'users-permissions',
    options: {
      identifier: 'user@example.com',
      password: 'securePassword123'
    }
  }
});

// The client will automatically authenticate before the first request
const userProfile = await client.collection('users-permissions/users').findOne('me');

Manual JWT Token Usage:

// Obtain JWT token manually
const response = await fetch('http://localhost:1337/api/auth/local', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    identifier: 'user@example.com',
    password: 'password123'
  })
});

const { jwt } = await response.json();

// Use JWT token with client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: jwt
});

6.3 Error Handling#

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

try {
  const client = strapi({ 
    baseURL: 'invalid-url', // Invalid URL format
    auth: 'token'
  });
} catch (error) {
  if (error.name === 'StrapiInitializationError') {
    console.error('Failed to initialize client:', error.message);
  }
}

// Runtime error handling
try {
  const articles = await client.collection('articles').findOne('invalid-id');
} catch (error) {
  if (error.name === 'HTTPError') {
    console.error('Request failed:', error.status, error.message);
  }
}

7. Summary#

The Strapi SDK provides a robust initialization system with:

  1. Simple factory function (strapi()) for basic use cases
  2. Advanced configuration through direct StrapiClient instantiation
  3. Flexible authentication with pluggable strategy system
  4. Type-safe configuration with TypeScript interfaces
  5. Comprehensive validation of initialization parameters

The internal architecture uses:

Supported authentication strategies include: