Package API
Reference for @sumx/http-client: the factory, request helpers returned by createSumxHttpClient, response types, and standalone utilities.
createSumxHttpClient
Call once in src/axios/axiosInstance.ts. Returns a SumxHttpClient object:
import { createSumxHttpClient } from '@sumx/http-client';
export const {
axiosInstance,
httpRequestUpdated,
httpRequest,
createHttpRequest,
cancelPendingBrowserApiRequests,
powerBIBaseURL,
} = createSumxHttpClient({ /* see [configuration](/http-client/configuration) */ });| Member | Description |
|---|---|
axiosInstance | Configured Axios instance (interceptors, BFF baseURL, auth headers) |
httpRequestUpdated | Primary typed helper for ERP APIs (see below) |
httpRequest | Same as httpRequestUpdated with data typed as Record<string, unknown> |
createHttpRequest | Options-object wrapper around httpRequestUpdated |
cancelPendingBrowserApiRequests | Abort in-flight browser requests (session dialog) |
powerBIBaseURL | Resolved URL for the Power BI base key |
Factory options and hooks: API bases & env · Portal integration.
httpRequestUpdated
Use this in feature services/ (no React). It runs through the shared Axios instance: BFF routing in the browser, client_id / user-context headers, 401 → logout, 403/404 → error routes, and ERP error normalization.
Signature
httpRequestUpdated<T = unknown>(
url: string,
method: httpMethods,
data?: Record<string, unknown>,
headers?: Record<string, string>,
responseType?: AxiosRequestConfig['responseType'],
apiBase?: string
): Promise<ResponseType<T>>;| Parameter | Default | Description |
|---|---|---|
url | — | Path relative to the API base (e.g. '/items') |
method | — | httpMethods.GET | POST | PUT | PATCH | DELETE |
data | undefined | JSON body for POST / PUT / PATCH |
headers | { 'Content-Type': 'application/json' } | Merged with defaults |
responseType | Axios default | Set 'blob' for file downloads |
apiBase | defaultApiBase (core) | Upstream key from apiBaseEnvConfig |
Examples
List (GET):
import { httpRequestUpdated } from '@/axios/axiosInstance';
import { httpMethods } from '@/enums';
export const getItems = (params?: { page?: number }) =>
httpRequestUpdated<ItemDto[]>('/items', httpMethods.GET, params);Create (POST):
export const createItem = (payload: CreateItemDto) =>
httpRequestUpdated<ItemDto>('/items', httpMethods.POST, payload);Alternate upstream (e.g. Power BI):
httpRequestUpdated<EmbedDto>(
'/reports/embed',
httpMethods.GET,
undefined,
undefined,
undefined,
'powerBi'
);Blob export:
const response = await httpRequestUpdated<Blob>(
'/export/pdf',
httpMethods.POST,
{ id },
{ 'Content-Type': 'application/json' },
'blob'
);
const blob = response.data; // blob response shape when responseType is 'blob'Behavior notes
- Throws if the ERP envelope contains
data.error.title(business error). - On failure, errors pass through
normalizeErrorResponse(see below). - Interceptors honor request headers for redirects and session dialog.
httpRequest
Same positional signature as httpRequestUpdated, but the generic defaults to Record<string, unknown> instead of a feature DTO type. Prefer httpRequestUpdated<T> for typed services.
const response = await httpRequest('/legacy-endpoint', httpMethods.GET);createHttpRequest
Object-style calls; generic T is on the function, not on HttpRequestOptions.
Signature
createHttpRequest<T = unknown>(options: HttpRequestOptions): Promise<ResponseType<T>>;
interface HttpRequestOptions {
url: string;
method: httpMethods;
data?: Record<string, unknown>;
headers?: Record<string, string>;
responseType?: AxiosInstance['defaults']['responseType'];
apiBase?: string;
}Example
import { createHttpRequest, httpMethods } from '@/axios/axiosInstance';
await createHttpRequest<ItemDto[]>({
url: '/items',
method: httpMethods.GET,
apiBase: 'core',
});axiosInstance
Raw Axios instance with SumX interceptors attached. Use when you need Axios APIs directly (uncommon in feature code). Prefer httpRequestUpdated for consistent ERP handling.
import { axiosInstance } from '@/axios/axiosInstance';
// Rare: custom config while keeping interceptors
await axiosInstance.request({ url: '/custom', method: 'get', apiBase: 'core' });cancelPendingBrowserApiRequests
Aborts all in-flight browser requests registered by the client (used when the cross-tab session timeout dialog opens). Wire from @sumx/ssr-auth-react check-token deps:
cancelPendingBrowserApiRequests('session-timeout-dialog');Server-side / SSR requests are not tracked.
powerBIBaseURL
Preset resolved URL for the powerBi (or powerBiApiBaseKey) entry from apiBases / env. Useful for embed URLs outside httpRequestUpdated.
Response types
ERP APIs return a normalized envelope. Import types from @sumx/http-client or re-export from @/types.
ResponseType<T>
interface ResponseType<T> {
data: {
statusCode: number;
succeeded: boolean;
idName: string;
refCode: string;
id: string | null;
data: {
pageNumber: number;
totalPages: number;
pageSize: number;
currentPageSize: number;
currentStartIndex: number;
currentEndIndex: number;
totalCount: number;
hasPrevious: boolean;
hasNext: boolean;
data: T; // ← your DTO or list lives here
[key: string]: unknown;
};
error: SumxApiError | null;
[key: string]: unknown;
};
status: number;
}Aliases
| Type | Meaning |
|---|---|
ResponseData<T> | ResponseType<T>['data'] |
ResponseAlternativeData<T> | ResponseType<T>['data']['data'] (inner payload) |
SumxApiError | title, errors, errorMessage, isDeleted, … |
Typical access:
const res = await httpRequestUpdated<ItemDto[]>('/items', httpMethods.GET);
const items = res.data.data.data; // T
const totalCount = res.data.data.totalCount;httpMethods
Enum exported from the package (portal re-exports via @/enums):
| Value | HTTP verb |
|---|---|
httpMethods.GET | GET |
httpMethods.POST | POST |
httpMethods.PUT | PUT |
httpMethods.PATCH | PATCH |
httpMethods.DELETE | DELETE |
Standalone utilities
Imported directly from @sumx/http-client (not from the factory).
normalizeErrorResponse
import { normalizeErrorResponse } from '@sumx/http-client';
const safe = await normalizeErrorResponse(caughtError);Parses Axios errors (including blob error bodies), extracts errorMessage, and returns a plain object suitable for UI. Used internally by interceptors; call manually in custom catch blocks if needed.
Header flag helpers
Read escape-hatch headers from an Axios config (used by interceptors; optional in app code):
| Function | Header |
|---|---|
shouldSkipAuthRedirect(config) | x-skip-auth-redirect |
shouldSkipClientErrorPageRedirect(config) | x-skip-client-error-redirect |
shouldAllowDuringSessionTimeoutDialog(config) | x-allow-session-timeout-request |
URL helpers
| Function | Purpose |
|---|---|
appendSegment(base, segment) | Join base URL + segment without duplicating (e.g. …/api + api) |
trimTrailingSlash(value) | Normalize trailing slashes |
Used by createApiBasesFromEnv and base URL resolution.
Typing apiBase on Axios
Narrow apiBase to your host keys in src/axios/axios.d.ts:
import type { AxiosInstance } from 'axios';
import type { ApiBaseKey } from '@/config/api-bases.config';
declare module 'axios' {
export interface AxiosRequestConfig {
apiBase?: ApiBaseKey;
}
}
export type SumxPortalAxiosTypesAnchor = AxiosInstance;Library-only apps without a host ApiBaseKey union can import @sumx/http-client/axios-types.
Request headers (escape hatches)
Set on individual requests via the headers argument or HttpRequestOptions.headers:
| Header | Effect |
|---|---|
x-skip-auth-redirect: true | Do not run logout redirect on 401 |
x-skip-client-error-redirect: true | Do not navigate to /not-found / /forbidden |
x-allow-session-timeout-request: true | Allow request while session dialog is open |
x-api-base | Override apiBase for one request (interceptor) |
Full export list
From createSumxHttpClient
| Export | Kind |
|---|---|
axiosInstance | Value |
httpRequestUpdated | Value |
httpRequest | Value |
createHttpRequest | Value |
cancelPendingBrowserApiRequests | Value |
powerBIBaseURL | Value |
Package barrel (@sumx/http-client)
| Export | Kind |
|---|---|
createSumxHttpClient | Factory |
createApiBasesFromEnv | API base URLs from env |
httpMethods | Enum |
normalizeErrorResponse | Error parser |
shouldSkipAuthRedirect | Header helper |
shouldSkipClientErrorPageRedirect | Header helper |
shouldAllowDuringSessionTimeoutDialog | Header helper |
appendSegment | URL helper |
trimTrailingSlash | URL helper |
ApiBaseEnvConfig | Type |
ApiBaseEnvEntry | Type |
CreateApiBasesFromEnvOptions | Type |
HttpRequestOptions | Type |
ResponseType | Type |
ResponseData | Type |
ResponseAlternativeData | Type |
SumxApiError | Type |
SumxHttpClient | Type |
SumxHttpClientConfig | Type |
SumxHttpClientHooks | Type |
Next.js
// next.config.js
transpilePackages: ['@sumx/http-client'],