Protect server endpoints
A Route Handler needs to reject requests from users who are not signed in.
Clerk · Function
auth() provides the current authentication context for Next.js App Router server code. It exposes the Auth object, route-protection capabilities, and a sign-in redirect helper.
In a Next.js App Router server context, call auth() to obtain the active request's Auth object and redirectToSignIn() helper. Inspect its authentication data, use protect() for authentication or authorization checks, and use getToken() when a session token or custom JWT must be sent to another server.
await auth()| Name | Type | Description |
|---|---|---|
| | No parameters are documented for the auth() helper. |
A promise resolving to the Auth object and a redirectToSignIn() method.
import { auth } from '@clerk/nextjs/server'
export async function GET() {
const { isAuthenticated, userId } = await auth()
if (!isAuthenticated) {
return new Response('Unauthorized', { status: 401 })
}
return Response.json({ userId })
}This Route Handler reads the server-side auth state and returns the authenticated user's ID, or a 401 response when no user is signed in.
A Route Handler needs to reject requests from users who are not signed in.
A Server Component needs the current user's authentication state.
A server request must call an external API on behalf of the current session.
A route needs to enforce roles, permissions, features, or plans.
auth() is a server-side App Router helper that returns the current Auth object and a redirectToSignIn() method. The Auth object exposes the current authentication state and methods such as protect() and getToken().
Follow-up: How would you protect an endpoint without redirecting? Check isAuthenticated and return an HTTP 401 response, or use protect() with behavior appropriate for the endpoint.
Use auth().isAuthenticated to determine whether a signed-in user exists. For more complete access rules, use the returned protect() method to enforce authentication or authorization.
Follow-up: How can authorization be enforced? Pass the relevant authorization requirements to protect(), such as a role, permission, feature, or plan.
Use getToken() when a server must forward the current session token or a custom JWT template to another API. It retrieves the token associated with the current authentication context.
Follow-up: What changes for machine-authenticated requests? The Auth object reflects machine-level authentication data rather than ordinary user-session details.
protect()redirectToSignIn()getToken()isAuthenticatedclerkMiddleware()Auth object