Clerk integration

This guide covers how to configure Clerk as an access provider for a Fauna database.

Once set up, end users can log in to Clerk to create a JWT for your client application. Your application can use the JWT as an authentication secret to run queries on the user’s behalf.

Before you start

To complete this guide, you’ll need:

Get the Clerk Frontend API URL and JWKS

  1. In the Clerk Dashboard, navigate to the API keys page.

  2. Click Show API URLs.

  3. Copy and save the Frontend API URL.

    Clerk Frontend API URL

  4. On the API keys page, click Show JWT public key. Copy and save the JWKS URL.

    Clerk JWKS URL

    You’ll use the URLs later in the guide.

Configure Fauna

  1. Log in to the Fauna Dashboard and select your database.

  2. Select the Access Providers tab and click Create Access Provider.

  3. Enter a Name for the access provider, such as Clerk.

  4. Copy and save the Audience URL. You’ll use the URL later in the guide.

  5. In Issuer, paste the Clerk Frontend API URL you copied earlier. Do not include a trailing slash (/).

  6. In JWKS Endpoint, paste the Clerk JWKS URL you copied earlier.

  7. Click Create.

  8. Click the access provider you created to access its FSL schema.

  9. Update the schema to include a user-defined role:

    access provider Clerk {
      ...
    
      // Adds a user-defined role to JWTs created by the access provider.
      role <role>
    }

    Don’t change the values of the issuer or jwks_uri fields.

  10. Click Save.

Create a JWT template in Clerk

  1. In the Clerk Dashboard, navigate to the JWT templates page.

  2. Click New template and select Fauna.

  3. Enter a Name for the template, such as fauna.

  4. In the Claims section, set the aud claim to the audience URL you copied earlier.

  5. Click Save.

Authenticate queries in an application

You can now use the JWT template to create Fauna JWTs in Clerk. You can use the JWTs to authenticate with Fauna as an end user. For example:

import React from 'react';
import { useAuth } from '@clerk/nextjs';
import { Client, fql } from "fauna";

const Example = () => {
  const { getToken } = useAuth();
  const [message, setMessage] = React.useState('');

  const makeQuery = async () => {
    let client;
    try {
      const secret = await getToken({ template: '<CLERK_JWT_TEMPLATE_NAME>' });
      client = new Client({ secret: secret });
      const response = await client.query(fql`'Hello World!'`);
      setMessage(response);
    } catch (error) {
      console.error(error);
      setMessage('Error occurred');
    } finally {
      if (client) client.close();
    }
  }

  return (
    <>
      <button onClick={makeQuery}>Make authenticated query</button>
      <p>Message: {message}</p>
    </>
  );
};

export default Example;

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!