Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.com

getAuth()

The getAuth() helper retrieves the authentication state, allowing you to protect your API routes or gather relevant data.

If you are using App Router, use the auth() helper instead.

Returns

getAuth() returns the Auth object.

Usage

Basic usage

The following example demonstrates how to use getAuth() to retrieve authentication information in an API route.

app/api/example/route.ts
import { getAuth } from "@clerk/nextjs/server"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { userId } = getAuth(req); // Add logic that retrieves the data for the API route return res.status(200).json({ userId: userId }); }

Protect API routes

It is important to protect your API routes to ensure that only authenticated users can access them. You can do this by checking if the userId is present in the getAuth() response, like in the following example:

app/api/example/route.ts
import { getAuth } from "@clerk/nextjs/server"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { userId } = getAuth(req); if (!userId) { return res.status(401).json({ error: "Not authenticated" }); } // Add logic that retrieves the data for the API route return res.status(200).json({ userId: userId }); }

Usage with getToken()

getAuth() returns getToken(), which is a method that returns the current user's session token. You can also use this function to retrieve a custom JWT template, like in the following example:

app/api/example/route.ts
import { getAuth } from "@clerk/nextjs/server"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { getToken } = getAuth(req); const token = await getToken({ template: "supabase" }); // Add logic that retrieves the data // from your database using the token return res.status(200).json({}); }

Usage with clerkClient

clerkClient is used to access the Backend SDK, which exposes Clerk's backend API resources. You can use getAuth() to pass authentication information that many of the Backend SDK methods require, like in the following example:

app/api/example/route.ts
import { clerkClient, getAuth } from "@clerk/nextjs/server"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { userId } = getAuth(req); const user = userId ? await clerkClient.users.getUser(userId) : null; return res.status(200).json({}); }

Last updated on April 22, 2024

What did you think of this content?

Clerk © 2024