Install and setup Kilpi
Install Kilpi and setup your Kilpi instance by following the quickstart guide.
export const Kilpi = createKilpi({ ... }) Install ReactServerPlugin.
Install the ReactServerPlugin. It automatically…
- Caches the subject for you (using
React.cache). - Provides you with React Server Components.
- Provides you with the
Kilpi.$onUnauthorizedRscAssertmethod.
npm install @kilpi/react-serveryarn add @kilpi/react-serverpnpm add @kilpi/react-serverbun add @kilpi/react-serverApply the plugin in your Kilpi configuration as follows.
import { ReactServerPlugin } from "@kilpi/react-server";
export const Kilpi = createKilpi({ // ... plugins: [ReactServerPlugin()]})
const { Authorize } = Kilpi.$createReactServerComponents(); Read more about ReactServerPlugin for more details on usage.
Handle unauthorized errors from .assert()
The .assert() method throws an error when authorization is denied.
Since Next.js supports throwing redirections, handling unauthorized exceptions is easiest with a global onUnauthorizedAssert handler.
export const Kilpi = createKilpi({ // ... async onUnauthorizedAssert(decision) { // Optionally customize behavior based on the decision switch (decision.reason) { ... }
// By default, redirect user redirect("/sign-in"); }})Next steps
Here are some tips on how to best use Kilpi in a Next.js application.
1. Use <Authorize /> to protect your UI.
Simple example of protecting your UI.
export default async function DashboardPage() { return ( <Authorize policy={Kilpi.always()}> <Dashboard /> </Authorize> );}2. Setup page-specific error handlers.
For example, if you want unauthorized access to /posts/[id] to redirect to /posts, you can use Kilpi.$onUnauthorizedRscAssert as follows.
export default async function PostPage(props: PageProps) { const { id } = await props.params;
// If any assertion on this page fails, e.g. in // `getPost.authorized`, always redirect to `/posts`. Kilpi.$onUnauthorizedRscAssert(async (decision) => { redirect("/posts"); });
// Protected query which uses .assert() const post = await getPost.authorized(id);
return <PostDetails post={post} />;}3. Protect your client UI.
See usage on client and the ReactClientPlugin for more information on protecting your client-side application with the @kilpi/client and @kilpi/react-client packages.