Grafbase
Learn how to integrate Clerk and Grafbase into your application
Getting started
The first step is to create a new application from the Clerk Dashboard if haven’t already done so.
In the sidebar, you'll want to navigate to "JWT Templates" then create a new template. Clerk conventiently provides a Grafbase template which will pre-populate the default claims required.
You can also include additional claims, or modify the template as necessary. Shortcodes are available to make adding dynamic user values easy.
If your GraphQL API restricts access based on groups, you’ll need to specify the users groups in the array above.
Configure Grafbase
You'll next need to configure Grafbase so it knows you want to use Clerk as the OIDC issuer. This can be found in the dashboard under api keys in the advanced section if you didn't grab it from the JWT template
Signed in user authentication
If you want to enable access to your Grafbase data for any signed-in user, then you’ll want to configure your schema with the allow: private
rule:
schema@auth(providers: [{ type: oidc, issuer: "{{ env.ISSUER_URL }}" }]rules: [{ allow: private }]) {query: Query}
Make sure to set the environment variable ISSUER_URL
(using the Grafbase CLI, or Dashboard) to be your Frontend API value found on the Clerk dashboard for your instance.
Group-based authentication
If you’re working with group-based user access then you can use allow: groups
, and provide an array of groups to your schema @auth
rules:
schema@auth(providers: [{ type: oidc, issuer: "{{ env.ISSUER_URL }}" }]rules: [{ allow: groups, groups: ["backend", "admin"] }]) {query: Query}
Make sure to replace YOUR_FRONTEND_API
with the Frontend API value found on the Clerk dashboard for your instance.
If needed, you can also use a shortcode to dynamically include the users current organization's role:
{"groups": ["{{org.role}}"]}
Authenticating requests
You must send OIDC (JWT) tokens using an Authorization: Bearer TOKEN
header. Your token must include the group if using group-based authentication.
The useAuth hook os the easiest way to generate JWTs. Use await getToken({ template: "..." })
and specify your grafbase template to retrieve a new JWT.
1import { useAuth } from '@clerk/nextjs'2import useSWR from 'swr'34export const useQuery = (query, variables) => {5if (!query) {6throw Error('No query provided to `useQuery`')7}89const { getToken } = useAuth()1011const fetcher = async () => {12const token = await getToken({ template: 'grafbase' })13const results = await fetch('YOUR_GRAFBASE_API', {14method: 'POST',15headers: {16'Content-Type': 'application/json',17authorization: `Bearer ${token}`18},19body: JSON.stringify({ query, variables })20}).then(res => res.json())21return results22}23return useSWR(query, fetcher)24}2526const YOUR_GRAPHQL_QUERY = `27query {28__schema {29types {30name31}32}33}34`3536const SchemaPage = () => {37const { data, error } = useQuery(YOUR_GRAPHQL_QUERY)38if (error) {39return <div>error</div>40}41return <pre>{JSON.stringify({ data }, 2, null)}</pre>42}4344export default SchemaPage
1import { useAuth } from '@clerk/nextjs'23export const ApolloProviderWrapper = ({ children }: PropsWithChildren) => {4const { getToken } = useAuth()56const client = useMemo(() => {7const authMiddleware = setContext(async (operation, { headers }) => {8const token = await getToken({ template: 'grafbase' })910return {11headers: {12...headers,13authorization: `Bearer ${token}`14}15}16})1718return new ApolloClient({19link: from([authMiddleware, httpLink]),20cache: new InMemoryCache()21})22}, [getToken])2324return <ApolloProvider client={client}>{children}</ApolloProvider>25}
Need help?
- Get support on our Discord channel