Intercom fetch articles with Redux gives CORS error

133 Views Asked by At

I am trying to fetch all articles from our intercom but I keep getting CORS error in local environment.

My API looks like this (the 'hardcodedToken' is our temporarily hardcoded Bearer token for development purposes

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

export const intercomApi = createApi({
  reducerPath: 'intercomApi',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://api.intercom.io/',
    prepareHeaders: (headers) => {
      const accessToken = 'hardcodedToken';
      if (accessToken) {
        headers.set('Authorization', `Bearer ${accessToken}`);
        headers.set('Content-Type', 'application/json; charset=utf-8');
        headers.set('Access-Control-Allow-Origin', '*');
      }
      return headers;
    }
  }),

  tagTypes: ['Article'],
  endpoints: (build) => ({
    getIntercomLatestUpdatesArticles: build.query<Article[], void>({
      query: () => 'articles',
      providesTags: ['Article'],
transformResponse: (response: { results: Article[] }) => {
        const filteredResponse: Article[] = response.results.filter(
          (item: Article) => item.parent_id === 5388628
        );
        return filteredResponse.sort((a, b) => b.id - a.id).slice(0, 2);
      }
  })
});

export const { useGetIntercomLatestUpdatesArticlesQuery } = intercomApi;
export interface Article {
  id: number;
  type: string;
  workspace_id: string;
  parent_id: number | null;
  parent_type: string;
  parent_ids: number[];
  title: string;
  description: string;
  body: string;
  author_id: number;
  url: string;
  state: string;
  tags?: string[];
  created_at?: number;
  updated_at?: number;
}

enter image description here

I tried pretty much everything I could find but I still can't get it to work. I tried deploying it into development environment and it's getting the same error.

Is there something wrong with my api? I do get the data without problem with postman.

1

There are 1 best solutions below

4
Adrian Stanisławski On

This is a problem with your API not with your frontend. Your API needs to be configured to allow calls from different domains. It is working from Postman because Postman does not check if you are allowed to do the call. But browsers do check this. Your API needs to return headers which states what domains are allowed to access it. If they wouldn't check this then any website you enter would be able to call any online API as you as long you are logged in to this API. Thanks to CORS, API can tell the browser which domains really can do requests to it protecting you as a user. So basically, you need to return this header:

Access-Control-Allow-Origin', '*'

but from your API. BTW - such broad access is not a good idea for production environments usually as you probably do not want for any website to be able to call this API.

Example debug settings (not for production) for .NET core (if the API is in the .NET core of course):

 builder.Services.AddCors(o => o.AddDefaultPolicy(
   policy => policy
   .WithExposedHeaders("*")
   .AllowAnyOrigin()
   .AllowAnyHeader()));