UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

218 lines (165 loc) • 8.06 kB
# Errors and 404s > What a visitor sees when a page throws, or asks for a url nothing answers. An `error.tsx` is what a visitor sees when a page throws, and a `not-found.tsx` is what they see for a page that doesn't exist. Both are optional, and the one nearest the page wins. ```text src/app/ not-found.tsx any url no route matches orders/ error.tsx anything under /orders that throws ``` ## Showing an error page Put an `error.tsx` in the folder you want to cover: ```tsx title="src/app/orders/error.tsx" 'use client' import type { RouteErrorProps } from '@rsc-kit/core/RouteErrorBoundary' export default function OrdersError({ error, reset }: RouteErrorProps) { return ( <section> <h1>That did not work</h1> <p>{error.message}</p> <button type="button" onClick={reset}>Try again</button> </section> ) } ``` Anything below it that throws renders this instead. The layouts above stay on screen; only the part that failed is replaced. It must start with `'use client'`, or the build refuses it. Catching a render error happens in the browser, and `reset` is a callback the browser calls. Without an `error.tsx`, a page that throws shows the engine's error page where the page was, with the layouts around it kept and a **Try again** button. In development it shows the message and stack; in production, "Something went wrong" and the digest to search the server log for. In development, a page that throws also opens Vite's error overlay, whether an `error.tsx` caught it or the engine's page did. That includes a page you reached by a link or a redirect, not only one you reloaded. ### Trying again `reset()` asks the server for the page again and renders the answer. It suits a failure that might not happen twice, such as a service that was down for a moment. The error stays on screen until the new page arrives, and shows again if the page fails again. Don't call `refresh()` beside it or reload the document. Navigating away clears the error too. ### The message in production React replaces `error.message` with a generic sentence and puts a hash on `error.digest`, so a message naming a table, a query or a path never reaches a browser. Log the digest where you log the error, and the two line up. ### What it doesn't catch - **A layout above it that throws.** The boundary sits inside that layout, so put an `error.tsx` a folder higher. The engine's own error page is outermost and catches those too. - **A page that throws every time it renders.** That fails the build instead of shipping a stored error page. ## Handling a refusal in a server component A refused `rpc()` throws an error you can check for, so a server component can show something else instead of failing: ```tsx import { ServerAuthenticationError } from '@rsc-kit/core/errors' async function Invite({ token }: { token: string }) { try { return <Accept invite={await rpc('Invites.find', token)} /> } catch (error) { if (error instanceof ServerAuthenticationError) return <SignInToAccept /> throw error } } ``` | Error | When | | --- | --- | | `ServerAuthenticationError` | the backend answered 401 | | `ServerAuthorizationError` | the backend answered 403 | A refusal with a status of its own (`abort(429)`, Go's `Refuse(503, …)`) carries it as `error.refusalStatus`, beside the backend's message. Left uncaught, the page answers with that status. Rethrow what you don't handle, so a not-found or a redirect still works. ## Showing a 404 page `src/app/not-found.tsx` renders for any url no route matches: ```tsx title="src/app/not-found.tsx" import Link from '@rsc-kit/core/Link' export default function NotFound() { return ( <main> <h1>No such page</h1> <p>Nothing answers that url. <Link href="/">Go home</Link>.</p> </main> ) } ``` - It renders inside your root layout, with a real **404** status, so search engines don't index it. - It is a server component, so it can be `async` and read cookies. - A client-side navigation to a missing url renders it in place, with the layout kept and the url changed. Without one, an unmatched url gets a plain `Not found`, and a navigation to it is a full page load. Only a request that can show a page gets it. A missing image, script, font or stylesheet - a browser's `/favicon.ico` - gets a plain 404 at once. This holds under a dynamic route like `/[team]` too: a request the browser marks as one of those (`Sec-Fetch-Dest`) gets a plain 404 before any of the route's middleware runs. A `route.ts` still answers it, since an image endpoint is a route, not a page. ### A 404 page for one part of the site A `not-found.tsx` beside a layout answers `notFound()` from every page under it, inside that layout: ```text src/app/ layout.tsx not-found.tsx ← an unmatched url, and anything outside the shop (shop)/ layout.tsx ← the shop's header and cart not-found.tsx ← a missing product: the header stays c/[category]/[sub]/[product]/page.tsx ``` The nearest one above the page that said so wins, whether `notFound()` came from the page's body, a read under `<Suspense>` or a `middleware.ts`. An url no route owns has no page to be under, so only the root `not-found.tsx` answers it. ## When the page has to decide `/posts/42` matches a route, but there may be no post 42. Call `notFound()` from the page: ```tsx title="src/app/posts/[slug]/page.tsx" import { notFound } from '@rsc-kit/core/not-found' export default async function PostPage({ params }) { const post = await findPost((await params).slug) if (!post) notFound() return <article>{post.title}</article> } ``` It throws, so nothing after it runs. If you wrap it in a `try`/`catch`, rethrow what you don't recognise, or the missing page becomes a blank region. A backend's 404 is the same signal, so a read you mean to be optional can be caught on purpose: `await rpc('Posts.related', id).catch(() => null)` renders the page without it. ### Where you call it decides the status - **Above every `<Suspense>`** - at the top of a page, or in a layout - nothing has been sent yet, and the response is a real 404. - **Inside a `<Suspense>` boundary**, the page has already started streaming with a `200`. The browser then shows your `not-found.tsx` where the page was, with the layouts above it kept and the url unchanged, and adds `<meta name="robots" content="noindex">` so search engines skip it. Search engines and link-preview scrapers always get the real status: they are answered once the whole page has rendered, so `notFound()` is a 404 and `redirect()` a redirect wherever they were called. The engine recognises them by user agent - Googlebot, Bingbot, Applebot, DuckDuckBot, Yandex, Baidu, and the preview fetchers of Facebook, X, LinkedIn, Slack, Discord, WhatsApp, Telegram and others. A page under a `loading.tsx` is always inside a boundary. When a person must get a real 404 - a record their account can't see - check in a `middleware.ts` beside the page. It runs before anything is sent, even for a page the build stored. Its argument is the route's params as a plain object: `{ slug: '42' }`. ## A server module in the browser bundle ```txt [rsc-kit] '@rsc-kit/core/redirect' is for the server, and ended up in the browser bundle: imported by src/lib/team.ts which is imported by src/app/teams/controls.tsx ``` The build stops, and in development the module fails to load, when a file the browser imports reaches `request`, `redirect`, `revalidate`, `cache`, `section`, or any other part of this package that only works on a server. The usual cause is a helper file shared by both kinds of code: a page calls its `redirect()`, and a client component imports its `label()`. Split it into two files - one only server components import, one the client can. A type-only import doesn't count. Mark your own server-only files with `import 'server-only'`. A client file that reaches one fails the same way, naming the files that brought it there.