redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Redundant trailing slash is added when using root endpoint

Open ygrishajev opened this issue 3 years ago • 3 comments

Steps to reproduce:

  1. declare an API with a baseUrl
  2. add an endpoint that should query root baseUrl with params
  3. call the endpoint

Expected url: /api/foo?bar=baz Actual url: /api/foo/?bar=baz

As a result that redundant trailing slash added after path is causing issues in some apps/environments. E.g. Next.js app would do a redirect to an endpoint without trailing slash, which would fail in iOS Chrome.

Example client API declaration:

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api/foo' }),
  endpoints: (builder) => ({
    findAll: builder.query({
      query: (params) => ({ url: '', params })
    })
  })
});

The issue is tracking down to joinUrls utility function and could be fixed like so:

function joinUrls(base, url) {
    if (!base) {
        return url;
    }
    if (!url) {
        return base;
    }
    if (isAbsoluteUrl(url)) {
        return url;
    }
    base = withoutTrailingSlash(base);
    url = withoutLeadingSlash(url);
    
    const delimiter = url.startsWith('?') ? '' : '/' // <- detect a proper delimiter
  
    return base + delimiter + url;
}

I'm open to do a PR if this is a valid solution.

ygrishajev avatar Jun 01 '22 13:06 ygrishajev

Yeah, if you could file a PR that would be appreciated!

markerikson avatar Jun 29 '22 02:06 markerikson

Yeah, if you could file a PR that would be appreciated!

@markerikson Sure, done. Pls review

ygrishajev avatar Jun 29 '22 04:06 ygrishajev

Unfortunately that one is not ready yet - I'll reopen it here so we don't forget about that :)

phryneas avatar Jun 29 '22 14:06 phryneas