next.js - How to give not-found.tsx a custom layout? - Stack Overflow

admin2025-04-20  0

I currently have my authenticated pages and anonymous pages separated with their own layouts. I've done this because I need the layout to change depending on whether a user is logged in or not.

So my pages are structured like this:

/app
    /(pages)
        /(anon)
            layout.tsx
            page.tsx
            /about
                page.tsx
            /contact
                page.tsx
            /login
                page.tsx
        /(auth)
            layout.tsx
            /dashboard
                page.tsx

I really want to customise the 404 page. Next.js only recognises the not-found.tsx file if it is directly inside the /app directory. It also requires its own layout.tsx file.

However, adding a layout.tsx directly inside /app gives all my pages two layouts. It double wraps them. One from /app, and the other from the next layout.tsx inside whatever folder that page resides in.

I currently have my authenticated pages and anonymous pages separated with their own layouts. I've done this because I need the layout to change depending on whether a user is logged in or not.

So my pages are structured like this:

/app
    /(pages)
        /(anon)
            layout.tsx
            page.tsx
            /about
                page.tsx
            /contact
                page.tsx
            /login
                page.tsx
        /(auth)
            layout.tsx
            /dashboard
                page.tsx

I really want to customise the 404 page. Next.js only recognises the not-found.tsx file if it is directly inside the /app directory. It also requires its own layout.tsx file.

However, adding a layout.tsx directly inside /app gives all my pages two layouts. It double wraps them. One from /app, and the other from the next layout.tsx inside whatever folder that page resides in.

Share Improve this question edited Mar 2 at 12:12 Progman 19.7k7 gold badges55 silver badges82 bronze badges asked Mar 2 at 11:38 cap1hunnacap1hunna 1147 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Found the solution.

I suppose it was an error on my part, but I will post an answer for anyone who happens to stumble across the same dilemma.

My different layout.tsx files each had their on <html> <head> <body> tags, as each directory was treated with isolation.

The solution was to keep one "master/root" layout.tsx file directly inside /app. This would hold <html> <head> <body> tags. The other separate layout.tsx files in other directories just omit that. So they only contain what was actually different about each layout, rather than them essentially being their own entire root layout, which was causing the double wrap, hence pages being wrapped inside two <html> and so on.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745123766a286303.html

最新回复(0)