Docs

Read session and user data in your Nuxt app with Clerk

Clerk provides composables to access the session and user data in your Nuxt application.

Client-side

useAuth()

The useAuth() composable provides access to the current user's authentication state and methods to manage the active session. You can use this composable to protect pages.

In the following example, the isLoaded property checks if Clerk has finished initializing and the userId property checks if the user is signed in.

pages/protected-page.vue
<script setup>
const { userId, isLoaded } = useAuth()
</script>

<template>
  <div v-if="!isLoaded">Loading...</div>
  <div v-else-if="!userId">Sign in to access this page</div>
  <div v-else>Hello, {{ userId }}!</div>
</template>

useUser()

The useUser() composable provides access to the current user's User object, which holds all of the data for a user of your application and provides a set of methods to manage their account.

In the following example, the isLoaded property checks if Clerk has finished initializing and the isSignedIn property checks if a user is currently signed in.

pages/protected-page.vue
<script setup>
const { isLoaded, isSignedIn, user } = useUser()
</script>

<template>
  <div v-if="!isLoaded">Loading...</div>
  <div v-else-if="!isSignedIn">Sign in to access this page</div>
  <div v-else>Hello, {{ user.firstName }}!</div>
</template>

Server-side

clerkClient()

The clerkClient() helper returns an instance of the JavaScript Backend SDK.

In the following example, the auth object is used to get the userId to check if the user is signed in. The clerkClient() helper retrieves the full User object.

server/api/auth/index.ts
import { clerkClient } from '@clerk/nuxt/server'

export default defineEventHandler(async (event) => {
  const { userId } = event.context.auth

  // Check if the user is signed in
  if (!userId) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized: No user ID provided',
    })
  }

  // Retrieve the user data
  const user = await clerkClient(event).users.getUser(userId)
  return user
})

Feedback

What did you think of this content?

Last updated on