#Render components as HTML string (or any other technique to return a `Response` with custom HTML)

5 messages · Page 1 of 1 (latest)

stone crystal
#

Hello Astro community,

After extensive searches... check the following case:

---
// ,,,
const data = await someDataFetchingFunction();
if (!data) {
  return new Response("not found", {
    status: 404,
    statusText: 'Not found'
  });
}
---
<MyStuff/>

it's a simple case of returning a 404 page in case some data fetching operation wasn't successful.
Now, the question is.. if I wanted to return a custom page / custom HTML instead of the not found string, what could be the best approach ?

Options I thought about:

  • using fs.readFile with a pre-generated single page html file
  • redirect to a /404 (very bad tho)
  • using conditions in the component, such as { data && ( <MyStuff/ ) || <My404/> } but i'd really rather not do that.

The ideal solution would be to have a 404.astro page being either exportable as HTML or returnable as component.
Something like:

import my404 from 'http404.astro'

return new Response(my404.render(), { status: 404 })

Is there anything like that around ?
Thanks !

burnt verge
stone crystal
#

@burnt verge that works! the [...any] approach also in combination to being used as middleware works too

#

thank you a lot!

#

is there anything similar for 500 error pages?