The Docs.

Prim+RPC is in prerelease mode and may be unstable until official release.
All Plugins

Astro

Plugin Details
  • Plugin Type:
    Method Handler
  • Transport:
    HTTP
  • Works with:

Prim+RPC supports Astro in SSR mode.

Let’s say that you have a module like so (you can place functions wherever you’d like):

export function hello() {
	return "Hi from Prim+RPC!"
}
hello.rpc = true
 
export default hello

You may configure Prim+RPC with Astro’s Server Endpoints by using a catch-all route in your pages directory:

import { createPrimServer } from "@doseofted/prim-rpc"
import { defineAstroPrimHandler } from "@doseofted/prim-rpc-plugins/astro"
import * as module from "../../server"
 
const prim = createPrimServer({ module })
 
// Astro 3+
export const { GET, POST } = defineAstroPrimHandler({ prim })
// Only if Astro <=3 (exported method names were lowercase)
export const { GET: get, POST: post } = defineAstroPrimHandler({ prim })

Your Prim+RPC server is now set up! Astro is a fullstack framework that runs on both server and client, which means the Prim+RPC client may be called on the server.

On the server, you can avoid a network request from the client by conditionally passing the module. Below is an example of how you may do so, using the Fetch API method plugin:

import { createPrimClient } from "@doseofted/prim-rpc"
import { createMethodPlugin } from "@doseofted/prim-rpc-plugins/browser"
import type * as Module from "./server"
 
const endpoint = import.meta.env.SSR ? "" : "/prim"
const module = import.meta.env.SSR ? import("./server") : null
const methodPlugin = createMethodPlugin()
export const client = createPrimClient<Promise<Module>>({ endpoint, module, methodPlugin })

Now this exported client may used from anywhere in your project:

---
import { client } from "../client"
const greeting = await client.hello()
---
 
<p>Server rendered: {greeting}</p>
<p>Client rendered: <span id="client-rendered"></span></p>
 
<script>
	import { client } from "../client"
	const clientRendered = document.getElementById("client-rendered")
	if (clientRendered) clientRendered.innerText = await client.hello()
</script>

You may also choose a compatible method plugin:

Report an Issue