> [!WARNING]
- > `auth.protect()` only works for App Router and is considered experimental.
+ > [`auth.protect()`](/docs/references/nextjs/auth#protect) is only available for App Router, and only works on the server-side.
The following example uses [`auth.protect()`](/docs/references/nextjs/auth#protect) to protect a RSC from unauthenticated and unauthorized access.
@@ -108,14 +121,13 @@ The examples below work for both SSR and CSR. Examples are written for Next.js A
- If the user is authenticated but is not authorized (as in, does not have the `org:team_settings:read` permission), `auth.protect()` will throw a `404` error.
- If the user is both authenticated and authorized, `auth.protect()` will return the user's `userId`.
- ```tsx {{ filename: '/app/dashboard/settings/layout.tsx' }}
- import type { PropsWithChildren } from 'react'
+ ```tsx {{ filename: '/app/dashboard/settings/page.tsx' }}
import { auth } from '@clerk/nextjs/server'
- export default async function SettingsLayout(props: PropsWithChildren) {
+ export default async function Page() {
const { userId } = await auth.protect({ permission: 'org:team_settings:read' })
- return props.children
+ return {userId} is authorized to access this page.
}
```
@@ -131,21 +143,24 @@ The examples below work for both SSR and CSR. Examples are written for Next.js A
import { auth } from '@clerk/nextjs/server'
export default async function ExampleServerComponent() {
- async function myAction(formData: FormData) {
+ async function myServerAction(formData: FormData) {
'use server'
const { has } = await auth()
+ // Check if the user is authorized
const canManage = has({ permission: 'org:team_settings:manage' })
// If has() returns false, the user does not have the correct permissions
+ // You can choose how your app responds. This example returns a 403 error.
if (!canManage)
return Response.json({ error: 'User does not have the correct permissions' }, { status: 403 })
- // Add logic for managing team settings
+ // If the user is both authenticated and authorized, move forward with your logic
+ return users.getTeams(userId)
}
return (
-