API Routes
The getAuth()
helper retrieves the authentication state allowing you to protect your API routes or gather relevant data.
1import { getAuth } from "@clerk/nextjs/server";2import type { NextApiRequest, NextApiResponse } from 'next'34export default async function handler(req: NextApiRequest, res: NextApiResponse) {5const { userId } = getAuth(req);6// Load any data your application needs for the API route7return res.status(200).json({data})8};
1import { getAuth } from "@clerk/nextjs/server";23export default async function handler(req, res) {4const { userId } = getAuth(req);5// Load any data your application needs for the API route6return res.status(200).json({data});7}
Before Next.js 12.2
You can use withAuth
to retrieve data and use requireAuth
to protect your route automatically while retrieving data.
1import { withAuth } from '@clerk/nextjs/api'2import { NextApiResponse, NextApiRequest } from 'next'3import { ServerGetToken } from '@clerk/types'45//Interface example with Clerk6interface ClerkRequest extends NextApiRequest {7auth: {8userId?: string | null9sessionId?: string | null10getToken: ServerGetToken11}12}1314export default withAuth(async (req: ClerkRequest, res: NextApiResponse) => {15const { userId, sessionId, getToken } = req.auth16// Load any data your application needs for the API route17res.status(200).json({ data })18})
1import { withAuth } from "@clerk/nextjs/api";23export default withAuth(async (req, res) => {4const { userId } = req.auth;5// Load any data your application needs for the API route6res.status(200).json({ data })7});
1import { requireAuth } from '@clerk/nextjs/api'2import { NextApiResponse, NextApiRequest } from 'next'3import { ServerGetToken } from '@clerk/types'45interface ClerkRequest extends NextApiRequest {6auth: {7userId?: string | null8sessionId?: string | null9getToken: ServerGetToken10}11}1213export default requireAuth(async (req: ClerkRequest, res: NextApiResponse) => {14const { userId } = req.auth15// Load any data your application needs for the API route16res.status(200).json({ data})17})
1import { requireAuth } from '@clerk/nextjs/api';23export default requireAuth(async (req, res) => {4const { userId} = req.auth;5// Load any data your application needs for the API route6res.status(200).json({ data })7});
Example Response
{sessionId: 'sess_2GaMqUCB3Sc1WNAkWuNzsnYVVEy',userId: 'user_2F2u1wtUyUlxKgFkKqtJNtpJJWj',orgId: null,getToken: [AsyncFunction (anonymous)],claims: {azp: 'http://localhost:3000',exp: 1666622607,iat: 1666622547,iss: 'https://clerk.quiet.muskox-85.lcl.dev',nbf: 1666622537,sid: 'sess_2GaMqUCB3Sc1WNAkWuNzsnYVVEy',sub: 'user_2F2u1wtUyUlxKgFkKqtJNtpJJWj'}}
More detailed information about the fields in this object can be found in the Authentication Object documentation.