Next.js Discord

Discord Forum

[Next.js 14][AppRouter] How to use specified layout for not-found page?

Answered
Araucanian herring posted this in #help-forum
Open in Discord
Araucanian herringOP
Hi everyone, I'm new to Next.js 14.
I have defined a root layout in app/layout.tsx, which contains some links and renders the content of child components. I also created a custom "not found" page by following the documentation here: https://nextjs.org/docs/app/api-reference/file-conventions/not-found.

However, I'm having an issue: when I visit a non-existing URL, my custom "not found" page is rendered within the root layout. I want to use a different layout for the "not found" page.

How can I achieve that?
Someone suggested that I try defining app/(not-found)/layout.tsx, but it didn't work.

This is an example of my Next.js app. https://stackblitz.com/edit/stackblitz-starters-mgqwak?file=app%2Flayout.tsx
Answered by joulev
app/
  (main)/
    layout.tsx <- actual root layout here
    ...
  layout.tsx <- empty root layout (see below)
  not-found.tsx


the empty root layout is just
export default function Layout({ children }) {
  return children;
}


then in not-found you can use <html>, <body> and anything you like
View full answer

7 Replies

Answer
Araucanian herringOP
Thanks a lot! Your suggestion worked like a charm.
I didn't realize that Route Groups could be used this way.
yup, route group is very powerful
Tufted Titmouse
Hello @joulev and @Araucanian herring. I followed your advise and created:
app/
  (main)/
    layout.tsx <- actual root layout here
    ...
  layout.tsx <- empty root layout (see below)
  not-found.tsx

This works if you have for example (main)/about/ and then domain.com/wasfwa that results in an error. If you, however, have (main)/blog/page.tsx and your error is domain.com/blog/wasfwa you get an error: In HTML, <html> cannot be a child of <div>.. This is because not-found has to return either the whole <html <body> etc in some cases and only the inner children in others, but I cannot catch them all. So I am not sure how to proceed.
Tufted Titmouse
But I only have one not-found file. In app/not-found.tsx Are you saying that I should create multiple? Even if I try that and create /app/(main)/not-found.tsx which doesn't have <html>, when I go to domain.com/blog/404 I get the same <html> cannot be a child of <div> error. It seems like Next.js is using only one global not-found file for every route.
Araucanian herringOP
@Tufted Titmouse empty root layout must contain html, body tags then render a children
and the content of not-found.tsx or any pages mustn't contain html, body
plz see my example, I think it works in your case
https://stackblitz.com/edit/stackblitz-starters-mgqwak?file=app%2F(main)%2Flayout.tsx