2

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?

benjdan
  • 169
  • 2
  • 6
  • 1
    I would suggest to create a proxy with nextjs API Routes https://nextjs.org/docs/api-routes/introduction and then you can use that proxy into your frontend. With that you should able to get rid of that CORS issue. – Rohman HM Oct 12 '21 at 22:58
  • Thanks, I will look at it. – benjdan Oct 12 '21 at 23:04

1 Answers1

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.

Geoff Taylor
  • 496
  • 3
  • 17