Use Clerk with Fastify
Learn how to use Clerk to easily add authentication focused on security, speed, and DX to your Fastify server.
After following this guide, you should have a working Fastify app with public and private routes, authenticated using the clerkPlugin
and getAuth
helpers.
Set environment variables
Below is an example of an .env.local
file.
Pro tip! If you are signed into your Clerk Dashboard, your secret key should become visible by clicking on the eye icon. Otherwise, you can find your keys in the Clerk Dashboard on the API Keys page.
This examples uses dotenv
to load the environment variables. You can use any other library or method, if you so wish.
Configure clerkPlugin
in your Fastify application
The Clerk plugin can be registered globally or for specific routes. This examples registers the plugin globally.
Accessing auth state using getAuth
The getAuth
helper can be used to access the auth state of the current request.
Require authentication for a route
To protect a route using Clerk, you can use getAuth
to check if the user is authenticated. If the user is not authenticated, you can return a 403 error.
Using Clerk for specific routes only
If you want to use Clerk for specific routes only, you can register the plugin for specific routes. In this example, the routes are split into two groups: one for public routes and one for private routes.
Feedback
Last updated on