Apollo+React: How do I use a proxy so client and graphql are on the same domain?

Viewed 2678

I am following an (excellent) security tutorial by Ryan Chenkie, but trying to use a graphql api rather than a REST api which he uses.

The graphql server is running on localhost:4000 and the Apollo-React client is on localhost:3000. It works fine.

Now, I want to use a cookie for the auth token, so I need client and server to be on the same domain. Per Chenkie's recommendation I set up a proxy on the client in package.json

"proxy": "http://localhost:4000/"

then in my index.js, where apollo client is set up, I create an httplink as follows:

const link = createHttpLink({
  uri: "http://localhost:3000", 
  headers: { authorization: token },  // The token in the auth header will be removed when the cookie approach is working)
});

For the uri I have tried the following:

  uri: "http://localhost:3000"
  uri: "/graphql"
  uri: "/"
  uri: ""

I always get a 404 error. Any idea what I am doing wrong?

Thanks for your help.

2 Answers

Dumb mistake on my part. Solution: You must manually stop and restart the client-side react server for the proxy to take effect. Just saving a file is not sufficient.

Also, the HttpLink uri: "/graphql" is the correct one. It works as expected (when you restart the react server!)

In the proxy section in your package.json you have to add the base url of the server that you want to proxy, in your case the GraphQL server aka http://localhost:4000.

When creating the link, add the endpoint under which GraphQL accepts the requests, usually that is /graphql but you'll have to make sure.

So that'd be:

const link = createHttpLink({
  uri: "/graphql", 
  headers: { authorization: token },  // The token in the auth header will be removed when the cookie approach is working)
});

This means that every relative request will be proxied towards localhost:4000 and for your HTTPLink that it will use http://localhost:4000/graphql.

If you still get the 404 make sure that your graphql server is running and that the graphql endpoint is indeed /graphql.

Related