Return components from Route Handlers
Unanswered
Pastore della Lessinia e del Lag… posted this in #help-forum
Pastore della Lessinia e del LagoraiOP
Weird question but is there a way to render / stream React Components from Route Handlers?
api/components/route.ts
export const GET = () => {
return <Foo />
}
3 Replies
@joulev No. Use page.js files for that
Pastore della Lessinia e del LagoraiOP
are u sure that its not possible?
obviously I know we should use pages for that usually
obviously I know we should use pages for that usually
@Pastore della Lessinia e del Lagorai are u sure that its not possible?
obviously I know we should use pages for that usually
Well, it’s not technically impossible, but it’s so practically infeasible that you should just consider it impossible.
Route handlers can return any kind of http responses, so it can return html too. In the simplest form, you can use [renderToStaticMarkup](https://react.dev/reference/react-dom/server/renderToStaticMarkup) to convert the component to a string and return that string with Content-Type: text/html for example.
But that won’t give you interactivity (so e.g. useState won’t work). Then you need to do a bit more to get useState to work. Then you notice hydration is not working properly, so you need to do a bunch more to get it working. Then you realise you don’t have server components and streaming, there goes another huge effort to get that running. Before you know it you invented nextjs 2.
Instead of that, you just need to rename the file from route.ts to page.tsx. All problems solved. Nextjs takes care of everything for you. Hence my answer: “No. Use page.js instead”.
Route handlers can return any kind of http responses, so it can return html too. In the simplest form, you can use [renderToStaticMarkup](https://react.dev/reference/react-dom/server/renderToStaticMarkup) to convert the component to a string and return that string with Content-Type: text/html for example.
But that won’t give you interactivity (so e.g. useState won’t work). Then you need to do a bit more to get useState to work. Then you notice hydration is not working properly, so you need to do a bunch more to get it working. Then you realise you don’t have server components and streaming, there goes another huge effort to get that running. Before you know it you invented nextjs 2.
Instead of that, you just need to rename the file from route.ts to page.tsx. All problems solved. Nextjs takes care of everything for you. Hence my answer: “No. Use page.js instead”.