'CORS issue fetching data with WPGraphQL and Next.JS

I have created a Next.js app using Wordpress as a CMS and WPGraphQL to fetch data. I have created apollo-client the following way:

  uri: process.env.NEXT_PUBLIC_WP_API_URL,
  headers: {
    'Authorization': process.env.NEXT_PUBLIC_WP_AUTHORIZATION,
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Access-Control-Allow-Credentials': true,    
  },
  credentials: 'include',
  fetchOptions: {
    mode: 'no-cors'
  }
})
const client = new ApolloClient({
    link: httpLink,
    cache: new InMemoryCache()
});

I can fetch data using getStaticProps and getServerSideProps with or without token but when trying with useQuery and a token it doesn't work: I get the data logged in the terminal and my Chrome networks shows a CORS issue. Anyone had experienced it before?



Solution 1:[1]

CORS restrictions are executed solely by your browser. That's why you don't see any issues in queries run on the server, but in the browser is expecting the response to contain the proper headers and if not the response is blocked for reaching the application, what you are currently doing is setting the header is your request but there is nothing to ensure those headers are passed to the response.

I recommend installing the WPGraphQL CORS plugin and configuring it like in the screenshot below.

enter image description here

This will make it so localhost:3000 is properly applied to the 'Access-Control-Allow-Origin' header for GraphQL responses for requests sent from http://localhost:3000.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Geoff Taylor