Redirects, Not Found, Loading and Error Pages

Next.js Course: Beginner to Advanced with Examples · Routing and Navigation · 7 min read · Updated

When things do not go smoothly

  1. A visitor asks for an address.
  2. Next.js looks for a matching page.
  3. If it moved, a missing page, slow data or an error shows up, the matching special file is chosen.
  4. The visitor sees a friendly screen instead of a blank page.

A good site does not only work when everything goes well. It also behaves politely when a page moved, when a page does not exist, when data is slow and when something breaks. Next.js gives each of these moments its own special file or function. Think of it as a shop. If an item has moved, a sign points to the new shelf (redirect). If an item does not exist, the assistant says so kindly (not found). While the assistant fetches something from the back room, you see a small please-wait sign (loading). And if the back room is flooded, the shop has a calm message and a way to try again (error).

Redirects in code

The redirect function from next/navigation sends the visitor to another address. It works in Server Components, Server Actions and Route Handlers. By default the answer is a temporary 307 code. We tested this page.

import { redirect } from "next/navigation";

export default function OldPage() {
  redirect("/about");
}

When we asked for /old-page, the server answered 307 and pointed to /about. For a permanent move, which search engines should remember, use the permanentRedirect function or the redirects setting in next.config.ts, which gives a 308 code.

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async redirects() {
    return [
      { source: "/old-blog/:slug", destination: "/blog/:slug", permanent: true },
    ];
  },
};

export default nextConfig;

Not found pages

Call notFound from next/navigation when you cannot find what the address asks for, for example a post that does not exist. Next.js then shows the nearest not-found file. A not-found file in the app folder is the page for the whole site. We tested one, and an unknown address such as /nope returned a 404 and this page.

import Link from "next/link";

export default function NotFound() {
  return (
    <main>
      <h1>Page not found</h1>
      <Link href="/">Go home</Link>
    </main>
  );
}
import { notFound } from "next/navigation";

const posts = ["hello-nextjs", "routing-basics"];

export function generateStaticParams() {
  return posts.map((slug) => ({ slug }));
}

export default async function PostPage({ params }: PageProps<"/posts/[slug]">) {
  const { slug } = await params;
  if (!posts.includes(slug)) notFound();
  return <h1>{slug}</h1>;
}

The call to notFound stops the function, so the lines after it do not run. There is one detail that surprises many people, and we measured it. An address that matches no folder at all, such as /nope, returned the status 404. But an address that matches the [slug] folder and then calls notFound, such as /posts/zzz, showed our not-found page with the status 200. The reason is streaming: with Cache Components, Next.js sends the ready static part of the page first, and that first part starts the response with 200. Next.js protects your search ranking by adding a robots noindex tag to the streamed not-found page, so Google should not index it. The official docs say that some crawlers may still call it a soft 404. If you need a true 404 status, make the check run before the response starts.

Loading pages

A file named loading in a route folder shows while the page, or something under it, waits for its data. Next.js wraps the page in a Suspense boundary for you and shows your loading component until the page is ready. The user sees something at once, and the layout stays in place.

export default function Loading() {
  return <p>Loading dashboard...</p>;
}
  • Keep loading screens light: a text line or a simple skeleton that has the same shape as the real content.
  • A loading file covers the folder it is in and the folders below it.
  • For a smaller area, you can wrap only that part in Suspense yourself. You will do this in the data fetching module.

Error pages

A file named error shows when something inside the route throws an error while rendering. It must be a client component, so it starts with use client. It receives the error and a reset function. Calling reset tries to draw the route again, which helps when the error was a short problem such as a lost network connection.

"use client";

export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
  return (
    <main>
      <h1>Something went wrong</h1>
      <button onClick={() => reset()}>Try again</button>
    </main>
  );
}
  • The page is replaced by your error screen, but the layout around it stays working.
  • Do not show the raw error message to visitors. In production Next.js hides the details of server errors and gives a digest code, which you can search for in your server logs.
  • Place an error file in a folder to protect only that part of the site.

Global error handling

An error file cannot catch an error thrown by the root layout itself, because it sits inside that layout. For that rare case there is a file called global-error in the app folder. It replaces the whole page, so it must include its own html and body tags. Keep it very simple.

"use client";

export default function GlobalError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
  return (
    <html lang="en">
      <body>
        <h1>Something went seriously wrong</h1>
        <button onClick={() => reset()}>Try again</button>
      </body>
    </html>
  );
}

The global-error example was type-checked, but we did not force an error in the root layout to see it run.

The order of the special files

In one route folder Next.js nests the special files like layers. The layout is the outer layer. Inside it are the error boundary, then the loading boundary and the not-found boundary, and the page is the innermost part. This order explains why an error file cannot catch errors from the layout beside it.

Your task

  1. Create /old-page that redirects to /about. Check the response code with your browser network tab.
  2. Add app/not-found.tsx with a link home. Visit an address that does not exist.
  3. Add loading.tsx to a folder and slow its page down with a wait function. Watch the loading text appear.
  4. Add error.tsx and throw an error inside a page on purpose. Press the Try again button.

How to check it worked

  • /old-page ends on /about.
  • Unknown addresses show your own not-found page.
  • A thrown error shows your error page and the rest of the site still works.

Frequently asked questions

What is the difference between redirect and permanentRedirect?

redirect is temporary (307). permanentRedirect and the permanent option in next.config.ts are permanent (308), which tells search engines to move the old address to the new one.

Why must error.tsx be a client component?

It needs to handle the reset button, which runs in the browser. So it starts with the line use client.

Does not-found give a real 404 status?

Yes. In our test an unknown address returned status 404 with our own page.