Cartesiandocs

React SDK

Quickstart

Sign a shopper in with a token and show the assistant in a React app.

Create the client

Create one CartesianClient for your app, outside your components.

cartesian.ts
import { CartesianClient } from "@cogitx/cartesian-react";

export const cartesian = new CartesianClient({
  vertical: "grocery",
  baseUrl: "https://assistant.freshmart.com",
});

Wrap your app

App.tsx
import { CartesianProvider, CartesianPanel, CartesianAskButton } from "@cogitx/cartesian-react";
import "@cogitx/cartesian-react/styles.css";
import { cartesian } from "./cartesian";

export function App() {
  return (
    <CartesianProvider client={cartesian} options={{ title: "FreshMart" }}>
      <Shop />
      <CartesianAskButton style={{ position: "fixed", right: 20, bottom: 20 }} />
      <CartesianPanel />
    </CartesianProvider>
  );
}

Sign the shopper in

After your own sign-in, ask your backend for a Cartesian session token and pass it to the SDK. The SDK never handles passwords.

const { token } = await fetch("/me/cartesian-session").then((r) => r.json());
await cartesian.signIn(token);
tsx

The token is saved in localStorage. On the next page load the client starts in the restoring state and the provider checks the token again with GET /api/auth/session.

Session rules

Response to GET /api/auth/sessionResult
200signedIn. The socket connects and the cart, wishlist and threads load.
401The token is cleared and the state becomes signedOut. onSignInRequired() is called.
5xx or a network errorThe token is kept and the state stays restoring. The provider retries with backoff (2 s doubling to 30 s) and again when the browser comes back online.

A 401 on any later request also signs the shopper out. Call cartesian.signOut() when the shopper signs out of your app.

Embed instead of a panel

CartesianChat fills its parent. Give the parent a height:

<div style={{ height: "100vh" }}>
  <CartesianChat />
</div>
tsx

Server-side rendering

The package works with server-rendered React. The entry is marked "use client", so in the Next.js App Router you can import the components into a client component. Create the client in the browser only, for example in a module that only client components import.

Next