Install & setup Kilpi
Install Kilpi and setup your Kilpi instance by following the quickstart guide.
export const Kilpi = createKilpi({ getSubject, policies, ...})
Install React Server Components plugin
To automatically provide a scope for React Server Components, install the React Server Components Plugin.
npm install @kilpi/react-server
yarn add @kilpi/react-server
pnpm add @kilpi/react-server
bun add @kilpi/react-server
Apply the plugin in your Kilpi configuration as follows.
export const Kilpi = createKilpi({ getSubject, policies, plugins: [ReactServerComponentPlugin()]})
Read more about the plugin for more details on usage and available components.
Optional: Use Kilpi React Server Components
Use Kilpi to protect your UI in React Server Components with the components provided by the React Server Components plugin.
export const { Access } = Kilpi.ReactServer.createComponents();
<Access to="documents:create" Unauthorized={<p>Not authorized to create documents</p>}> <CreateDocumentForm /></Access>
Read more about the Access component and other components provided by the plugin.
Provide scope for server actions and endpoints
To use the full feature set of Kilpi, you need to provide a scope for each request. The React Server Components can automatically only provide a scope for React Server Components.
To provide a scope for server actions, you can use the Kilpi.scoped
function to wrap each server action.
export const myServerAction = Kilpi.scoped(async () => { await Kilpi.onUnauthorized(() => { ... }); // Works due to Kilpi.scoped await Kilpi.authorize(...); // Works due to Kilpi.scoped // ...});
To provide a scope for endpoints, you can use the Kilpi.scoped
function to wrap each endpoint.
export const POST = Kilpi.scoped(async (request: Request) => { await Kilpi.onUnauthorized(() => { ... }); // Works due to Kilpi.scoped await Kilpi.authorize(...); // Works due to Kilpi.scoped // ... return new Response();});
If you’re using next-safe-action
or similar framework for authoring server actions, you can use the middleware approach as follows with Kilpi.runInScope
.
export const ActionClient = createSafeActionClient({ ... }) .use(async ({ next }) => { return await Kilpi.runInScope(async () => { // Optionally setup a global authorization error handler here Kilpi.onUnauthorized((error) => { ... });
// Run the action within the scope return await next(); }); });
Optional: Install Kilpi for React Client
To use Kilpi on the client and in client components, you must install and setup @kilpi/client and @kilpi/react-client for client-side bindings.