#How to handle a 404 error page when there's a shared layout?

1 messages · Page 1 of 1 (latest)

vast shoal
#

I have a Next.js website with a shared layout for pages that are in the docs section of the website, that shows a sidebar and a navbar. When a user goes to a page that doesn't exist in the docs sidebar, it shows a 404 not found. But when I render this, it renders within the layout, which looks kind of weird. How do you typically handle this? Do you display something other than "404 not found. Return to docs"? What are some alternative messages.

solid stirrupBOT
#

Hi @vast shoal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources, there are several approaches to handling 404 errors within a shared layout in Next.js.

The Problem with 404 Pages in Shared Layouts

You're experiencing a common issue where the 404 page is rendered within your docs layout (with sidebar and navbar), which can look strange to users. This happens because the not-found.tsx component respects the layout hierarchy in the App Router.

Solutions and Approaches

1. Custom 404 Page Content

Instead of a generic "404 not found" message, you could customize the content to fit better within your docs layout:

  • "This documentation page doesn't exist"
  • "We couldn't find this article in our documentation"
  • "This topic isn't in our documentation yet"

You could also add helpful elements like:

  • Links to popular documentation pages
  • A search box to find relevant content
  • Suggested related topics

2. Using Catch-All Routes

One solution mentioned in the knowledge sources is to use a catch-all route within your docs section:

// app/docs/[...fallback]/page.tsx
import { notFound } from 'next/navigation'

export default function CatchAllPage() {
  notFound()
}

With a corresponding not-found.tsx file in your docs directory that's designed to work within your layout.

3. Technical Considerations

There are some technical issues to be aware of:

  • There's an open issue where 404 pages aren't properly server-rendered when using notFound() in certain contexts.
  • If you're using internationalization, there are additional challenges with global 404 pages.

4. Alternative Approach for Multiple Root Layouts

If you have multiple root layouts and are struggling with 404 handling, you can use a catch-all segment approach:

#
app/
├── docs/
│   ├── layout.tsx (your docs layout with sidebar)
│   └── [...fallback]/
│       └── page.tsx (calls notFound())
│   └── not-found.tsx (custom 404 for docs section)

This structure allows you to have a custom 404 page specifically for your docs section that works within your docs layout.

Remember that the 404 page should be helpful to users, guiding them back to useful content rather than just stating that something is missing.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: