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
Try including your layout CSS globally:
In your
app/not-found.tsx
For using your
global.css
which is imported onlayout.tsx
you don’t need to import again on yournot-found.tsx
page. You can directly access the classes likeclassName='yourCustomCSS'
Make sure you have imported your
globals.css
file into the rootapp/layout.tsx
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