12

This is the sturcure of my next.js project.

enter image description here

And my 404.js page is :

'use client';

export default function NotFound() {
    return (
        <div>
            <h2>Not Found</h2>
        </div>
    );
}

when I enter the wrong route it does not work and does not go to my custom page and goes to next.js 404 page. why, Where am I wrong?

thanks in advance.

AR Second
  • 582
  • 1
  • 6
  • 25
  • Hello and welcome to Stack Overflow. Please read [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/questions/285551/why-should-i-ot-upload-images-of-code-data-errors) to see how you can improve your question. – Andy Preston Mar 03 '23 at 09:39

3 Answers3

37

With Next 13.3 you just need to change the file name to not-found.js.

An app/not-found.js file will now automatically handle visits to an URL that does not have a matching route in your app.

Docs: https://nextjs.org/docs/app/api-reference/file-conventions/not-found

Announced in : https://nextjs.org/blog/next-13-3


With Next 13.2, according to the docs:

"Note: not-found.js currently only renders when triggered by the notFound function, we're working on support for catching unmatched routes."

So it's not yet automatic but looks like they are working on it. File should also be named not-found.js instead of 404.js,

In the meantime, as it looks like dynamic routes are resolved after static routes, you can solve it by creating a dynamic catch-all route using a [...not_found] folder and add it to your app folder.

Image of folder structure for a Next 13 application showing the app folder with a [...not_found] folder, an articles folder and a layout.js, not-found.js, and page.js file in the root of the app folder.

Inside the dynamic route folder add a page.js file that calls the notFound() function.

app/[...not_found]/page.js

import Link from 'next/link'
import {notFound} from "next/navigation"

export default function NotFoundCatchAll() {
  notFound()
  return null
}

And inside the not-found.js file in the root of your app folder you can add your custom 404 page.

app/not-found.js

import Link from 'next/link'

export default function NotFound() {
  return <div>
      <h1>Not found – 404!</h1>
      <div>
        <Link href="/">Go back to Home</Link>
      </div>
  </div>
}

Important to note that this approach can create problems if you have multiple dynamic routes in your app folder. Dynamic routes in another static folder should be fine however.

Hope it helps and good luck!

  • Please read [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/questions/285551/why-should-i-ot-upload-images-of-code-data-errors) to see how you can improve your answer. – Andy Preston Mar 03 '23 at 09:40
  • 1
    Is it possible to explicitly navigate to the `src/app/not-found.js`? Like by going to `app.com/not-found`? What I'm trying to do is use the custom server and specifically render the not-found page. The `render404` doesn't appear to work. – CMCDragonkai Jul 20 '23 at 14:29
  • 2
    I have this setup correctly, yet my 404 template is missing all styles. The Layout template is being inherited, but all of my styles are missing. Any thoughts on how to diagnose this? – Jay Jul 20 '23 at 14:50
4

NextJS13 doesnt do error handling in this format, you dont want to use a file named 404.js but instead a file named error.js.

This will catch any errors sent from an API request returning a 404 response.

Docs here: https://beta.nextjs.org/docs/routing/error-handling


If your API instead returns a 200 response but an empty body, you could create another component named not-found.js, import that into the file you want it to show on, and return it on if the api is empty, for example:

app/dashboard/not-found.js

export default function NotFound() {
  return (
    <>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
    </>
  );
}

app/dashboard/index.js:

import { notFound } from 'next/navigation';

async function fetchUsers(id) {
  const res = await fetch('https://...');
  if (!res.ok) return undefined;
  return res.json();
}

export default async function Profile({ params }) {
  const user = await fetchUser(params.id);

  if (!user) {
    notFound();
  }

  // ...
}

Docs here: https://beta.nextjs.org/docs/api-reference/notfound

Stewartside
  • 20,378
  • 12
  • 60
  • 81
  • Is it possible to explicitly navigate to the `src/app/not-found.js`? Like by going to `app.com/not-found`? What I'm trying to do is use the custom server and specifically render the not-found page. The `render404` doesn't appear to work. – CMCDragonkai Jul 20 '23 at 14:29
-7

To create a not-found page in Next.js using the app folder, you can follow these steps:

  1. Create a new folder named pages in your project's root directory.

  2. In the pages folder, create a new file named 404.js.

  3. In the 404.js file, add the following code to render the Not Found page:

    const NotFound = () => {
      return (
        <div>
          <h1>404 - Not Found</h1>
        </div>
      )
    }
    
    export default NotFound
    
  4. In your _app.js file, add a catch-all route to display the Not Found page for any unknown routes:

import App, { Container } from 'next/app'

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps }
  }

  render() {
    const { Component, pageProps } = this.props

    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    )
  }
}

export default MyApp

Now, when a user visits a route that does not exist in your application, the Not Found page will be displayed.

Stewartside
  • 20,378
  • 12
  • 60
  • 81
  • 3
    This is a great answer for nextjs 12 and below. The user wants NextJS13 which uses the new React Server Components in the new `/app` folder and not the `/pages` folder. – Stewartside Feb 02 '23 at 11:10