Next.js Discord

Discord Forum

How to detect if a URL will 404 or not in Middleware?

Unanswered
Res posted this in #help-forum
Open in Discord
ResOP
If I do something like this, it'd add too much overhead to every page:

async function middleware(request){
  const res = await fetch(request.nextUrl)
  if (res.status === 404){
      doSomething()  
  }
}


I can also recursively go through all the folders, get the paths and check if a path exists in this json file I'll create in build time, in the middleware.

if (!pathMatch(url.pathname, pagePaths)) {
        doSomething()
    }


Problem with this approach is dynamic routes. (And also rewrites and redirects in next.config file. This doesn't take that into account as it just grabs the paths from app/ folder)

Say if I have /notes/[note]. I would match /notes/1 /notes/2/ and so on.
But if I get a /notes/kaljsdklajsdlk1212312 and it'd 404, I wouldn't know, using this approach.

I'm out of ideas, let me know if you have any ideas / leads.
Thanks in advance.

0 Replies