Astro Hybrid output with Server Endpoints (API Routes)

Has anyone managed to get Astro with output: "hybrid" mode working in CloudFlare pages with Server Endpoints https://docs.astro.build/en/guides/endpoints/#server-endpoints-api-routes Astro docs on CloudFlare adapter https://docs.astro.build/en/guides/integrations-guide/cloudflare/ claim that:
This adapter allows Astro to deploy your hybrid or server rendered site to Cloudflare.
But no matter what, I haven't been able to to get API Routes working with CloudFlare pages on "hybrid" mode. If I change to "server" output, then the API routes immediately start working. I'm using latest dependencies of everything with minimal setup. I've tried all sorts of combinations. So with server mode and with this configuration, it works:
export default defineConfig({
output: "server",
adapter: cloudflare({
imageService: "compile",
mode: "directory",
routes: {
strategy: "include",
include: ["/api/*"],
},
}),
});
export default defineConfig({
output: "server",
adapter: cloudflare({
imageService: "compile",
mode: "directory",
routes: {
strategy: "include",
include: ["/api/*"],
},
}),
});
… but if I change that output value to hybrid, it stops working. Or it "works" but it acts like a Static Endpoint, always returning Hello World! and ignoring the url search params. My super simple test endpoint at src/pages/api/hello.ts looks like this:
import { type APIRoute } from "astro";

export const GET: APIRoute = ({ request }) => {
const url = new URL(request.url);
const name = url.searchParams.get("name") || "World";

return new Response(
JSON.stringify({
message: `Hello ${name}!`,
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
},
);
};
import { type APIRoute } from "astro";

export const GET: APIRoute = ({ request }) => {
const url = new URL(request.url);
const name = url.searchParams.get("name") || "World";

return new Response(
JSON.stringify({
message: `Hello ${name}!`,
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
},
);
};
3 Replies
DaniFoldi
DaniFoldi3mo ago
Hi :meowwave:, you're only a simple addition away: In each file (.astro file or api route) that you want server-rendered in hybrid mode, you need to add
export const prerender = false
export const prerender = false
to it, and it should start working. This is an override similar to opting in to prerendering if your output mode was set to server. Docs, for reference: https://docs.astro.build/en/guides/server-side-rendering/#opting-out-of-pre-rendering-in-hybrid-mode
aripalo
aripalo3mo ago
And sure enough, with that addition it works! Thank you, you saved a lot of headache for me ❤️ Also I feel a bit stupid because I have another Astro website that is running in Netlify on hybrid mode and I realized I've used that export const prederender = false there already but totally forgot that one this time! Again million thanks! 🥳
DaniFoldi
DaniFoldi3mo ago
Glad it's working now :meowparty: