Skip to Content
HTTP ClientPackage API

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) */ });
MemberDescription
axiosInstanceConfigured Axios instance (interceptors, BFF baseURL, auth headers)
httpRequestUpdatedPrimary typed helper for ERP APIs (see below)
httpRequestSame as httpRequestUpdated with data typed as Record<string, unknown>
createHttpRequestOptions-object wrapper around httpRequestUpdated
cancelPendingBrowserApiRequestsAbort in-flight browser requests (session dialog)
powerBIBaseURLResolved 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>>;
ParameterDefaultDescription
urlPath relative to the API base (e.g. '/items')
methodhttpMethods.GET | POST | PUT | PATCH | DELETE
dataundefinedJSON body for POST / PUT / PATCH
headers{ 'Content-Type': 'application/json' }Merged with defaults
responseTypeAxios defaultSet 'blob' for file downloads
apiBasedefaultApiBase (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

TypeMeaning
ResponseData<T>ResponseType<T>['data']
ResponseAlternativeData<T>ResponseType<T>['data']['data'] (inner payload)
SumxApiErrortitle, 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):

ValueHTTP verb
httpMethods.GETGET
httpMethods.POSTPOST
httpMethods.PUTPUT
httpMethods.PATCHPATCH
httpMethods.DELETEDELETE

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):

FunctionHeader
shouldSkipAuthRedirect(config)x-skip-auth-redirect
shouldSkipClientErrorPageRedirect(config)x-skip-client-error-redirect
shouldAllowDuringSessionTimeoutDialog(config)x-allow-session-timeout-request

URL helpers

FunctionPurpose
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:

HeaderEffect
x-skip-auth-redirect: trueDo not run logout redirect on 401
x-skip-client-error-redirect: trueDo not navigate to /not-found / /forbidden
x-allow-session-timeout-request: trueAllow request while session dialog is open
x-api-baseOverride apiBase for one request (interceptor)

Full export list

From createSumxHttpClient

ExportKind
axiosInstanceValue
httpRequestUpdatedValue
httpRequestValue
createHttpRequestValue
cancelPendingBrowserApiRequestsValue
powerBIBaseURLValue

Package barrel (@sumx/http-client)

ExportKind
createSumxHttpClientFactory
createApiBasesFromEnvAPI base URLs from env
httpMethodsEnum
normalizeErrorResponseError parser
shouldSkipAuthRedirectHeader helper
shouldSkipClientErrorPageRedirectHeader helper
shouldAllowDuringSessionTimeoutDialogHeader helper
appendSegmentURL helper
trimTrailingSlashURL helper
ApiBaseEnvConfigType
ApiBaseEnvEntryType
CreateApiBasesFromEnvOptionsType
HttpRequestOptionsType
ResponseTypeType
ResponseDataType
ResponseAlternativeDataType
SumxApiErrorType
SumxHttpClientType
SumxHttpClientConfigType
SumxHttpClientHooksType

Next.js

// next.config.js transpilePackages: ['@sumx/http-client'],