Nextjs blog route not found - how to handle
Unanswered
British Shorthair posted this in #help-forum
British ShorthairOP
Hey all, I am building a nextjs blog. I am currently reading about the not-found.js file and how it handles routes. I have one such file in the app folder. According to the documentation this will handle any errors in my routes for the 'whole application'. Now my blog - lets say is coolblog.com. If I do coolblog.com/hey which does not exist, my custom not-found file really is working. However I DO have a posts directory. If I do coolblog.com/posts/hey which hey.md does not exist but posts directory does exist I get the messy error message - Unhandled Runtime Error
Error: ENOENT: no such file or directory. Do I need another identical not-found.js file under app/posts/[slug]/not-found.js? Sorry the documentation is confusing me.
Error: ENOENT: no such file or directory. Do I need another identical not-found.js file under app/posts/[slug]/not-found.js? Sorry the documentation is confusing me.
9 Replies
@British Shorthair
Trigger the
For example:
https://nextjs.org/docs/app/api-reference/functions/not-found#notfound
Trigger the
notFound
function manually.For example:
import { notFound } from 'next/navigation'
export default async function Post({ params }) {
const post = await getPost(params.slug)
if (!post) {
notFound()
}
// ...
}
https://nextjs.org/docs/app/api-reference/functions/not-found#notfound
British ShorthairOP
yep, already did that
does not work in my case
I think that the "Error: ENOENT: no such file or directory." is thrown by your function that reads the markdown file. You may need to handle it when the markdown file is not found.
British ShorthairOP
ok, good idea, so regardless if I have a not-found file I still need to handle it in the getPostBySlug function which 'finds' the posts?
You need to trigger
notFound
function manually since next.js doesn't know when is 404 if you using dynamic routes (e.g. /posts/[slug]
). I'm not an expert but I think this is the reason.British ShorthairOP
I already do this with the custom NotFound file but the error come from the getPostBySlug
You need to handle this case.
For example:
For example:
const getPostBySlug = (slug) => {
// ...
// to check whether the file exists
if (!fs.existsSync(fullPath)) {
return null
}
// ...
}
British ShorthairOP
ok got it, will dig more, thank you very much