getAuth()
The getAuth()
helper retrieves authentication state from the request object.
- 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 variableCLERK_SECRET_KEY
.
Returns
getAuth()
returns the Auth
object. See the Auth
reference 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 clerkClient.users.getUser()
to get the current user's User
object. If not authenticated, the request is rejected with a 401
status code.
See more detailed examples in the dedicated guide.
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
Last updated on