Unverified Commit 8c271102 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

Update Next.js auth docs examples (#86361)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?
Updated the `Layouts and auth checks` section in the authentication
documentation (`docs/01-app/02-guides/authentication.mdx`).

### Why?
The previous example demonstrating authentication checks within layouts
was confusing and contradicted the documentation's own advice against
this pattern. This update aims to provide clearer, recommended
approaches for implementing authentication checks.

### How?
- Removed the misleading layout-based authentication example.
- Introduced a new subsection with an example showing authentication
checks in a page component.
- Added another new subsection with an example demonstrating
authentication checks in a leaf component.
- Enhanced the "Good to know" section with a reminder about the
necessity of authorization checks for Server Actions.

Closes NEXT-
Fixes #

-->

---
[Slack
Thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1763685748449029?thread_ts=1763685748.449029&cid=C03KAR5DCKC)

<a
href="https://cursor.com/background-agent?bcId=bc-f490a8eb-8f55-4a85-a31a-357adb24c09a"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/open-in-cursor-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/open-in-cursor-light.svg"><img alt="Open in
Cursor"
src="https://cursor.com/open-in-cursor.svg"></picture></a>&nbsp;<a
href="https://cursor.com/agents?id=bc-f490a8eb-8f55-4a85-a31a-357adb24c09a"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/open-in-web-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/open-in-web-light.svg"><img alt="Open in Web"
src="https://cursor.com/open-in-web.svg"></picture></a>
Co-authored-by: 's avatarCursor Agent <cursoragent@cursor.com>
parent 5bbcd7d2
...@@ -1355,51 +1355,96 @@ For example, consider a shared layout that fetches the user data and displays th ...@@ -1355,51 +1355,96 @@ For example, consider a shared layout that fetches the user data and displays th
This guarantees that wherever `getUser()` is called within your application, the auth check is performed, and prevents developers forgetting to check the user is authorized to access the data. This guarantees that wherever `getUser()` is called within your application, the auth check is performed, and prevents developers forgetting to check the user is authorized to access the data.
```tsx filename="app/layout.tsx" switcher #### Auth checks in page components
export default async function Layout({
children, For example, in a dashboard page, you can verify the user session and fetch the user data:
}: {
children: React.ReactNode; ```tsx filename="app/dashboard/page.tsx" switcher
}) { import { verifySession } from '@/app/lib/dal'
const user = await getUser();
export default async function DashboardPage() {
const session = await verifySession()
// Fetch user-specific data from your database or data source
const user = await getUserData(session.userId)
return ( return (
// ... <div>
<h1>Welcome, {user.name}</h1>
{/* Dashboard content */}
</div>
) )
} }
``` ```
```jsx filename="app/layout.js" switcher ```jsx filename="app/dashboard/page.jsx" switcher
export default async function Layout({ children }) { import { verifySession } from '@/app/lib/dal'
const user = await getUser();
export default async function DashboardPage() {
const session = await verifySession()
// Fetch user-specific data from your database or data source
const user = await getUserData(session.userId)
return ( return (
// ... <div>
<h1>Welcome, {user.name}</h1>
{/* Dashboard content */}
</div>
) )
} }
``` ```
```ts filename="app/lib/dal.ts" switcher #### Auth checks in leaf components
export const getUser = cache(async () => {
You can also perform auth checks in leaf components that conditionally render UI elements based on user permissions. For example, a component that displays admin-only actions:
```tsx filename="app/ui/admin-actions.tsx" switcher
import { verifySession } from '@/app/lib/dal'
export default async function AdminActions() {
const session = await verifySession() const session = await verifySession()
if (!session) return null const userRole = session?.user?.role
// Get user ID from session and fetch data if (userRole !== 'admin') {
}) return null
}
return (
<div>
<button>Delete User</button>
<button>Edit Settings</button>
</div>
)
}
``` ```
```js filename="app/lib/dal.js" switcher ```jsx filename="app/ui/admin-actions.jsx" switcher
export const getUser = cache(async () => { import { verifySession } from '@/app/lib/dal'
export default async function AdminActions() {
const session = await verifySession() const session = await verifySession()
if (!session) return null const userRole = session?.user?.role
// Get user ID from session and fetch data if (userRole !== 'admin') {
}) return null
}
return (
<div>
<button>Delete User</button>
<button>Edit Settings</button>
</div>
)
}
``` ```
This pattern allows you to show or hide UI elements based on user permissions while ensuring the auth check happens at render time in each component.
> **Good to know:** > **Good to know:**
> >
> - A common pattern in SPAs is to `return null` in a layout or a top-level component if a user is not authorized. This pattern is **not recommended** since Next.js applications have multiple entry points, which will not prevent nested route segments and Server Actions from being accessed. > - A common pattern in SPAs is to `return null` in a layout or a top-level component if a user is not authorized. This pattern is **not recommended** since Next.js applications have multiple entry points, which will not prevent nested route segments and Server Actions from being accessed.
> - Ensure that any Server Actions called from these components also perform their own authorization checks, as client-side UI restrictions alone are not sufficient for security.
### Server Actions ### Server Actions
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment