Next
Install Kilpi for Next
Ensure you have setup Kilpi using the quickstart guide before proceeding.
Install plugins
Install the React Server Components Plugin (@kilpi/react-server
) to use Kilpi with React Server Components.
Optional: Install the React Client Components Plugin (@kilpi/react-client
) for component and hook bindings into @react/client
on the client.
Provide a scope for server actions and endpoints
The React Server Components Plugin can’t automatically provide a scope for server actions or endpoints as there is no global request-scoped API. You have to do this manually with Kilpi.runInScope
to use all Kilpi features, such as Kilpi.onUnauthorized
.
The ReactServerComponentPlugin
from @kilpi/react-server
automatically provides a scope for react server components.
Wrap each server action with Kilpi.runInScope
as follows.
"use server"
export async function myServerAction() { return await Kilpi.runInScope(async () => { // Your logic wrapper in scope });}
Or better, when using next-safe-action
or similar framework for authoring server actions, you can use the middleware approach as follows.
export const ActionClient = createSafeActionClient({}) .use(async ({ next }) => { return await Kilpi.runInScope(async () => { // Tip: This is a great place to setup a // global error handler for server actions
// Run the action within the scope return await next(); }); });
Wrap each endpoint with Kilpi.runInScope
as follows.
export const POST = async function handle(request: Request) { return await Kilpi.runInScope(async () => { // Your endpoint... return new Response(); });}