Skip to content

Redux won't add Authorization header to slightly different URL #4722

@Asqit

Description

@Asqit

Greetings redux developers, newbie here!

I am here to ask for help. I have application in next.js@14 and redux-toolkit + Query. Everything works smoothly and is really good, but I have this single query which makes me go crazy. So essentially I have followed the reauth guide and each of my query/mutation will have a Authorization: Bearer <token_please> in headers. That is fine, until we get to the following query and it's second part. I believe it's the URL change that makes it not to follow the desired behaviour, but I am not sure and I have no idea how to resolve this.

getNewLeads: builder.query<Lead, void>({
      async queryFn(_args, _api, _extraOpts, baseFetch) {
        const params = new URLSearchParams();

        // works fine! is authorized and works well
        const existing = await baseFetch(
          apiUrl(
            `/leads/?states=new&states=opened${params.toString() ? '&' + params.toString() : ''}`
          )
        );

        if (!existing.data || !Object.hasOwn(existing.data, 'items')) {
          return { error: existing.error as FetchBaseQueryError };
        }

        const typedExisting = (existing.data as PaginationResponse<RawLead>).items;
        if (Array.isArray(typedExisting) && typedExisting.length !== 0) {
          return {
            data: transformRawLead(typedExisting[0]),
          };
        }

       // This is the part, where we won't have authorized request and so we get 401
        const newLeads = await baseFetch(
          apiUrl(`/get-new-leads${params.toString() ? '?' + params.toString() : ''}`)
        );

        if (!newLeads.data) {
          return { error: newLeads.error as FetchBaseQueryError };
        }

        return {
          data: transformRawLead((newLeads.data as RawLead[])[0]),
        };
      },
    }),

The apiUrl function just appends the dynamic versioning ... /api/v1, /api/v2. To keep this issue short, for now I will not provide my baseQuery and my authorizedBaseQuery as it's litterally the same as is in docs. (+- baseUrl, timeout )

Please, pretty please, help me solve this, I already spent god knows many hours on this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions