This repo shows an example use case for how you can authenticate your Hasura GraphQL service requests using Clerk as an authentication provider.
Clerk is Hiring!
Would you like to work on Open Source software and help maintain this repository? Apply today!
The integration works by using Clerk to generate a JWT to authenticate requests with Hasura. A token with the necessary claims can be created using the Hasura JWT template from your Clerk dashboard and then set as a Bearer token in the Authorization
header of requests to your GraphQL endpoint.
To get a better understanding of the integration, you can check out our documentation on the integration.
To run the example locally you need to:
- Sign up for a Clerk account at https://clerk.dev/.
- Create a Hasura token from your Clerk dashboard and configure the integration.
- Set the required Frontend API variable from your Clerk project and the Hasura GraphQL endpoint as shown in the example env file.
- Set the name of your Hasura JWT template in the
useQuery
hook npm install
the required dependencies.npm run dev
and you are good to go.
After setting the Hasura token and starting the dev server, visit http://localhost:3000/schema
If you see the number of GraphQL schema types, the authenticated request to Hasura has been made successfully. If not, check your browser console and network logs for errors.
useQuery
is a data fetching hook composed with useSWR which sets the fetcher function as graphql-request and includes the Hasura token generated with a Clerk JWT template in the Authorization
header.
To make a GraphQL query with the useQuery
hook, pass your query as the first parameter:
const { data, error } = useQuery(
`{
countries {
code
name
capital
}
}`
);
When performing a mutation, you can pass in variables as the second parameter:
const { error } = useQuery(
`mutation ($country: countries_insert_input = {}) {
insert_countries_one(object: $country) {
code
name
}
}`,
{
country: {
code: "AR",
name: "Argentina",
capital: "Buenos Aires",
},
}
);
If you would like a request to be skipped, pass a truthy value as the third parameter:
const skipQuery = true;
const { data, error } = useQuery(
`{
countries_by_pk(code: 'AR') {
name
}
}`,
null,
skipQuery
);
The query is not executed in this case.
If you need support or have anything you would like to ask, please reach out in our Discord channel. We'd love to chat!