Steams / ra-data-hasura-graphql

React-admin data provider for Hasura GraphQL endpoints
MIT License
211 stars 33 forks source link

How do I add headers #72

Open dbrosy opened 3 years ago

dbrosy commented 3 years ago

I'm trying the following code but headers option doesn't work

const App = () => {
  const [dataProvider, setDataProvider] = React.useState<any>(undefined);

  React.useEffect(() => {
    (async () => {
      const dp = await buildHasuraProvider({
        clientOptions: {
          uri: hasuraUrl,
          headers: {
            "x-hasura-admin-secret": "hasuraSecret",
          },
        },
      });
      setDataProvider(() => dp);
    })();
  }, []);

the uri works but not headers

Error:

Error: GraphQL error: x-hasura-admin-secret/x-hasura-access-key required, but not found

what is the correct syntax for headers?

cpv123 commented 3 years ago

@dbrosy you can supply the client instance directly, instead of the client options. It is shown here in the README: https://github.com/Steams/ra-data-hasura-graphql#adding-authentication-headers

You probably want something like this:

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: hasuraUrl,
  cache: new InMemoryCache(),
  headers: {
    'x-hasura-admin-secret': 'hasuraSecret',
  },
});

const App = () => {
  const [dataProvider, setDataProvider] = React.useState<any>(undefined);

  React.useEffect(() => {
    (async () => {
      const dp = await buildHasuraProvider({ client 
});
      setDataProvider(() => dp);
    })();
  }, []);

Alternatively, you can stick with just client options but you'll have to build them like this

import { createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const authLink = setContext((_, { headers }) => ({
  headers: {
    ...headers,
    'x-hasura-admin-secret': hasuraSecret,
  },
}));

const httpLink = createHttpLink({
  uri: hasuraUrl,
});

const clientOptions = {
  link: authLink.concat(httpLink),
};

and then pass clientOptions as you did in your example.