auth()
The auth()
helper returns the Authentication
object of the currently active user. This is the same Authentication
object that is returned by the getAuth()
hook. However, it can be used in Server Components, Route Handlers, and Server Actions.
The auth()
helper does require Middleware.
Return type of auth()
auth()
returns the Auth
object with a few extra properties:
protect()
You can use the protect()
helper to check if a user is authorized to access something, such as a component or a route handler.
protect()
will return the Authentication
object if the user is authorized. If the user is not authorized, it will throw a notFound
Next.js error.
auth().protect()
only works for App Router and is considered experimental.
You can use the protect()
helper in two ways:
- to check if a user is authenticated
- to check if a user is authorized to access something, such as a component or a route handler
protect()
will return the Authentication
object if the user is authenticated or authorized. If the user is not authenticated or authorized, protect()
will redirect the user to the sign-in page or to a custom URL that you provide as a parameter.
protect()
accepts the following parameters:
Name | Type | Description |
---|---|---|
role? | string | The role to check for. |
permission? | string | The permission to check for. |
has? | (isAuthorizedParams: CheckAuthorizationParamsWithCustomPermissions) => boolean | A function that returns a boolean based on the permission or role provided as parameter. Can be used for authorization. See the dedicated has() section for more information. |
unauthorizedUrl? | string | The URL to redirect the user to if they are not authorized. |
unauthenticatedUrl? | string | The URL to redirect the user to if they are not authenticated. |
redirectToSignIn()
redirectToSignIn()
is a method that redirects the user to the sign-in page. It accepts the following parameters:
Name | Type | Description |
---|---|---|
returnBackUrl? | string | URL | The URL to redirect the user back to after they sign in. |
Use auth()
to retrieve userId
app/page.tsximport { auth } from '@clerk/nextjs/server'; export default function Page() { const { userId } : { userId: string | null } = auth(); // ... }
Use auth()
for data fetching
When using a Clerk integration, or if you need to send a JWT along to a server, you can use the getToken
function.
app/api/example/route.tsimport { auth } from '@clerk/nextjs/server'; export async function GET() { const {userId, getToken} = auth(); if(!userId){ return new Response("Unauthorized", { status: 401 }); } try { const token = await getToken({template: "supabase"}); // Add logic here to fetch data from Supabase and return it. const data = { supabaseData: 'Hello World' }; return Response.json({ data }); } catch (error) { return Response.json(error); } }
Use auth()
to check if a user is authenticated
auth().protect()
can be used in a layout.tsx
file to protect the entire route, including all children.
In the following example,
- the
protect()
helper is used to check if a user visiting any/dashboard
route is authenticated. - If the user is not authenticated, they will be redirected to the sign-in route.
- If the user is authenticated, they can view any
/dashboard
route and its children.
app/dashboard/layout.tsximport { auth } from '@clerk/nextjs/server' export default async function Layout({ children }:{ children: React.ReactNode }){ auth().protect() return <>{children}</> }
Use auth()
to check if a user is authorized
auth()
returns the Auth
object, which includes the has()
helper. auth()
also returns the protect()
helper.
has()
and protect()
can be used to check if a user is authorized to access certain parts of your application.
Use has()
to check if a user is authorized
Use the has()
helper in order to check if a user is authorized to access a component.
In the following example:
has()
is used to check if a user has theorg:team_settings:manage
permission.- If the user does not have the permission,
null
is returned. - If the user has the permission, the component will return the "Team Settings" heading.
app/page.tsximport { auth } from '@clerk/nextjs/server'; export default async function Page() { const { has } = auth(); const canManage = has({ permission:"org:team_settings:manage" }); if(!canManage) return null; return <h1>Team Settings</h1> }
Use protect()
to check if a user is authorized
Use the protect()
helper to protect a route handler from unauthorized access.
auth().protect()
only works for App Router and is considered experimental.
In the following example:
protect()
helper is used to check if a user is authorized to access a route handler.- If the user is not authorized, the
protect()
helper will redirect the user to the sign-in route. - If the user is authorized, the
protect()
helper will return theAuthentication
object, which has theuserId
property.
app/api/route.tsimport { auth } from "@clerk/nextjs/server"; export const POST = () => { const { userId } = auth().protect({ permission: "org:team_settings:manage" }); return users.createTeam(userId); }
Use auth()
to check your current user's role
In some cases, you need to check your user's current organization role before displaying data or allowing certain actions to be performed.
Check the current user's role with the orgRole
property of the Authentication
object returned by auth()
, as shown in the following example:
app/page.tsximport { auth } from '@clerk/nextjs/server'; export default async function Page() { const { orgRole } = auth(); return ( <> <div>Your current role is {orgRole}</div> </> ) }
Last updated on March 1, 2024