Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Preserve HTTP errors and session recovery in SDKs (#14593)

Hemang-ai0f224508b3d2
diff --git a/.changeset/steady-http-error-recovery.md b/.changeset/steady-http-error-recovery.md
new file mode 100644
index 0000000000..3cab1ab725
--- /dev/null
+++ b/.changeset/steady-http-error-recovery.md
@@ -0,0 +1,7 @@
+---
+"@spree/sdk": patch
+"@spree/admin-sdk": patch
+"@spree/seller-sdk": patch
+---
+
+Preserve HTTP error statuses when a server returns an empty, non-JSON, or malformed error body. Avoid treating these responses as network failures, and allow admin and seller session recovery to handle unauthorized responses.
diff --git a/docs/developer/sdk/admin/querying-and-errors.mdx b/docs/developer/sdk/admin/querying-and-errors.mdx
index 18ac353bdc..b0eae0683a 100644
--- a/docs/developer/sdk/admin/querying-and-errors.mdx
+++ b/docs/developer/sdk/admin/querying-and-errors.mdx
@@ -97,6 +97,8 @@ try {
}
```
+If a proxy or server returns an empty body, non-JSON content, or JSON without a valid Spree error, the error has code `http_error` and retains the HTTP status. The raw response body is omitted. For requests outside `/auth/`, a `401` still reaches the registered `onUnauthorized` handler. Retry decisions still follow the configured HTTP status policy.
+
### Validation errors
On `422` responses, `details` maps attribute names to arrays of messages — ready to project onto form fields:
diff --git a/docs/developer/sdk/configuration.mdx b/docs/developer/sdk/configuration.mdx
index b2cf1e33d3..3b7ea2fe35 100644
--- a/docs/developer/sdk/configuration.mdx
+++ b/docs/developer/sdk/configuration.mdx
@@ -47,6 +47,8 @@ The channel scopes product visibility (only products published on that channel a
## Error Handling
+Unsuccessful HTTP responses throw a `SpreeError`. If a proxy or server returns an empty body, non-JSON content, or JSON without a valid Spree error, the error has code `http_error`, retains the HTTP status, and omits the raw response body. Retry decisions still follow the configured HTTP status policy.
+
```typescript
import { SpreeError } from '@spree/sdk';
diff --git a/packages/admin-sdk/tests/auth.test.ts b/packages/admin-sdk/tests/auth.test.ts
index 1d126a4681..b32ca3ff52 100644
--- a/packages/admin-sdk/tests/auth.test.ts
+++ b/packages/admin-sdk/tests/auth.test.ts
@@ -1,9 +1,49 @@
import { HttpResponse, http } from 'msw'
-import { beforeEach, describe, expect, it } from 'vitest'
-import { API_PREFIX, createUnauthenticatedClient } from './helpers'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createAdminClient, SpreeError } from '../src'
+import { API_PREFIX, BASE_URL, createUnauthenticatedClient } from './helpers'
import { server } from './mocks/server'
describe('auth', () => {
+ describe('non-JSON unauthorized responses', () => {
+ it('refreshes the token before retrying the original request', async () => {
+ const tokens: string[] = []
+ server.use(
+ http.get(`${API_PREFIX}/products`, ({ request }) => {
+ tokens.push(request.headers.get('Authorization') ?? '')
+ if (tokens.length === 1) {
+ return HttpResponse.html('<html>Unauthorized</html>', { status: 401 })
+ }
+ return HttpResponse.json({ data: [] })
+ }),
+ )
+ const client = createAdminClient({ baseUrl: BASE_URL, jwtToken: 'expired-token' })
+ const onUnauthorized = vi.fn(async () => {
+ client.setToken('refreshed-token')
+ return true
+ })
+ client.onUnauthorized(onUnauthorized)
+
+ await expect(client.products.list()).resolves.toEqual({ data: [] })
+ expect(onUnauthorized).toHaveBeenCalledTimes(1)
+ expect(tokens).toEqual(['Bearer expired-token', 'Bearer refreshed-token'])
+ })
+
+ it('does not invoke session recovery for a failed login', async () => {
+ const handleLogin = vi.fn(() => new HttpResponse(null, { status: 401 }))
+ server.use(http.post(`${API_PREFIX}/auth/login`, handleLogin))
+ const client = createUnauthenticatedClient()
+ const onUnauthorized = vi.fn(async () => true)
+ client.onUnauthorized(onUnauthorized)
+
+ await expect(client.auth.login({ email: '[email protected]', password: 'p' })).rejects.toBeInstanceOf(
+ SpreeError,
+ )
+ expect(handleLogin).toHaveBeenCalledTimes(1)
+ expect(onUnauthorized).not.toHaveBeenCalled()
+ })
+ })
+
describe('login', () => {
beforeEach(() => {
server.use(
diff --git a/packages/sdk-core/src/request.ts b/packages/sdk-core/src/request.ts
index dcc6e5e12a..5b8d203122 100644
--- a/packages/sdk-core/src/request.ts
+++ b/packages/sdk-core/src/request.ts
@@ -227,8 +227,24 @@ export function createRequestFn(
continue
}
- const errorBody = (await response.json()) as ErrorResponse
- throw new SpreeError(errorBody, response.status)
+ const errorBody: ErrorResponse | null = await response.json().catch(() => null)
+ if (
+ typeof errorBody?.error?.code === 'string' &&
+ typeof errorBody.error.message === 'string'
+ ) {
+ throw new SpreeError(errorBody, response.status)
+ }
+
+ // Proxy error pages and empty bodies must not turn HTTP failures into network retries.
+ throw new SpreeError(
+ {
+ error: {
+ code: 'http_error',
+ message: `Request failed with status ${response.status}`,
+ },
+ },
+ response.status,
+ )
}
// Handle 204 No Content (empty body)
diff --git a/packages/sdk/tests/retry.test.ts b/packages/sdk/tests/retry.test.ts
index 7543fe36a2..d5f1751d3b 100644
--- a/packages/sdk/tests/retry.test.ts
+++ b/packages/sdk/tests/retry.test.ts
@@ -241,6 +241,86 @@ describe('Retry logic', () => {
})
})
+ describe('HTTP errors without a Spree error body', () => {
+ it.each([
+ { status: 400, body: '<html>Bad request</html>' },
+ { status: 401, body: '' },
+ { status: 403, body: 'Access denied' },
+ { status: 404, body: '{' },
+ { status: 422, body: 'null' },
+ { status: 422, body: '{}' },
+ { status: 422, body: '{"error":null}' },
+ { status: 422, body: '{"error":"Invalid address"}' },
+ { status: 422, body: '{"error":{"code":422,"message":"Invalid address"}}' },
+ { status: 422, body: '{"error":{"code":"invalid","message":[]}}' },
+ ])('preserves status $status without retrying $body', async ({ status, body }) => {
+ const mockFetch = vi.fn().mockImplementation(() => new Response(body, { status }))
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: { baseDelay: 1 } })
+
+ await expect(client.products.list()).rejects.toMatchObject({
+ name: 'SpreeError',
+ code: 'http_error',
+ status,
+ message: `Request failed with status ${status}`,
+ details: undefined,
+ })
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not retry a rejected cart write as a network failure', async () => {
+ const mockFetch = vi.fn().mockImplementation(() => new Response('Forbidden', { status: 403 }))
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: { baseDelay: 1 } })
+
+ await expect(client.carts.create()).rejects.toMatchObject({
+ name: 'SpreeError',
+ status: 403,
+ })
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it('respects the configured status retry policy for non-JSON errors', async () => {
+ const mockFetch = vi
+ .fn()
+ .mockImplementation(() => new Response('Service unavailable', { status: 503 }))
+ const client = createClient({
+ ...baseConfig,
+ fetch: mockFetch,
+ retry: { retryOnStatus: [429], baseDelay: 1 },
+ })
+
+ await expect(client.products.list()).rejects.toMatchObject({
+ name: 'SpreeError',
+ status: 503,
+ })
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it('preserves the final HTTP status after retryable errors are exhausted', async () => {
+ const mockFetch = vi
+ .fn()
+ .mockImplementation(() => new Response('Service unavailable', { status: 503 }))
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: { baseDelay: 1 } })
+
+ await expect(client.products.list()).rejects.toMatchObject({
+ name: 'SpreeError',
+ code: 'http_error',
+ status: 503,
+ })
+ expect(mockFetch).toHaveBeenCalledTimes(3)
+ })
+
+ it('preserves the HTTP status when retries are disabled', async () => {
+ const mockFetch = vi.fn().mockResolvedValue(new Response(null, { status: 502 }))
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false })
+
+ await expect(client.products.list()).rejects.toMatchObject({
+ name: 'SpreeError',
+ status: 502,
+ })
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+ })
+
describe('custom retry config', () => {
it('respects custom maxRetries', async () => {
const mockFetch = vi
diff --git a/packages/seller-sdk/tests/auth.test.ts b/packages/seller-sdk/tests/auth.test.ts
new file mode 100644
index 0000000000..2fd50cb616
--- /dev/null
+++ b/packages/seller-sdk/tests/auth.test.ts
@@ -0,0 +1,95 @@
+import { HttpResponse, http } from 'msw'
+import { describe, expect, it, vi } from 'vitest'
+import { createSellerClient, SpreeError } from '../src'
+import { server } from './mocks/server'
+
+const BASE_URL = 'http://api.test'
+const API_PREFIX = `${BASE_URL}/api/v3/seller`
+
+describe('non-JSON unauthorized responses', () => {
+ it('refreshes the token before replaying the request once', async () => {
+ const tokens: string[] = []
+ server.use(
+ http.get(`${API_PREFIX}/products`, ({ request }) => {
+ tokens.push(request.headers.get('Authorization') ?? '')
+ if (tokens.length === 1) {
+ return HttpResponse.html('<html>Unauthorized</html>', { status: 401 })
+ }
+ return HttpResponse.json({ data: [] })
+ }),
+ )
+ const client = createSellerClient({
+ baseUrl: BASE_URL,
+ jwtToken: 'expired-token',
+ retry: { baseDelay: 0 },
+ })
+ const onUnauthorized = vi.fn(async () => {
+ client.setToken('refreshed-token')
+ return true
+ })
+ client.onUnauthorized(onUnauthorized)
+
+ await expect(client.products.list()).resolves.toEqual({ data: [] })
+ expect(onUnauthorized).toHaveBeenCalledTimes(1)
+ expect(tokens).toEqual(['Bearer expired-token', 'Bearer refreshed-token'])
+ })
+
+ it('preserves the HTTP error when session recovery is declined', async () => {
+ const handleProducts = vi.fn(() =>
+ HttpResponse.html('<html>Unauthorized</html>', { status: 401 }),
+ )
+ server.use(http.get(`${API_PREFIX}/products`, handleProducts))
+ const client = createSellerClient({ baseUrl: BASE_URL, retry: { baseDelay: 0 } })
+ const onUnauthorized = vi.fn(async () => false)
+ client.onUnauthorized(onUnauthorized)
+
+ const request = client.products.list()
+
+ await expect(request).rejects.toBeInstanceOf(SpreeError)
+ await expect(request).rejects.toMatchObject({ status: 401 })
+ expect(handleProducts).toHaveBeenCalledTimes(1)
+ expect(onUnauthorized).toHaveBeenCalledTimes(1)
+ })
+
+ it('stops after the replay also returns an unauthorized response', async () => {
+ const tokens: string[] = []
+ server.use(
+ http.get(`${API_PREFIX}/products`, ({ request }) => {
+ tokens.push(request.headers.get('Authorization') ?? '')
+ return HttpResponse.html('<html>Unauthorized</html>', { status: 401 })
+ }),
+ )
+ const client = createSellerClient({
+ baseUrl: BASE_URL,
+ jwtToken: 'expired-token',
+ retry: { baseDelay: 0 },
+ })
+ const onUnauthorized = vi.fn(async () => {
+ client.setToken('refreshed-token')
+ return true
+ })
+ client.onUnauthorized(onUnauthorized)
+
+ const request = client.products.list()
+
+ await expect(request).rejects.toBeInstanceOf(SpreeError)
+ await expect(request).rejects.toMatchObject({ status: 401 })
+ expect(tokens).toEqual(['Bearer expired-token', 'Bearer refreshed-token'])
+ expect(onUnauthorized).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not invoke session recovery for a failed login', async () => {
+ const handleLogin = vi.fn(() => HttpResponse.html('<html>Unauthorized</html>', { status: 401 }))
+ server.use(http.post(`${API_PREFIX}/auth/login`, handleLogin))
+ const client = createSellerClient({ baseUrl: BASE_URL, retry: { baseDelay: 0 } })
+ const onUnauthorized = vi.fn(async () => true)
+ client.onUnauthorized(onUnauthorized)
+
+ const request = client.auth.login({ email: '[email protected]', password: 'password' })
+
+ await expect(request).rejects.toBeInstanceOf(SpreeError)
+ await expect(request).rejects.toMatchObject({ status: 401 })
+ expect(handleLogin).toHaveBeenCalledTimes(1)
+ expect(onUnauthorized).not.toHaveBeenCalled()
+ })
+})