#Return HTML from APIRoute
3 messages · Page 1 of 1 (latest)
Hi @south ocean. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Astro's API routes are designed to handle various types of data, including HTML. However, the way you return the data from your API route can affect how it's interpreted by the client. If you're returning an object with body: rawHTML, it's likely being interpreted as a string, which is why you're seeing the raw text instead of rendered HTML.
To return HTML from an API route, you need to set the Content-Type header to text/html. Here's an example of how you might do this:
// Example: src/pages/api/profile.js
export async function post(params, request) {
const rawHTML = await request.json()
return new Response(rawHTML, {
status: 200,
headers: {
"Content-Type": "text/html",
},
})
}
Regarding the use of Node builtins, Astro recommends avoiding them whenever possible due to compatibility issues with multiple runtimes. However, if you really need to use them, Astro supports Node.js builtins using Node’s newer node: prefix. Here's an example of how you might read a file:
---
// Example: import the "fs/promises" builtin from Node.js
import fs from 'node:fs/promises';
const url = new URL('../../package.json', import.meta.url);
const json = await fs.readFile(url, 'utf-8');
const data = JSON.parse(json);
---
Please note that this is a general guide and you may need to adjust the code to fit your specific use case. For more information, you can refer to the Astro documentation (https://docs.astro.build).
Sources:
- Astro Blog: Experimental Server-Side Rendering (https://astro.build/blog/experimental-server-side-rendering)
- Astro Documentation: Node Builtins (https://docs.astro.build/en/guides/imports)