diff --git a/.changeset/proud-horses-add.md b/.changeset/proud-horses-add.md new file mode 100644 index 0000000000..ffe9b46d53 --- /dev/null +++ b/.changeset/proud-horses-add.md @@ -0,0 +1,5 @@ +--- +"@medusajs/js-sdk": patch +--- + +fix(js-sdk): Preserve path in baseUrl diff --git a/packages/core/js-sdk/src/__tests__/client.spec.ts b/packages/core/js-sdk/src/__tests__/client.spec.ts index 58199a56b1..5e35771678 100644 --- a/packages/core/js-sdk/src/__tests__/client.spec.ts +++ b/packages/core/js-sdk/src/__tests__/client.spec.ts @@ -12,6 +12,11 @@ const server = setupServer( test: "test", }) }), + http.get(`${baseUrl}/some/path/test`, ({ request, params, cookies }) => { + return HttpResponse.json({ + test: "test", + }) + }), http.get(`${baseUrl}/throw`, ({ request, params, cookies }) => { return new HttpResponse(null, { status: 500, @@ -184,6 +189,42 @@ describe("Client", () => { global.window = undefined as any }) + + it("should handle baseUrl with path correctly", async () => { + const pathClient = new Client({ + baseUrl: `${baseUrl}/some/path`, + }) + + const resp = await pathClient.fetch("test") + expect(resp).toEqual({ test: "test" }) + }) + + it("should handle baseUrl with trailing slash path correctly", async () => { + const pathClient = new Client({ + baseUrl: `${baseUrl}/some/path/`, + }) + + const resp = await pathClient.fetch("test") + expect(resp).toEqual({ test: "test" }) + }) + + it("should handle baseUrl with just origin", async () => { + const originClient = new Client({ + baseUrl, + }) + + const resp = await originClient.fetch("test") + expect(resp).toEqual({ test: "test" }) + }) + + it("should handle baseUrl with just origin and trailing slash", async () => { + const originClient = new Client({ + baseUrl: `${baseUrl}/`, + }) + + const resp = await originClient.fetch("test") + expect(resp).toEqual({ test: "test" }) + }) }) describe("GET requests", () => { @@ -247,4 +288,6 @@ describe("Client", () => { global.window = undefined as any }) }) + + }) diff --git a/packages/core/js-sdk/src/client.ts b/packages/core/js-sdk/src/client.ts index 1bad3d3ce0..03794630f8 100644 --- a/packages/core/js-sdk/src/client.ts +++ b/packages/core/js-sdk/src/client.ts @@ -1,5 +1,5 @@ -import qs from "qs" import { events } from "fetch-event-stream" +import qs from "qs" import { ClientFetch, Config, @@ -224,7 +224,9 @@ export class Client { let normalizedInput: RequestInfo | URL = input if (input instanceof URL || typeof input === "string") { - normalizedInput = new URL(input, this.config.baseUrl) + const baseUrl = new URL(this.config.baseUrl) + const fullPath = `${baseUrl.pathname.replace(/\/$/, '')}/${input.toString().replace(/^\//, '')}` + normalizedInput = new URL(fullPath, baseUrl.origin) if (init?.query) { const params = Object.fromEntries( normalizedInput.searchParams.entries()