getAuth()
The getAuth()
helper retrieves the authentication state, allowing you to protect your API routes or gather relevant data. The variables available in the response can be found here.
Usage
Basic usage
pages/api/example.tsimport { getAuth } from "@clerk/nextjs/server"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const { userId } = getAuth(req); // Load any data your application needs for the API route return res.status(200).json({ userId: userId }); }
Protecting 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.
pages/api/example.tsimport { 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" }); } // Load any data your application needs for the API route return res.status(200).json({ userId: userId }); }
Usage with getToken
The getToken()
function returns a promise that resolves to the current user's session token. You can also use this function to retrieve a custom JWT template.
pages/api/example.tsimport { 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" }); // Retrieve the data from your database return res.status(200).json({}); }
Usage with clerkClient
The clerkClient
allows you to access the Clerk API. You can use this to retrieve or update data.
pages/api/example.tsimport { clerkClient } from "@clerk/nextjs"; 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); const user = userId ? await clerkClient.users.getUser(userId) : null; return res.status(200).json({}); }