React Server Components (RSC) Plugin


Installation

Install the plugin with your package manager of choice.

Terminal window
npm install @kilpi/react-server

Apply the plugin in your Kilpi configuration as follows.

kilpi.ts
import { createKilpi } from "@kilpi/core";
import { ReactServerComponentPlugin } from "@kilpi/react-server";
export const Kilpi = createKilpi({
getSubject,
policies,
plugins: [ReactServerComponentPlugin()]
})

Automatic scope for RSCs

The plugin automatically provides a scope for React Server Components.

export default async function ProtectedPage() {
Kilpi.onUnauthorized(() => redirect("/")); // Just works
Kilpi.authorize("any:policy");
return <div>...</div>;
}

Components

Use the Kilpi.ReactServer.createComponents function (provided by the plugin) to create React server component bindings for working with Kilpi.

kilpi.components.ts
export const { Access } = Kilpi.ReactServer.createComponents();

<Access />

Access is used to show or hide components based on the user’s authorizations.

Access is an asynchronous component which implement <Suspense /> internally, allowing you to stream in UI and use a loading fallback.

async function Component({ comment }) {
return (
<div>
<p>{comment.content}</p>
<Access
to="comments:delete"
// Required only if policy takes in a resource
on={comment}
// Optional fallback UIs
Loading={<p>Loading...</p>}
Unauthorized={<p>Unauthorized</p>}
>
<button>Delete</button>
</Access>
</div>
);
}