@deliverart/sdk-js-authentication

中文文档
3.0.1发布于 2026/11/11TypeScriptESM + CJS近 30 天下载 3158

Authentication module for DeliverArt SDK

原始使用文档
文档目录22 节
  1. Installation
  2. Exported Types
  3. AuthenticationPlugin
  4. AuthenticationConfig
  5. AuthenticationExtension
  6. Errors
  7. Usage
  8. Basic Setup
  9. With Different Token Storage
  10. Enabling/Disabling Authentication
  11. Complete Example with Next.js
  12. Login Flow Example
  13. Logout Flow Example
  14. Token Refresh Example
  15. Error Handling
  16. How It Works
  17. Best Practices
  18. 1. Centralized Token Management
  19. 2. Secure Token Storage
  20. 3. Handle Token Expiration
  21. 4. Global Error Handling
  22. License

@deliverart/sdk-js-authentication

Authentication plugin for the DeliverArt JavaScript SDK. Automatically adds Bearer token authentication to all API requests.

Installation

npm install @deliverart/sdk-js-authentication @deliverart/sdk-js-core
# or
pnpm add @deliverart/sdk-js-authentication @deliverart/sdk-js-core
# or
yarn add @deliverart/sdk-js-authentication @deliverart/sdk-js-core

Exported Types

AuthenticationPlugin

class AuthenticationPlugin implements ApiClientPlugin<AuthenticationExtension>

Plugin that adds JWT Bearer token authentication to all API requests.

Constructor:

  • constructor(config: AuthenticationConfig)

AuthenticationConfig

interface AuthenticationConfig {
  getAccessToken: () => Promise<string | null>
}

Configuration object for the authentication plugin.

Properties:

  • getAccessToken: () => Promise<string | null> (required) - Async function that returns the access token or null if not authenticated

AuthenticationExtension

interface AuthenticationExtension extends ApiExtension {
  authentication: {
    enable: () => void;
    disable: () => void;
  }
}

Extension added to the API client when the plugin is installed.

Methods:

  • enable() - Enable authentication (adds Authorization header to requests)
  • disable() - Disable authentication (skips adding Authorization header)

Errors

AuthenticationError

class AuthenticationError extends Error

Thrown when authentication is required but no access token is available.

Usage

Basic Setup

import { createApiClient } from '@deliverart/sdk-js-core';
import { AuthenticationPlugin } from '@deliverart/sdk-js-authentication';

const getAccessToken = async (): Promise<string | null> => {
  // Retrieve token from your storage
  return localStorage.getItem('accessToken');
};

const client = createApiClient({ 
  baseUrl: 'https://api.deliverart.com' 
})
  .addPlugin(new AuthenticationPlugin({ getAccessToken }));

Parameters:

  • getAccessToken (required) - Function that retrieves the current access token

With Different Token Storage

LocalStorage

const getAccessToken = async (): Promise<string | null> => {
  return localStorage.getItem('accessToken');
};

SessionStorage

const getAccessToken = async (): Promise<string | null> => {
  return sessionStorage.getItem('accessToken');
};

Cookies

import Cookies from 'js-cookie';

const getAccessToken = async (): Promise<string | null> => {
  return Cookies.get('accessToken') ?? null;
};

Next.js with Server Actions

import { cookies } from 'next/headers';

const getAccessToken = async (): Promise<string | null> => {
  const cookieStore = await cookies();
  return cookieStore.get('accessToken')?.value ?? null;
};

Auth Provider (e.g., Auth0, Clerk)

import { useAuth } from '@clerk/nextjs';

const getAccessToken = async (): Promise<string | null> => {
  const { getToken } = useAuth();
  return await getToken();
};

Enabling/Disabling Authentication

// Disable authentication temporarily
client.authentication.disable();

// Make unauthenticated requests
await client.call(new PublicRequest());

// Re-enable authentication
client.authentication.enable();

// Make authenticated requests
await client.call(new ProtectedRequest());

Use Cases:

  • Public endpoints that don't require authentication
  • Guest checkout flows
  • Login/registration requests

Complete Example with Next.js

// lib/sdk/client.ts
import { createApiClient, type ApiClient } from '@deliverart/sdk-js-core';
import { AuthenticationPlugin } from '@deliverart/sdk-js-authentication';
import { ErrorHandlerPlugin } from '@deliverart/sdk-js-error-handler';

const getAccessToken = async (): Promise<string | null> => {
  // Server-side: get from cookies
  if (typeof window === 'undefined') {
    const { cookies } = await import('next/headers');
    const cookieStore = await cookies();
    return cookieStore.get('accessToken')?.value ?? null;
  }
  
  // Client-side: get from localStorage
  return localStorage.getItem('accessToken');
};

export const sdk = createApiClient({ 
  baseUrl: process.env.NEXT_PUBLIC_API_BASE_URL! 
})
  .addPlugin(new ErrorHandlerPlugin())
  .addPlugin(new AuthenticationPlugin({ getAccessToken }));

Login Flow Example

import { sdk } from './lib/sdk/client';
import { Login } from '@deliverart/sdk-js-auth';

// Disable authentication for login request
sdk.authentication.disable();

