Next.js Discord

Discord Forum

notFound() not working in app router. Error thinks I am using pages router.

Answered
American Wirehair posted this in #help-forum
Open in Discord
Avatar
American WirehairOP
I have the following code in /src/spp/page.tsx:
import { getPayload } from 'payload'
import config from '@payload-config'
import { notFound } from 'next/navigation'

const payload = await getPayload({ config })

const settings = await payload.findGlobal({ slug: 'settings' })
const pageQueryRes = await payload.find({
  collection: 'pages',
  where: {
    slug: {
      equals: '',
    },
  },
})

if (pageQueryRes.docs.length == 1) {
  // TODO: Implement notFound
  notFound()
}

const page = pageQueryRes.docs[0]

export const metadata = {
  title: settings?.siteTitle || 'Test',
  description: settings?.siteDescription || 'Generated by Next.js',
}

export default async function Page() {
  console.log(page)
  return <div></div>
}


However when the notFound() function is invoked I get the following error:
Error: Next.js navigation API is not allowed to be used in Pages Router.
    at notFound (webpack-internal:///(rsc)/./node_modules/next/dist/client/components/not-found.js:28:19)
    at eval (webpack-internal:///(rsc)/./src/app/(frontend)/page.tsx:32:62)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Answered by joulev
You need to call all that data fetching stuff inside the page component
View full answer

10 Replies

Answer
Avatar
American WirehairOP
thanks
Avatar
You shouldn’t do anything in the root scope (outside page component, generateMetadata etc)
Avatar
@joulev You shouldn’t do anything in the root scope (outside page component, generateMetadata etc)
Avatar
American WirehairOP
Can I do datafetching there if I need it for metadata?
And if I do datafetching in both scopes should I be redefining "payload" in both scopes or can I define it in the root scope and then use it in the component?
Avatar
@American Wirehair Can I do datafetching there if I need it for metadata?
Avatar
Then you need to use generateMetadata, and also call the data fetching stuff there. Use React.cache to ensure that though the data fetching part is called twice, it only runs once
Avatar
American WirehairOP
Ahh I see
Avatar
@American Wirehair And if I do datafetching in both scopes should I be redefining "payload" in both scopes or can I define it in the root scope and then use it in the component?
Avatar
That one I’m not sure because I don’t use payload cms. Check their docs to see what they recommend when using it with nextjs. Though defining it inside the component will definitely work
Avatar
Eurasian Wryneck
I think the reason following.
If using the App Router (spp/ directory), keep notFound().