Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

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.

1
import { useAuth } from '@clerk/nextjs'
2
import useSWR from 'swr'
3
4
export const useQuery = (query, variables) => {
5
if (!query) {
6
throw Error('No query provided to `useQuery`')
7
}
8
9
const { getToken } = useAuth()
10
11
const fetcher = async () => {
12
const token = await getToken({ template: 'grafbase' })
13
const results = await fetch('YOUR_GRAFBASE_API', {
14
method: 'POST',
15
headers: {
16
'Content-Type': 'application/json',
17
authorization: `Bearer ${token}`
18
},
19
body: JSON.stringify({ query, variables })
20
}).then(res => res.json())
21
return results
22
}
23
return useSWR(query, fetcher)
24
}
25
26
const YOUR_GRAPHQL_QUERY = `
27
query {
28
__schema {
29
types {
30
name
31
}
32
}
33
}
34
`
35
36
const SchemaPage = () => {
37
const { data, error } = useQuery(YOUR_GRAPHQL_QUERY)
38
if (error) {
39
return <div>error</div>
40
}
41
return <pre>{JSON.stringify({ data }, 2, null)}</pre>
42
}
43
44
export default SchemaPage
1
import { useAuth } from '@clerk/nextjs'
2
3
export const ApolloProviderWrapper = ({ children }: PropsWithChildren) => {
4
const { getToken } = useAuth()
5
6
const client = useMemo(() => {
7
const authMiddleware = setContext(async (operation, { headers }) => {
8
const token = await getToken({ template: 'grafbase' })
9
10
return {
11
headers: {
12
...headers,
13
authorization: `Bearer ${token}`
14
}
15
}
16
})
17
18
return new ApolloClient({
19
link: from([authMiddleware, httpLink]),
20
cache: new InMemoryCache()
21
})
22
}, [getToken])
23
24
return <ApolloProvider client={client}>{children}</ApolloProvider>
25
}

Need help?

Was this helpful?

Clerk © 2023