Nhost
Learn how to integrate Clerk into your Nhost project
Getting started
You can connect your Clerk-authenticated application to a Hasura GraphQL endpoint within minutes.
The first step is to navigate to JWT Templates from the Clerk Dashboard. Click on the button to create a New Template based on Nhost.
This will pre-populate the default claims required by Nhost and Hasura. You can include additional claims or modify them as necessary. Shortcodes are also available to make adding dynamic user values easy.
By default, Clerk will sign the JWT with a private key automatically generated for your application, which is what most developers use for Nhost. If you so choose, you can customize this key.
Configure Nhost
The next step is to provide Nhost with the public keys used to verify the JWT issued by Clerk. Assuming you didn’t use a custom key, this can be done by using a JSON Web Key Set (JWKS), which Clerk automatically creates an endpoint for with your Frontend API (https://<YOUR_FRONTEND_API>/.well-known/jwks.json
).
From your Clerk JWT template screen, find the JWKS Endpoint input and click to Copy the endpoint.
From your Nhost dashboard, navigate to Settings → Environment Variables.
Find the NHOST_JWT_SECRET
key and click to Edit the value.
{"jwk_url":"https://{{fapi}}/.well-known/jwks.json"}
Replace the URL with the JWKS endpoint you copied from your JWT template.
With Custom Signing Key
If you used a custom signing key, instead of providing the jwk_url
you need to provide the algorithm type
and key
as JSON object in the NHOST_JWT_SECRET
field.
{"type": "HS256", "key": "<YOUR_SIGNING_KEY>" }
Don't forget to click Apply Changes to save your JWT template.
Configure the providers
Both Nhost and Clerk have Provider components that are required to wrap your React application to provide the authentication context.
This is how you would set up a Next.js application using both Providers:
1import { NhostNextProvider, NhostClient } from '@nhost/nextjs';2import {3ClerkProvider,4RedirectToSignIn,5SignedIn,6SignedOut7} from '@clerk/nextjs';891011const nhost = new NhostClient({12subdomain: process.env.NEXT_PUBLIC_NHOST_SUBDOMAIN || '',13region: process.env.NEXT_PUBLIC_NHOST_REGION || ''14});1516function MyApp({ Component, pageProps }) {17return (18<NhostNextProvider nhost={nhost} initial={pageProps.nhostSession}>19<ClerkProvider {...pageProps}>20<SignedIn>21<Component {...pageProps} />22</SignedIn>23<SignedOut>24<RedirectToSignIn />25</SignedOut>26</ClerkProvider>27</NhostNextProvider>28);29}3031export default MyApp;
Configure your GraphQL client
GraphQL clients (such as Apollo Client and Relay) can help with querying and caching your data. They can also manage UI state, keep data in sync, and boost performance. GraphQL requests can be to the Hasura backend using different clients.
The last step of integrating Clerk as the modern web authentication solution for Hasura is to pass the JWT in the Authorization
header with your requests. You can access the token generated with the Hasura claims by calling getToken({ template: <your-template-name> })
on the Session object with the name of your template.
Even if you don’t have a database table set up yet, we can make use of the built-in GraphQL introspection system to validate that the authenticated requests are working properly.
Here is an example of using Apollo Client in conjunction with the useAuth
hook in a Next.js application to make a request to the Hasura GraphQL endpoint:
1import {2ApolloProvider,3ApolloClient,4HttpLink,5from,6InMemoryCache,7} from "@apollo/client";8import { setContext } from "@apollo/client/link/context";9import { useAuth } from "@clerk/nextjs";1011export const ApolloProviderWrapper = ({ children }) => {12const { getToken } = useAuth();13const apolloClient = useMemo(() => {14const authMiddleware = setContext(async (req, { headers }) => {15const token = await user.getToken({template: "template"});16return {17headers: {18...headers,19authorization: `Bearer ${token}`,20},21};22});2324const httpLink = new HttpLink({25uri: process.env.GRAPHQL_URI,26});2728return new ApolloClient({29link: from([authMiddleware, httpLink]),30cache: new InMemoryCache(),31});32}, [getToken])3334return <ApolloProvider client={apolloClient}>{children}</ApolloProvider>;35};
As an alternative, here is an example of using Fetch API in conjunction with the useSWR
hook in a Next.js application to make a request to the Hasura GraphQL endpoint:
pages/index.jsimport { useAuth } from '@clerk/nextjs';import useSWR from 'swr';export default function Home() {const { getToken } = useAuth();const subdomain = process.env.NEXT_PUBLIC_NHOST_SUBDOMAIN;const endpoint = `https://${subdomain}.nhost.run/v1/graphql`;const query = `query { __schema { types { name } } }`;const fetcher = async (...args) =>fetch(...args, {method: 'POST',headers: {'Content-Type': 'application/json',Accept: 'application/json',Authorization: `Bearer ${await getToken({ template: 'nhost' })}`},body: JSON.stringify({ query })}).then(res => res.json());const { data } = useSWR(endpoint, fetcher);return <p>GraphQL schema has {data?.data?.__schema.types.length} types</p>;}
Note that the getToken({ template: <your-template-name> })
call is asynchronous and returns a Promise that needs to be resolved before accessing the token value. This token is short-lived for better security and should be called before every request to your GraphQL API. The caching and refreshing of the token is handled automatically by Clerk.