Next.js Discord

Discord Forum

Giving "not-found" response for app router.

Unanswered
Gray-breasted Martin posted this in #help-forum
Open in Discord
Gray-breasted MartinOP
I have a project which is using the app router. We are using our own design system. So, we have to use "use client" flag for all pages.

However, some of the pages have generic Ids coming from the routing. To check one of this id is valid or not, when page is loading, we are asking an endpoint. Because the page is client component, a loading component is rendering while validation endpoint respond.

If we think this process from perspective of SEO and CSR, the page is returning 200 status. For example;

- The domain is x.com.
- x.com/items/[itemId] is our generic route. When I am checking the itemId valid or not, my page is rendering loading component because it is client component.
- So, the app is returning status 200.
- But there is no page related to this id.


What I have tried;

- Middleware;
I have checked this id at middleware and I can return 404. But I couldn't show any custom 404 UI.

What are your suggestions at this point?

Using version nextjs@14.1.0

6 Replies

you can use notFound function to redirect to the 404 UI
import { notFound } from 'next/navigation'

and create this file -> app/not-found.tsx
you can put your 404 UI here
Gray-breasted MartinOP
For the UI, it is okay. But the SEO based, I am rendering the loading component at page and the page status is returning 200 while it should return 404.

On the other hand, notFound function couldn't be used inside the middleware as my know-how from the docs, discussions and my tries even if there is a not-found page under my app directory.
can i see the middleware?

I think its something like this

export function middleware(request: NextRequest) {

if(404condition){
return NextResponse.redirect(new URL('/notfound', request.url))}
}
or do you want to show on the page the 404 UI?
if you dont want to redirect to the not found page, you could set it as a cookie on the middleware, and read the cookie on the page
Gray-breasted MartinOP
I am thinking that cookie solution is more valid for my case. Thank you.