This is an example application demonstrating GitBook Visitor Authentication on a Next.js and Clerk.dev stack.
You must have an account on Clerk.dev to proceed.
This demo was built using the following framework versions:
- Node v18
- Next.js v13.3
- Clerk v4.16
- Create a new application in Clerk — you can have a free one, for demo purposes — and set it up with a handful of providers: this demo uses GitHub, Google and the Email providers.
- In the API Keys section, choose "Next.js" to retrieve your Clerk API keys.
- Copy the
.env.local.example
to.env.local
and replace the API keys with yours.
Clerk offers JWT templates to customize how tokens are signed. It allows to define the secret key used to sign the token so that GitBook can verify the validity of JWT tokens.
Create a new JWT template:
- Go to your Clerk dashboard.
- In your Clerk application, go to JWT templates.
- Create a new template using the "Blank" template.
- Give your template a name (this demo uses
'GitBook'
). - Enable the "Custom signing key" and select the HS256 algorithm.
- Go to your GitBook space.
- Choose "Share", then "Share to an audience".
- Enable "Publish with visitor authentication".
- Copy the private key.
- Paste that private key in Clerk's JWT template Signing key field.
- Define a simple template (GitBook doesn't give possibility to make use of these fieds for now). For example, in development:
{ "aud": "https://localhost:3000/api/visitor-auth", "user_id": "{{user.id}}", "last_name": "{{user.last_name}}", "first_name": "{{user.first_name}}" }
- Click Apply changes.
- Go back to your GitBook space.
- Go to "Share", then "Share to an audience"
- In the Customize URL section, click Copy published link
- Paste the link to the
.env.local
file in theNEXT_PUBLIC_GITBOOK_URL
variable
This will make sure that you get redirected to the GitBook space once signed in.
Install dependencies and then run the development server:
npm install
npm run dev
- Open http://localhost:3000 with your browser to see the result.
- Sign up for a new account using one of the providers you configured for your Clerk app.
- Sign in using your newly created account,
./pages/api/visitor-auth.ts is the API endpoint used to get the JWT token and redirect to the protected GitBook space defined in the NEXT_PUBLIC_GITBOOK_URL
environment variable. Notice how it makes use of the Clerk JWT template named `GitBookˋ to ensure the signature will match what GitBook expects.
The ./components/Header.tsx and ./pages/index.tsx use the <SignedIn>
and <SignedOut>
Clerk components to adapt the displayed content.
In ./pages/sign-in/[[...index]].tsx, note the afterSignInUrl="/api/visitor-auth"
parameter that is responsible to redirecting directly to the GitBook space after signing in. You can change this however you feel like.
Thanks!