Commit ca8c5e7e authored by Zack Tanner's avatar Zack Tanner

support `cause` in Next.js error signals

parent c291ff6b
...@@ -67,6 +67,45 @@ export default async function AdminPage() { ...@@ -67,6 +67,45 @@ export default async function AdminPage() {
} }
``` ```
You can also pass an error cause to `forbidden` to handle different types of errors before escalating to the Next.js' error page. For example, you can call `forbidden` with an error cause associated with a session expiration error and redirect the user to the login page.
```tsx filename="app/lib/dal.ts"
import { forbidden } from 'next/navigation'
import { cookies } from 'next/headers'
export async function verifySession() {
const cookieStore = await cookies()
const token = cookieStore.get('token')
if (!token) {
forbidden(new AuthError('No token found'))
}
if (isExpired(token.value)) {
forbidden(new SessionExpiredError('Session expired'))
}
}
```
```tsx filename="app/auth/page.tsx"
import { InvalidPermissionError, isExpired } from '@/app/lib/dal'
export default async function AdminPage() {
try {
await verifySession()
} catch (err) {
if (err instanceof Error && err.cause instanceof SessionExpiredError) {
redirect('/login')
}
throw err
}
// Render the admin page for authorized users
return <></>
}
```
## Good to know ## Good to know
- The `forbidden` function cannot be called in the [root layout](/docs/app/building-your-application/routing/layouts-and-templates#root-layout-required). - The `forbidden` function cannot be called in the [root layout](/docs/app/building-your-application/routing/layouts-and-templates#root-layout-required).
......
...@@ -19,7 +19,8 @@ async function fetchUser(id) { ...@@ -19,7 +19,8 @@ async function fetchUser(id) {
} }
export default async function Profile({ params }) { export default async function Profile({ params }) {
const user = await fetchUser(params.id) const id = await params.id
const user = await fetchUser(id)
if (!user) { if (!user) {
notFound() notFound()
...@@ -29,6 +30,40 @@ export default async function Profile({ params }) { ...@@ -29,6 +30,40 @@ export default async function Profile({ params }) {
} }
``` ```
You can also pass an error cause to `notFound` to handle different types of errors before escalating to the Next.js' error page. For example, you can call `notFound` with a path where the resource was relocated to, which can be selectively handled when using this function, while still falling back to a 404 page if unhandled.
```tsx filename="app/auth/page.js"
import { ResourceRelocatedError } from '@/app/lib/dal'
import { notFound } from 'next/navigation'
async function fetchArticle(slug) {
const res = await fetch('https://...')
if (res.status === 301) {
notFound(new ResourceRelocatedError('/new-url'))
}
return res.json()
}
export default function Page({ params }) {
let article
try {
const slug = await params.slug
article = await fetchArticle(slug)
} catch (err) {
if (err.cause instanceof ResourceRelocatedError) {
redirect(err.cause.redirectTo)
}
throw err
}
// ...
}
```
> **Good to know**: `notFound()` does not require you to use `return notFound()` due to using the TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type. > **Good to know**: `notFound()` does not require you to use `return notFound()` due to using the TypeScript [`never`](https://www.typescriptlang.org/docs/handbook/2/functions.html#never) type.
## Version History ## Version History
......
...@@ -16,16 +16,17 @@ If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api ...@@ -16,16 +16,17 @@ If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api
## Parameters ## Parameters
The `permanentRedirect` function accepts two arguments: The `permanentRedirect` function accepts three arguments:
```js ```js
permanentRedirect(path, type) permanentRedirect(path, type, cause)
``` ```
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------------------------------------------------- | ----------------------------------------------------------- | | --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `path` | `string` | The URL to redirect to. Can be a relative or absolute path. | | `path` | `string` | The URL to redirect to. Can be a relative or absolute path. |
| `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. | | `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. |
| `cause` | `Error` | An optional error that will be attached to the `cause` property of the error thrown by Next.js. |
By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `permanentRedirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
......
...@@ -19,16 +19,17 @@ If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api ...@@ -19,16 +19,17 @@ If a resource doesn't exist, you can use the [`notFound` function](/docs/app/api
## Parameters ## Parameters
The `redirect` function accepts two arguments: The `redirect` function accepts three arguments:
```js ```js
redirect(path, type) redirect(path, type)
``` ```
| Parameter | Type | Description | | Parameter | Type | Description |
| --------- | ------------------------------------------------------------- | ----------------------------------------------------------- | | --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `path` | `string` | The URL to redirect to. Can be a relative or absolute path. | | `path` | `string` | The URL to redirect to. Can be a relative or absolute path. |
| `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. | | `type` | `'replace'` (default) or `'push'` (default in Server Actions) | The type of redirect to perform. |
| `cause` | `Error` | An optional error that will be attached to the `cause` property of the error thrown by Next.js. |
By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter. By default, `redirect` will use `push` (adding a new entry to the browser history stack) in [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) and `replace` (replacing the current URL in the browser history stack) everywhere else. You can override this behavior by specifying the `type` parameter.
......
...@@ -75,6 +75,49 @@ export default async function DashboardPage() { ...@@ -75,6 +75,49 @@ export default async function DashboardPage() {
} }
``` ```
You can also pass an error cause to `forbidden` to handle different types of errors before escalating to the Next.js' error page. For example, you can call `unauthorized` with an error cause associated with a session expiration error and redirect the user to the login page.
```tsx filename="app/lib/dal.ts"
import { unauthorized } from 'next/navigation'
import { cookies } from 'next/headers'
export async function verifySession() {
const cookieStore = await cookies()
const token = cookieStore.get('token')
if (!token) {
unauthorized(new AuthError('No token found'))
}
if (isExpired(token.value)) {
unauthorized(new SessionExpiredError('Session expired'))
}
}
```
```tsx filename="app/auth/page.tsx"
import { SessionExpiredError, verifySession } from '@/app/lib/dal'
export default async function AdminPage() {
try {
await verifySession()
} catch (err) {
if (err instanceof Error && err.cause instanceof SessionExpiredError) {
redirect('/login')
}
throw err
}
// Render the dashboard for authenticated users
return (
<main>
<h1>Welcome to the Dashboard</h1>
</main>
)
}
```
## Good to know ## Good to know
- The `unauthorized` function cannot be called in the [root layout](/docs/app/building-your-application/routing/layouts-and-templates#root-layout-required). - The `unauthorized` function cannot be called in the [root layout](/docs/app/building-your-application/routing/layouts-and-templates#root-layout-required).
......
...@@ -19,7 +19,7 @@ import { ...@@ -19,7 +19,7 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403` const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`
export function forbidden(): never { export function forbidden(cause?: Error): never {
if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) { if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {
throw new Error( throw new Error(
`\`forbidden()\` is experimental and only allowed to be enabled when \`experimental.authInterrupts\` is enabled.` `\`forbidden()\` is experimental and only allowed to be enabled when \`experimental.authInterrupts\` is enabled.`
...@@ -27,7 +27,7 @@ export function forbidden(): never { ...@@ -27,7 +27,7 @@ export function forbidden(): never {
} }
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
const error = new Error(DIGEST) as HTTPAccessFallbackError const error = new Error(DIGEST, { cause }) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST ;(error as HTTPAccessFallbackError).digest = DIGEST
throw error throw error
} }
...@@ -20,9 +20,9 @@ import { ...@@ -20,9 +20,9 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404` const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`
export function notFound(): never { export function notFound(cause?: Error): never {
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
const error = new Error(DIGEST) as HTTPAccessFallbackError const error = new Error(DIGEST, { cause }) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST ;(error as HTTPAccessFallbackError).digest = DIGEST
throw error throw error
......
...@@ -10,9 +10,10 @@ import { ...@@ -10,9 +10,10 @@ import {
export function getRedirectError( export function getRedirectError(
url: string, url: string,
type: RedirectType, type: RedirectType,
statusCode: RedirectStatusCode = RedirectStatusCode.TemporaryRedirect statusCode: RedirectStatusCode = RedirectStatusCode.TemporaryRedirect,
cause?: Error
): RedirectError { ): RedirectError {
const error = new Error(REDIRECT_ERROR_CODE) as RedirectError const error = new Error(REDIRECT_ERROR_CODE, { cause }) as RedirectError
error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};` error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`
return error return error
} }
...@@ -32,7 +33,8 @@ export function getRedirectError( ...@@ -32,7 +33,8 @@ export function getRedirectError(
export function redirect( export function redirect(
/** The URL to redirect to */ /** The URL to redirect to */
url: string, url: string,
type?: RedirectType type?: RedirectType,
cause?: Error
): never { ): never {
const actionStore = actionAsyncStorage.getStore() const actionStore = actionAsyncStorage.getStore()
const redirectType = const redirectType =
...@@ -40,7 +42,8 @@ export function redirect( ...@@ -40,7 +42,8 @@ export function redirect(
throw getRedirectError( throw getRedirectError(
url, url,
redirectType, redirectType,
RedirectStatusCode.TemporaryRedirect RedirectStatusCode.TemporaryRedirect,
cause
) )
} }
...@@ -58,9 +61,10 @@ export function redirect( ...@@ -58,9 +61,10 @@ export function redirect(
export function permanentRedirect( export function permanentRedirect(
/** The URL to redirect to */ /** The URL to redirect to */
url: string, url: string,
type: RedirectType = RedirectType.replace type: RedirectType = RedirectType.replace,
cause?: Error
): never { ): never {
throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect) throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect, cause)
} }
/** /**
......
...@@ -20,7 +20,7 @@ import { ...@@ -20,7 +20,7 @@ import {
const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401` const DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`
export function unauthorized(): never { export function unauthorized(cause?: Error): never {
if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) { if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {
throw new Error( throw new Error(
`\`unauthorized()\` is experimental and only allowed to be used when \`experimental.authInterrupts\` is enabled.` `\`unauthorized()\` is experimental and only allowed to be used when \`experimental.authInterrupts\` is enabled.`
...@@ -28,7 +28,7 @@ export function unauthorized(): never { ...@@ -28,7 +28,7 @@ export function unauthorized(): never {
} }
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
const error = new Error(DIGEST) as HTTPAccessFallbackError const error = new Error(DIGEST, { cause }) as HTTPAccessFallbackError
;(error as HTTPAccessFallbackError).digest = DIGEST ;(error as HTTPAccessFallbackError).digest = DIGEST
throw error throw error
} }
import { redirect } from 'next/navigation'
import { SessionExpiredError, verifyAuth } from './utils'
export default async function Page() {
try {
await verifyAuth()
} catch (err) {
if (err.cause instanceof SessionExpiredError) {
redirect('/')
}
throw err
}
return <p id="page">Cause Page</p>
}
import { cookies } from 'next/headers'
import { forbidden } from 'next/navigation'
export class AuthError extends Error {
constructor(message) {
super(message)
this.name = 'AuthError'
}
}
export class SessionExpiredError extends Error {
constructor(message) {
super(message)
this.name = 'AuthError'
}
}
export async function verifyAuth() {
const cookieStore = await cookies()
const token = cookieStore.get('token')
if (!token) {
forbidden(new AuthError('No token found'))
}
if (token.value === 'expired') {
forbidden(new SessionExpiredError('Session expired'))
}
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app dir - forbidden with customized boundary', () => { describe('app dir - forbidden with customized boundary', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -38,4 +39,22 @@ describe('app dir - forbidden with customized boundary', () => { ...@@ -38,4 +39,22 @@ describe('app dir - forbidden with customized boundary', () => {
'Root Forbidden' 'Root Forbidden'
) )
}) })
it('should support a custom error cause', async () => {
const browser = await next.browser('/cause')
// we don't have explicit handling for a missing token, but we still triggered `forbidden`
expect(await browser.elementByCss('h1').text()).toBe('Root Forbidden')
// Set a token
await browser.eval("document.cookie='token=expired'")
await browser.refresh()
// expired token, and the user decided that SessionExpiredError should be handled by redirecting to root
retry(async () => {
expect(await browser.url()).toBe(next.url)
})
expect(await browser.elementByCss('h1').text()).toBe('My page')
})
}) })
import { redirect } from 'next/navigation'
import { SessionExpiredError, verifyAuth } from './utils'
export default async function Page() {
try {
await verifyAuth()
} catch (err) {
if (err.cause instanceof SessionExpiredError) {
redirect('/')
}
throw err
}
return <p id="page">Cause Page</p>
}
import { cookies } from 'next/headers'
import { unauthorized } from 'next/navigation'
export class AuthError extends Error {
constructor(message) {
super(message)
this.name = 'AuthError'
}
}
export class SessionExpiredError extends Error {
constructor(message) {
super(message)
this.name = 'AuthError'
}
}
export async function verifyAuth() {
const cookieStore = await cookies()
const token = cookieStore.get('token')
if (!token) {
unauthorized(new AuthError('No token found'))
}
if (token.value === 'expired') {
unauthorized(new SessionExpiredError('Session expired'))
}
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app dir - unauthorized - basic', () => { describe('app dir - unauthorized - basic', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -38,4 +39,22 @@ describe('app dir - unauthorized - basic', () => { ...@@ -38,4 +39,22 @@ describe('app dir - unauthorized - basic', () => {
'Root Unauthorized' 'Root Unauthorized'
) )
}) })
it('should support a custom error cause', async () => {
const browser = await next.browser('/cause')
// we don't have explicit handling for a missing token, but we still triggered `unauthorized`
expect(await browser.elementByCss('h1').text()).toBe('Root Unauthorized')
// Set a token
await browser.eval("document.cookie='token=expired'")
await browser.refresh()
// expired token, and the user decided that SessionExpiredError should be handled by redirecting to root
retry(async () => {
expect(await browser.url()).toBe(next.url)
})
expect(await browser.elementByCss('h1').text()).toBe('My page')
})
}) })
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