skip to Main Content

I’m trying to add a custom 404 page inside my Next app.
I want to use the same 404 page for all my "not found" routes.
My app directory looks like the following While my root layout.

If I navigate to a none existing route localhost:3000/example or a nested one localhost:3000/headphones/example, I’ll be redirected to the not-found page.
It’s working as expected But I noticed that the not found page is missing the layout.css file while the not-found.module.css is loaded normally.

The not found page component is quite simple.

import styles from '@/styles/pages/notFound.module.css'

import Link from 'next/link'

const NotFound = () => {
  return (
    <div id={styles.container_not_found}>
      <h1>not found</h1>
      <Link href='/'>go back home</Link>
    </div>
  )
}

export default NotFound

I observed the network tab in chrome when I do a page request.
If I request the home page or any existing page, I can clearly see the layout.css and the page’s module CSS files are been requested. However, If I request a non existing route, only the not-found.module.css is requested. This means, The header and footer aren’t styled in my not found page.

2

Answers


  1. Try including your layout CSS globally:

    // _app.js (or _app.tsx)
    import '../styles/layout.css'; // Include your layout.css globally
    
    function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />;
    }
    
    export default MyApp;
    
    Login or Signup to reply.
  2. In your app/not-found.tsx

    import Link from 'next/link'
     
    export default function NotFound() {
      return (
        <div>
          <h2>Not Found</h2>
          <p>Could not find requested resource</p>
          <Link href="/">Return Home</Link>
        </div>
      )
    }
    

    For using your global.css which is imported on layout.tsx you don’t need to import again on your not-found.tsx page. You can directly access the classes like className='yourCustomCSS'

    Make sure you have imported your globals.css file into the root app/layout.tsx

    import './globals.css' // < THIS LINE
    
    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode
    }) {
      return (
        <html lang="en">
          <body>{children}</body>
        </html>
      )
    }
    
    

    Read more on CSS: https://nextjs.org/docs/app/building-your-application/styling/css-modules

    Read more on not found page: https://nextjs.org/docs/app/api-reference/file-conventions/not-found

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search