how to know if the app is on the not found page in nextjs 14 app router

108 Views Asked by At

I'm encountering difficulty determining if my Next.js application is on the 404 not-found page within the app router. I have a functioning 404 not-found page that displays when the URL doesn't match any routes defined in my app's router folder. However, there's a component named NewsLetter in the global layout file, so that displays on every page, including the 404 not-found page. I want to exclude this component from the 404 not-found page and from the newsletter-confirmation page.

I handle the exclusion of the NewsLetter component on the newsletter-confirmation page by checking the pathname and returning null before the component's return code if the pathname is /newsletter-confirmation. like this below

import { usePathname } from "next/navigation"

export default function Newsletter() {
  const pathname = usePathname();

  // Hide newsletter subscription section if the current path is the newsletter confirmation page
  if (pathname !== "/newsletter-confirmation") return null;

  return (
    <div>
      //rest code here...
    </div>
  )
}

However, I encountered an issue when trying to implement a similar logic for the 404 not-found page. When I logged the pathname, I noticed that it returns the random pathname currently in the URL. For instance, if I type /abcd in the URL, I'll get the value abcd as the pathname value, making it unusable for my purposes.

I've tried searching extensively online but haven't found a solution. How can I reliably determine if my app is on the Not Found page within the app router, so I can handle the exclusion of the NewsLetter component appropriately.

I've attempted to conditionally render a NewsLetter component inside the Layout file based on whether the current page is the 404 not-found page. However, I haven't been able to find a solution anywhere online, in the documentation, or in related questions on forums. I've even posted my question on the Next.js community forum, but unfortunately, I haven't received an answer yet.

My goal is to dynamically hide the NewsLetter component if the current page is the 404 not-found page. This would allow me to create exact web design, ensuring that the NewsLetter component isn't displayed on the 404 not-found page. Any insights or solutions would be greatly appreciated.

0

There are 0 best solutions below