Skip to main content
Docs

getAuth()

The getAuth() helper retrieves authentication state from the request object.

Note

If you are using App Router, use the instead.

  • Name
    req
    Description

    The Next.js request object.

  • Name
    opts?
    Description

    An optional object that can be used to configure the behavior of the getAuth() function. It accepts the following properties:

    • secretKey?: A string that represents the Secret Key used to sign the session token. If not provided, the Secret Key is retrieved from the environment variable CLERK_SECRET_KEY.

Returns

getAuth() returns the Auth object. See the for more information.

Usage

The following example uses getAuth() to protect a route and load the user's data. If the user is authenticated, their userId is passed to to get the current user's object. If not authenticated, the request is rejected with a 401 status code.

See more detailed examples in the .

pages/api/auth.ts
import { getAuth, clerkClient } from '@clerk/nextjs/server'
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  // Use getAuth() to get the user's ID
  const { userId } = getAuth(req)

  // Protect the route by checking if the user is signed in
  if (!userId) {
    return res.status(401).json({ error: 'Unauthorized' })
  }

  // Initialize the Backend SDK
  const client = await clerkClient()

  // Get the user's full Backend User object
  const user = await client.users.getUser(userId)

  return res.status(200).json({ user })
}

Feedback

What did you think of this content?

Last updated on