Closed shortcircuit3 closed 4 years ago
Per the example in the readme you can provide a fetchOptionsOverride
function that sets headers directly or enables credentials (ie cookies) based on your desired auth strategy:
// Any GraphQL API can be queried in components, where fetch options for
// the URL, auth headers, etc. are specified. To avoid repetition it’s a
// good idea to import the fetch options override functions for the APIs
// your app uses from a central module. The default fetch options received
// by the override function are tailored to the operation; typically the
// body is JSON but if there are files in the variables it will be a
// FormData instance for a GraphQL multipart request.
fetchOptionsOverride(options) {
options.url = 'https://graphql-pokemon.now.sh';
},
this does not help illustrate how i can add headers...
See comment here on why I'm confused: https://github.com/jaydenseric/graphql-react/issues/30#issuecomment-470391464
headers
is not a validuseGraphQL
option: https://github.com/jaydenseric/graphql-react#function-usegraphql
That comment must be old. I see headers have been added here: https://github.com/jaydenseric/graphql-react#type-graphqlfetchoptions
Indeed; fetchOptionsOverride
is the option you're looking for.
Closing for now. Thank you!
Absolutely!
If you're using Next.js, here is something you may find useful for isomorphically accessing the cookie in your components/hooks:
import { useServerContext } from 'next-server-context';
import React from 'react';
export default function useGetCookie() {
const serverContext = useServerContext();
return React.useCallback(
() =>
typeof window === 'undefined'
? serverContext
? serverContext.request.headers.cookie
: undefined
: document.cookie,
[serverContext]
);
}
Then in your component/hook you can do this sort of thing:
const getCookie = useGetCookie();
const fetchOptionsOverride = (options) => {
options.url = process.env.API_GRAPHQL_URL;
const token = getCookieAccessToken(getCookie());
if (token) options.headers.Authorization = `Bearer ${token}`;
};
Very useful! Thanks!
I'm trying to figure out how I can implement auth between the client and the server with this library. Similar to this: https://www.apollographql.com/docs/react/networking/authentication/
Any leads?