This guide will show you how to use Clerk as your authentication provider in an existing Next.js + WunderGraph application.
Configure Clerk
- Go to Clerk (opens in a new tab) and create a new application or use an existing one.
- On your application dashboard to to
API Key - Use the
Quick Copyfor Next.js and copy the.env.local - Create a new
.env.localfile in the root folder (next to thepackage.json) - Paste the credentials into the
.env.localfile - Go to
JWT Templatesand create a newBlanktemplate - Name it
wundergraph - Use the following template: (You can also include other claims as needed)
{
"id": "{{user.id}}",
"email": "{{user.primary_email_address}}",
"lastName": "{{user.last_name}}",
"username": "{{user.username}}",
"firstName": "{{user.first_name}}"
}- Copy the JWKS Endpoint url
Configure WunderGraph
Open wundergraph.config.ts and add a new token-based authentication provider:
// ...
authentication: {
tokenBased: {
providers: [
{
jwksURL: 'https://your-clerk-subdomain.clerk.accounts.dev/.well-known/jwks.json',
},
],
},
},
// ...Configure Next.js
Open pages/_app.tsx and add the useWunderGraphClerk middleware to the withWunderGraph call:
import { Middleware } from 'swr';
import { useAuth } from '@clerk/nextjs';
import { useAuthMiddleware } from '@wundergraph/nextjs';
import { withWunderGraph } from '../components/generated/nextjs';
export const useWunderGraphClerk: Middleware = (useSWRNext) => {
const auth = useAuth();
return useAuthMiddleware(useSWRNext, async () => {
return auth.getToken({ template: 'wundergraph' });
});
};
const App = () => {
// ...
};
export default withWunderGraph(App, {
use: [useWunderGraphClerk],
});That's it! Your WunderGraph application is now protected by Clerk.