Skip to main content
Version: v2.x

React Server Components as Adapters

With NLUX, React Server Components (RSC) can be directly used as a chat response and rendered to the user in the chat UI. This enables a rich and more interactive experience, and an enhanced chatbot interface.


Overview



At their core, React Server Components (RSC) are an HTML representation that's being written in React/JSX syntax. They are rendered on the server and sent to the client in a serialized form that can be interpreted by the React client runtime and rendered as a part of the React component tree.

RSC and Next.js

React Server Components are tightly integrated with Next.js. Pages in Next.js are server components by default, and the 'use server' directive is widely used to explicitly indicate that a component should be rendered on the server (as page, or server component).

The NLUX RSC adapter has been designed and developed with Next.js as the primary use-case. However, it can be used with any other RSC compatible server-side rendering setup.

With NLUX RSC adapters, you can create a server component that will receive the user's message, and conversation history, and return the generated content in JSX format. This content will be rendered in the chat UI as a response to the user's message.

This feature enables a wide range of possibilities, such as:

  • Generative user interfaces that can be powered by large language models (using Vercel AI, LangChain)
  • Advanced response generation logic that can be implemented on the server.

Usage



On the server:

'use server';

import { StreamedServerComponentProps } from '@nlux/react';

export default async function MyServerComponent<AiMsg>({ message, extras }: StreamedServerComponentProps) {
// Your logic here
// ...

// Return the generated content in JSX format
return <div>Generated Content</div>;
}

The React Server Component should be a default export function that takes an object with the following properties:

  • message - The prompt message typed by the user, to be sent to the API.
  • extras - An object containing additional information that the adapter might need, such as the conversation history.

On The Client:

import { AiChat, useAsRscAdapter } from '@nlux/react';
useAsRscAdapter<AiMsg = string>(
import('path/to/server-component'),
loader?: ReactNode,
);

The useAsRscAdapter() hook takes 2 parameters:

  • import('path/to/server-component') - The path to the server component that should be used as the adapter.
  • loader - An optional ReactNode that will be displayed while the server component is being loaded.

The useAsRscAdapter() hook returns an adapter that can be used in the <AiChat adapter={adapter} /> component. When a user sends a message, NLUX will take care of calling the server component with the appropriate parameters and updating the chat UI with the response as it's being received.