try {
  const response = await sdk.call(new Login({
    email: '[email protected]',
    password: 'password123'
  }));
  
  // Store the token
  localStorage.setItem('accessToken', response.token);
  
  // Re-enable authentication for subsequent requests
  sdk.authentication.enable();
  
  // Now all requests will include the Authorization header
  const user = await sdk.call(new GetCurrentUser());
  
} catch (error) {
  console.error('Login failed:', error);
}

Logout Flow Example

import { sdk } from './lib/sdk/client';

// Clear the token
localStorage.removeItem('accessToken');

// Disable authentication (optional, depends on your needs)
sdk.authentication.disable();

// Redirect to login page
window.location.href = '/login';

Token Refresh Example

import { sdk } from './lib/sdk/client';
import { AuthenticationError } from '@deliverart/sdk-js-authentication';

let tokenRefreshPromise: Promise<string> | null = null;

const getAccessToken = async (): Promise<string | null> => {
  let token = localStorage.getItem('accessToken');
  
  // Check if token is expired (you need to implement this)
  if (token && isTokenExpired(token)) {
    // Ensure only one refresh happens at a time
    if (!tokenRefreshPromise) {
      tokenRefreshPromise = refreshToken();
    }
    
    try {
      token = await tokenRefreshPromise;
      localStorage.setItem('accessToken', token);
    } finally {
      tokenRefreshPromise = null;
    }
  }
  
  return token;
};

async function refreshToken(): Promise<string> {
  const refreshToken = localStorage.getItem('refreshToken');
  
  if (!refreshToken) {
    throw new AuthenticationError('No refresh token available');
  }
  
  // Disable authentication for refresh request
  sdk.authentication.disable();
  
  try {
    const response = await sdk.call(new RefreshToken({ refreshToken }));
    sdk.authentication.enable();
    return response.accessToken;
  } catch (error) {
    // Refresh failed, redirect to login
    localStorage.clear();
    window.location.href = '/login';
    throw error;
  }
}

function isTokenExpired(token: string): boolean {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.exp * 1000 < Date.now();
  } catch {
    return true;
  }
}

Error Handling

import { AuthenticationError } from '@deliverart/sdk-js-authentication';

try {
  await sdk.call(new GetUser('123'));
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message);
    // Redirect to login page
    window.location.href = '/login';
  }
}

How It Works

The plugin adds a request middleware that:

  1. Calls your getAccessToken function to retrieve the current token
  2. If a token is found, adds it to the Authorization header as Bearer <token>
  3. If no token is found and authentication is enabled, throws an AuthenticationError
  4. If authentication is disabled, skips adding the Authorization header

Best Practices

1. Centralized Token Management

Create a dedicated module for token management:

// lib/auth/tokens.ts
export const setAccessToken = (token: string) => {
  localStorage.setItem('accessToken', token);
};

export const getAccessToken = (): string | null => {
  return localStorage.getItem('accessToken');
};

export const clearTokens = () => {
  localStorage.removeItem('accessToken');
  localStorage.removeItem('refreshToken');
};

2. Secure Token Storage

  • Use httpOnly cookies for tokens when possible (more secure)
  • Avoid storing sensitive tokens in localStorage on production if possible
  • Consider using secure storage libraries for mobile apps

3. Handle Token Expiration

Implement automatic token refresh before the token expires:

const getAccessToken = async (): Promise<string | null> => {
  const token = localStorage.getItem('accessToken');
  
  if (token && willExpireSoon(token)) {
    return await refreshAccessToken();
  }
  
  return token;
};

function willExpireSoon(token: string, bufferSeconds = 60): boolean {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return payload.exp * 1000 < Date.now() + (bufferSeconds * 1000);
  } catch {
    return true;
  }
}

4. Global Error Handling

Set up global error handling for authentication errors:

import { ApiError } from '@deliverart/sdk-js-error-handler';

window.addEventListener('unhandledrejection', (event) => {
  if (event.reason instanceof ApiError && event.reason.statusCode === 401) {
    // Handle unauthorized errors globally
    clearTokens();
    window.location.href = '/login';
  }
});

License

MIT

版本与发布记录

@deliverart/sdk-js-authentication 共发布 319 个版本,首次发布于 2025/06/17;过去 12 个月发布了 230 个版本。

版本发布日期距今
3.0.1latest2026/11/111 天前
3.0.02026/11/092 天前
3.0.0-dev.1dev2026/11/092 天前
2.48.12026/10/2518 天前
2.48.02026/10/2319 天前
2.47.02026/10/2319 天前

关于 @deliverart/sdk-js-authentication 的常见问题

@deliverart/sdk-js-authentication 是什么?

Authentication module for DeliverArt SDK

如何安装 @deliverart/sdk-js-authentication?

在项目目录运行 npm install @deliverart/sdk-js-authentication,或使用 pnpm add / yarn add / bun add。

@deliverart/sdk-js-authentication 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@deliverart/sdk-js-authentication 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@deliverart/sdk-js-authentication 可以商用吗?

@deliverart/sdk-js-authentication 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@deliverart/sdk-js-authentication 的下载量有多少?

根据 npm 官方下载统计,@deliverart/sdk-js-authentication 在 2026/10/12 – 2026/11/10 这 30 天内被下载 3,158 次,日均约 105 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@deliverart/sdk-js-authentication 还在维护吗?

最新版本 3.0.1 发布于 2026/11/11(1 天前);至今共发布 319 个版本,其中过去 12 个月发布了 230 个;首次发布于 2025/06/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。