Authentication and Authorization

Grafbase supports connecting an identity providers, and using API keys to authenticate, and authorize API requests.

You can configure the providers and rules inside of your schema using the @auth directive.

This is the default authorization strategy. We recommend using it for APIs you want to make public, when prototyping, or developing your APIs.

Your API key must be sent with all requests as a header in the format of x-api-key: YOUR_API_KEY.

curl \
-X POST \
-H "content-type: application/json" \
-H "x-api-key: GRAFBASE_API_KEY" \
-d '{"query":"{ __schema { types { name } } }"}' \
"GRAFBASE_API_URL"

You can manage API keys from your project settings.

You can access data using a valid JWT token from a configued identity provider (IdP).

Your JWT token must be sent with all requests as a header in the format of authorization: Bearer TOKEN.

import { useAuth } from '@clerk/nextjs'
import useSWR from 'swr'

export const useQuery = (query, variables) => {
  if (!query) {
    throw Error('No query provided to \`useQuery\`')
  }

  const { getToken } = useAuth()

  const fetcher = async () => {
    const token = await getToken({ template: 'grafbase' })
    const results = await fetch('GRAFBASE_API_URL', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: \`Bearer ${token}\`
      },
      body: JSON.stringify({ query, variables })
    }).then(res => res.json())
    return results
  }
  return useSWR(query, fetcher)
}

const YOUR_GRAPHQL_QUERY = \`
	query {
		__schema {
			types {
				name
			}
		}
	}
\`

const SchemaPage = () => {
  const { data, error } = useQuery(YOUR_GRAPHQL_QUERY)
  if (error) {
    return <div>error</div>
  }
  return <pre>{JSON.stringify({ data }, 2, null)}</pre>
}

export default SchemaPage
Was this page helpful?