How can I use Redux RTK Query with aws API or integrate RTX with Aws cognito json Tokens?

Viewed 10

I'm trying to integrate RTK Query with aws API requests. I don't need to use api requests per say but I need to use the authentication that is provided by Cognito.

I tried to integrate this way, but apparently the token is not added :


import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

// Define a service using a base URL and expected endpoints
export const researchApi = createApi({
    reducerPath: 'researchApi',
    
    baseQuery: fetchBaseQuery({ baseUrl: process.env.NEXT_PUBLIC_API_RESEARCH }),

    prepareHeaders: async (headers) => {
        headers.set('Authorization', (await Auth.currentSession()).getIdToken().getJwtToken());
        return headers;
    },

    endpoints: (builder) => ({
      getResearch: builder.query({
        query: () => `research`,
      }),
    }),
  })
  
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetResearchQuery } = researchApi

Any idea how to make the two work together ? Either with aws API to send requests, or a way to pass the json token to the request would work also.

Cheers !

1 Answers

So I was doing the prepareHeaders wrong, here's some working code :

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { Auth, API, Storage } from 'aws-amplify';

// Define a service using a base URL and expected endpoints
export const researchApi = createApi({
    reducerPath: 'researchApi',
    
    baseQuery: fetchBaseQuery({ 
        baseUrl: process.env.NEXT_PUBLIC_API_RESEARCH,
        prepareHeaders: async (headers, { getState }) => {
            const token = (await Auth.currentSession()).getIdToken().getJwtToken();
            headers.set('Authorization', `${token}`);            
            return headers;
        }
    }),
    endpoints: (builder) => ({
      getResearch: builder.query({
        query: () => `research`,
      }),
    }),
  })
  
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetResearchQuery } = researchApi


Related