The Clerk Nuxt SDK gives you access to prebuilt components, composables, and helpers to make user authentication easier. Refer to the quickstart guideNuxt.js Icon to get started.
To configure Clerk with Nuxt, you must pass the @clerk/nuxt module to your Nuxt config in your nuxt.config.ts file. See the referenceNuxt.js Icon for more information on configuring the module, including setting Clerk options like signInForceRedirectUrl.
The Auth object is available at event.context.auth() in your event handlers. This JavaScript object contains important information like session data, your user's ID, as well as their Organization ID. Learn moreClerk Icon.
The following example uses event.context.auth() to protect the route based on token type:
It accepts any token type (acceptsToken: 'any') from the request.
If the token is a session_token, it logs that the request is from a user session.
Otherwise, it logs that the request uses a machine token and specifies its type.
exportdefaulteventHandler((event) => {// Use `event.context.auth()` to protect a route based on token typeconstauthObject=event.context.auth({ acceptsToken:'any' })if (authObject.tokenType ==='session_token') {console.log('This is a session token from a user') } else {console.log(`This is a ${authObject.tokenType} token`) }return {}})
Clerk's JS Backend SDKClerk Icon is a wrapper around the Backend API that makes it easier to interact with the API. For example, to retrieve a list of all users in your application, you can use the users.getUserList() method from the JS Backend SDK instead of manually making a fetch request to the https://api.clerk.com/v1/users endpoint.
To access a resource, you must first instantiate a clerkClient instance. See the reference documentationClerk Icon for more information.
To protect pages, use the useAuth() helper to protect a single page, or use it with defineNuxtRouteMiddleware() alongside the createRouteMatcher() helper to protect multiple pages. Learn more.
To protect API routes (/api/**), use the clerkMiddleware() helper. Learn moreNuxt.js Icon.
Quiz
When protecting pages/routes using middleware, what is the difference between using defineNuxtRouteMiddleware() and clerkMiddleware()? Why not use one or the other?
defineNuxtRouteMiddleware() is used to protect pages only and cannot protect API routes. clerkMiddleware() is used to protect API routes. It can protect pages, but on initial page reload only. On subsequent navigations, it won't be triggered because client-side navigation will bypass the middleware.