SolidJSS
SolidJSβ€’4mo agoβ€’
9 replies
dylanj

How to manually invoke server functions?

Hey all, have a bit of a weird problem trying to combine SolidStart with Cloudflare Durable Objects and Server Functions.

The following works great, unless the server function is used during server side rendering, in which case the "request" context that we forward to the durable object is for the page being rendered, not for the invocation of the server function. So the durable object responds with the fully rendered page, instead of the server function result. As you can imagine, this causes issues. It's easy enough to detect when this happens, but I can't figure out how to construct a new request to send to the Durable Object to invoke just the server function?

Or perhaps it would be best to skip any rendering on the worker entirely, and just send the whole request to the durable object to begin with. However this would require me to fork the cloudflare-durable preset.

export const increment = async (gameId: string) => {
  "use server";
  const event = getRequestEvent()!;
  const cloudflare = event.nativeEvent.context.cloudflare;

  // We're in the worker not the durable object
  if (!cloudflare.durable) {
    const binding = cloudflare.env.GAME;
    const id = binding.idFromName(gameId);

    return (await binding.get(id).fetch(event.request)) as number;
  }

  let value: number = (await cloudflare.context.storage.get("counter")) || 0;

  value += 1;
  await cloudflare.context.storage.put("counter", value);

  return value;
};
Was this page helpful?