In my project, I have the following folder structure:
In the /[...catchAll]/page.js
file, I have such a logic that checks if there exists any content at the desired URL, and if not, it returns a message: "This page does not exist.". Here is the code:
import PageTransition from "@/components/PageTransition";
import { pageContent } from "@/utils/content";
import { usePathname } from "next/navigation";
export default function CatchAll() {
const pathname = usePathname();
const blocks = pageContent?.[pathname];
return (
<>
{!blocks ? (
<PageTransition>
<main>
<h1>404 NOT FOUND</h1>
<p>
This page does not exist. Please check the URL and try again.
</p>
</main>
</PageTransition>
) : (
<>
{blocks.map((block, index) => (
<block.component {...block.componentProps} key={index}>
{block.content}
</block.component>
))}
</>
)}
</>
);
}
My focus is the 404 part, since my logic returns 200 OK
although there is no such a URL. I want it to return 404
. How should I implement this? Thanks in advance.
If you are using next js version 13 and above a simple not-found.js
file can be created in your app directory or src directory if that is being used.
By default this is a server component but can be marked async to fetch and display data. Also no props can be passed in this component.
src: https://nextjs.org/docs/app/api-reference/file-conventions/not-found