javascriptreactjstypescriptreact-hooksremix.run

How to redirect to a custom 404 page in remix.run?


I am trying to redirect the URL to a custom 404 page in remix.run but not able to do so. I have a url structure something like this -

app/
 ├── routes/
 │   ├── $dynamicfolder/
 │   │   ├── index.tsx
 │   │   ├── somepage.tsx
 │   │   ├── $.tsx
 │   └── index.tsx
 └── root.tsx

I have a certain number of pages under $dynamicfolder and they are accessible like this -

"https://example.com/xx/" (This is to access the index.tsx, I have 2 fixed values that are 
passed in "$dynamicfolder", let's say xx and xy),


"https://example.com/xx/somepage" (This is to access the other page)

When some other random value is passed in $dynamicfolder, let's say "yy", like this -

"https://example.com/yy/"

then I want that to be handled by $.tsx which is also inside $dynamicfolder. Unfortunately, that's not happening and it is throwing an obvious error.

I am accessing the value of $dynamicfolder in $dynamicfolder/index.tsx using useParams() hook. I just want to redirect the page to 404 when any other value apart from xx and xy is passed.

I did follow the remix docs, Splat URLs and Dynamic routes parameters but maybe I am doing some kind of mistake that I am not able to catch.

It is also possible that I might be doing it in the wrong way as I am new to remix.run. Any help would be appreciated. Thanks.


Solution

  • In your loader, check the params and throw new Response("Not found", { status: 404 }) as needed. Throwing a response will render the closest <CatchBoundary>

    In your root route, export a <CatchBoundary> to display your custom 404 error.

    https://remix.run/docs/en/v1/guides/not-found#root-catch-boundary