How To Secure a Vite-Powered React App With Seald End-to-End Encryption

With data breaches becoming increasingly common globally, end-to-end encryption has become essential. This article provides a step-by-step guide on implementing robust security measures by encrypting a chat application end-to-end, ensuring that private information is shielded from unauthorized access.
Header image

When sending messages across a chat app, one way to ensure the data and conversations are not intercepted is to build proper security to shield people who use the app. This article dives into how to implement strong end-to-end (E2EE) encryption in your app to protect users. We will integrate Seald's E2EE into Stream's Chat to provide a secure chat messaging environment for all participants.

Refer to this introductory tutorial to learn more about general concepts of E2EE.

Project Goal

The objective of the demo project involved in this tutorial is to ensure that chat conversations are only visible to channel members using the Stream Chat React SDK and the Seald end-to-end encryption SDK. That means these messages are not sent in plain text and can not be read server-side, as this might be an attack vector for a malign party. The example above demonstrates an encrypted chat using the Seald SDK. You have observed that sending a plain text message converts it to a cipher text. That is our main task for this tutorial. Only the message text is encrypted: metadata such as mentions, quoted-message IDs, and reactions stays readable to Stream.

The final end-to-end encrypted project is on GitHub. You can follow the steps in this tutorial and set up your own Next.js application. Or you can also create a new GitHub Code Space to run the app. The .env file in the GitHub project requires your Seald credentials. For a sample of how the .env file should look, you can check the .env.template file in the project. In the following sections, we'll dive into creating Seald and Stream accounts.

Setting Up A Stream Account

This section focuses on signing up for a Stream Chat account to get user credentials for the app.

Create a Stream account

In the chat messaging part of the app, we should create a new app on Stream Dashboard. Then, create a new user and a chat channel. We can now generate a token using the account's API Secret. Head to the Stream website, click Start Coding Free, and fill out your information to get an account.

After logging in to the account, you should do the following.

  • Create a new app by clicking the button Create App on the top right of the page.
  • To add a new channel, navigate to Chat Messaging -> Explorer -> Channels -> Create new channel. For this demo, let's use EncryptedChannel.
Create a new channel
  • Select Chat Messaging -> Explorer -> Users -> Create new user to add a new one. Let's call our new user TestUser.
Create a new user

We will shortly use the EncryptedChannel, and the TestUser to connect to the chat SDK's backend infrastructure.

Initiate a Next.js App

Unencrypted Chat

In this section, we create a new Next.js project and install all the necessary chat dependencies. We will add the end-to-end encryption dependencies when the unencrypted chat messaging functionality works successfully. Ensure you have npm or yarn installed, and create a new Next.js project with the following command:

npx create-next-app@latest

We follow the setup process to make sure the project is correctly configured:

What is your project named? end-to-end-encrypted-chat
Would you like to use TypeScript? Yes
Would you like to use ESLint? Yes
Would you like to use Tailwind CSS? Yes
Would you like your code inside a `src/` directory? No
Would you like to use App Router? (recommended) Yes
Would you like to use Turbopack for `next dev`?  Yes
Would you like to customize the import alias (`@/*` by default)? No
What import alias would you like configured? @/*

We have end-to-end-encrypted-chat as the project name and use TypeScript, ESLint, and TailwindCSS. The rest of the setup follows the recommended steps.

Next, launch the project in VS Code or your favorite IDE, cd into the end-to-end-encrypted-chat directory and use yarn or npm i stream-chat stream-chat-react @stream-io/node-sdk to fetch and install:

  • Stream Chat stream-chat: The core chat SDK without UI components.
  • Stream Chat React stream-chat-react: React chat SDK consisting of reusable UI components.
  • Stream Node SDK @stream-io/node-sdk: The server-side SDK we use to generate user tokens. It requires Node.js 22.12 or later.

Note: In VS Code, you can press the keyboard shortcut ⌃` to bring the integrated Terminal and run the above command.

Configure the Chat SDK

In this section, we set up the chat SDK to provide basic chat messaging functionality. All the files can also be found in the GitHub repository.
Go to the app's app directory, open page.tsx, and start by defining a type for the HomeState at the top of the file:

type HomeState = {
  apiKey: string;
  user: ClientUser;
  token: string;
};

We use this type to ensure that we initialize the chat only when we have received an authentication token (we will create the logic for this in the next step). The token is received using an API call to the route api/token.
We create a getUserToken function (wrapped in a useCallback hook) that we call in a useEffect hook. Here is the code for the page.tsx file:

export default function Home() {
  const [homeState, setHomeState] = useState<HomeState | undefined>();

  const userId = "TestUser";
  const userName = "TestUser";

  const getUserToken = useCallback(async (userId: string, userName: string) => {
    const response = await fetch("/api/token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ userId: userId }),
    });

    const responseBody = await response.json();
    const token = responseBody.token;

    const user: ClientUser = {
      id: userId,
      name: userName,
      image: `https://getstream.io/random_png/?id=${userId}&name=${userName}`,
    };

    const apiKey = process.env.NEXT_PUBLIC_STREAM_API_KEY;
    if (apiKey) {
      setHomeState({ apiKey: apiKey, user: user, token: token });
    }
  }, []);

  useEffect(() => {
    getUserToken(userId, userName);
  }, [userId, userName, getUserToken]);

  if (homeState) {
    return <MyChat {...homeState} />;
  } else {
    return <LoadingIndicator />;
  }
}

We need to add two things. The first is to create a Route Handler that is executed server-side and generates a token for the current user (which is what we call inside the getUserToken function).
We create a new folder api, then inside a new folder called token and inside a file called route.ts. The code inside uses the Stream secret to issue a token for a user:

import { StreamClient } from "@stream-io/node-sdk";

export async function POST(request: Request) {
  const apiKey = process.env.NEXT_PUBLIC_STREAM_API_KEY!;
  const streamSecret = process.env.STREAM_SECRET!;

  const serverClient = new StreamClient(apiKey, streamSecret);

  const body = await request.json();
  const userId = body?.userId;

  const token = serverClient.generatePermanentUserToken({ user_id: userId });
  const response = {
    userId: userId,
    token: token,
  };

  return Response.json(response);
}

In the Route Handler we are using two environment variables. For that we create a new .env file in the route of our project and fill that with the values we get from the Stream Dashboard (see earlier section):

NEXT_PUBLIC_STREAM_API_KEY=<your-api-key>
STREAM_SECRET=<your-stream-secret>

Notably, the API key secret is prefixed with NEXT_PUBLIC_ because it will be available on the client side, which is safe from a security standpoint. However, the secret should never be exposed to the client and only be available on the server, so we omit the prefix here.

Now that the setup is done, we can focus on showing the UI. Inside page.tsx we used a component called MyChat, that we haven't yet created. We create a new folder called components and inside create a file named MyChat.tsx.

We will need to add additional code later, but for now, we want to initialize a chat experience, and for that, we use the pre-built components that come with Stream's React SDK.

Before we can use those, we need to initialize the SDK using the three properties we've defined in our HomeState earlier: an apiKey, an authentication token, and a user object. We hand those in as parameters to the component and then call the built-in useCreateChatClient hook.

The code for the entire MyChat.tsx file looks like this:

import { useEffect, useMemo } from "react";
import { ChannelPaginator } from "stream-chat";
import type { ChannelFilters, ClientUser, SortParamRequest } from "stream-chat";
import {
  ChannelHeader,
  ChannelNavigation,
  Chat,
  LoadingIndicator,
  MessageComposer,
  MessageList,
  ThreadHeader,
  WithComponents,
  useCreateChatClient,
} from "stream-chat-react";
import { ChannelSlot, ChatView, ThreadSlot } from "stream-chat-react/slot-layout";
import type { LayoutDescriptor } from "stream-chat-react/slot-layout";
import EncryptedMessage from "./EncryptedMessage"; // we create this component later in the post

const layouts: LayoutDescriptor[] = [
  { id: "channels", slots: ["channel", "thread"] },
];
const overrides = { MessageUI: EncryptedMessage };

export default function MyChat({
  apiKey,
  user,
  token,
}: {
  apiKey: string;
  user: ClientUser;
  token: string;
}) {
  const chatClient = useCreateChatClient({
    apiKey: apiKey,
    tokenOrProvider: token,
    userData: user,
  });

  // Chat sorting options
  const paginator = useMemo(() => {
    if (!chatClient) return undefined;
    const sort: SortParamRequest[] = [
      { direction: -1, field: "last_message_at" },
    ];
    const filters: ChannelFilters = {
      type: "messaging",
      members: { $in: [user.id] },
    };
    return new ChannelPaginator({
      client: chatClient,
      id: "my-channels",
      filters,
      sort,
      paginatorOptions: { pageSize: 10 },
    });
  }, [chatClient, user.id]);

  useEffect(() => {
    if (!chatClient || !paginator) return;
    chatClient.channelManager.insertPaginator({ paginator });
    return () => {
      chatClient.channelManager.removePaginator(paginator);
    };
  }, [chatClient, paginator]);

  if (!chatClient || !paginator) {
    return <LoadingIndicator />;
  }

  return (
    <Chat client={chatClient}>
      <WithComponents overrides={overrides}>
        <ChatView
          layouts={layouts}
          views={{
            channels: (
              <>
                <ChannelNavigation />
                <ChannelSlot slot="channel" fallback={<p>Select a conversation to start chatting</p>}>
                  <ChannelHeader />
                  <MessageList />
                  <MessageComposer />
                </ChannelSlot>
                <ThreadSlot slot="thread">
                  <ThreadHeader />
                  <MessageList />
                  <MessageComposer />
                </ThreadSlot>
              </>
            ),
          }}
        />
      </WithComponents>
    </Chat>
  );
}

In summary, we import the required chat components such as Chat, ChatView, ChannelNavigation, and others. ChatView and the slot components come from the stream-chat-react/slot-layout entry point. We also create a ChannelPaginator for the channel list, with its sort, filters, and page size, and register it on chatClient.channelManager, which is where ChannelNavigation reads the lists it renders. Then, we check if the chatClient has already been initialized. If not, we show a loading indicator; if yes, we show the whole chat experience.

Add Styling To The Chat Layout

We can run the app but we will see that the styling is off. We need to follow two more steps to fix this. The first is to import the CSS code that ships with the Stream SDK. We add it to app/layout.tsx, directly above the existing globals.css import:

// The SDK stylesheet must load before globals.css, so the app's overrides
// (e.g. --str-chat__channel-list-width) win over the SDK defaults.
import "stream-chat-react/dist/css/index.css";
import "./globals.css";

What it does is make sure the necessary CSS classes and code are loaded that are used inside the custom components that we added to the MyChat.tsx file. The order matters: the SDK stylesheet sets the same CSS variables we override next, so it has to load first. There are many options to customize this; you can learn more in the Theming section of our docs.

The second step is to add the following CSS code to the globals.css file in our app folder. Add the following code below the existing code in globals.css:

body {
  display: flex;
}

.str-chat {
  --str-chat__channel-list-width: 30%;
}

.str-chat__channel {
  width: 100%;
}

Press control and backtick (⌃ ) to launch the Terminal in VS Code and run npm run devto start the development server. We will seeLocal: http://localhost:3000/` to preview the app. The channel list loads with no channel open, so click the encrypted channel to open it. The output of the unencrypted chat interface after selecting the channel is similar to the video preview below.

We can now see that sending and reading messages works for all members of a channel. However, these chats are not encrypted, meaning they are stored in plain text on the backend, which offers a vulnerability if a malign party achieves access to our servers. Let's fix that by securing messages to make them non-human readable with end-to-end encryption in the following sections.

Setup The Seald SDK For E2E-Encryption

Create a seald account

To use the Seald client-side encryption SDK for the first time, we need to create a staging environment account on their website. Once our account is ready, we can sign in to the dashboard to get started with our generated JSON Web Token secret or create a new JWT secret in the administration panel.

First, copy all the user credentials from your Seald administration dashboard. Open the .env file in the project's root folder and add the following code below the previous credentials (replace with the your own dashboard data):

NEXT_PUBLIC_SEALD_APP_ID="YOUR_SEALD_APP_ID"
NEXT_PUBLIC_SEALD_API_URL="https://api.staging-0.seald.io/"
NEXT_PUBLIC_KEY_STORAGE_URL="https://ssks.staging-0.seald.io/"
JWT_SECRET="YOUR_JWT_SECRET"
JWT_SECRET_ID="YOUR_JWT_SECRET_ID"

The JWT secret needs the JOIN_TEAM and ADD_CONNECTOR permissions, which you can set when you create it in the dashboard.

To integrate the Seald encryption service directly into our app, we must install the NPM package @seald-io/sdk which is compatible with both mobile and web apps. In our project, we will navigate to the root directory and run one of the following command to install the SDK.

npm i -S @seald-io/sdk
#or
yarn add @seald-io/sdk

Inside the SDK we need to create identities to manage the encryption and who has permission the decrypt certain messages. For this we can use passwort protection of the identities (there is also the alternative to use a 2-man-rule).

We can install the relevant password protection package like this:

npm i -S @seald-io/sdk-plugin-ssks-password
#or
yarn add @seald-io/sdk-plugin-ssks-password

To verify if the above packages were installed successfully, open your project's package.json and check the dependencies section.

"dependencies": {
    "@seald-io/sdk": "^0.30.0",
    "@seald-io/sdk-plugin-ssks-password": "^0.30.0",
    "next": "14.2.10",
    "react": "^18",
    "react-dom": "^18",
    "@stream-io/node-sdk": "^0.9.6",
    "stream-chat": "^10.2.0",
    "stream-chat-react": "^15.0.2"
  },
Get started! Activate your free Stream account today and start prototyping your chat app.

Initializing The Seald SDK With A Context Object

After installing the Seald SDK, there are a few steps to follow to encrypt and decrypt an app. To do this we will create a Context object (see more info on the topic here) to inject the necessary data into the DOM tree.

To have a central way of handling all encryption-related matters, we inject a SealdContextProvider. This takes care of holding on to the relevant variables and provides the necessary functions for performing the encryption and decryption of messages.

Create a new folder called contexts and inside a new file called SealdContext.tsx. The first thing we do is to import the dependencies for the Seald SDKs, along with React and three helpers we write in a moment:

import React, { useCallback, useContext, useRef } from "react";
import { createContext, useState } from "react";
import SealdSDK from "@seald-io/sdk";
import SealdSDKPluginSSKSPassword from "@seald-io/sdk-plugin-ssks-password";
import type { EncryptionSession } from "@seald-io/sdk/lib/main.js";
import { getDatabaseKey } from "@/lib/getDatabaseKey";
import { registerUser } from "@/lib/registerUser";
import { sealdConnector } from "@/lib/sealdConnector";

Then, we define a state called SealdState for this (check the code comments for what each variable does):

type SealdState = {
  sealdClient: ReturnType<typeof SealdSDK> | undefined; // necessary for calling further functions
  sealdId: string | undefined; // the user's Seald identity
  /** The Stream user ID of the current user. */
  userId: string | undefined;
  loadingState: "loading" | "finished" | "error";
  /** Why Seald couldn't be initialized, when `loadingState` is `"error"`. */
  error: string | undefined;
  initializeSeald: (userId: string, password: string) => void;
  /**
   * Encrypts a message for everyone in the channel. Creates the channel's
   * encryption session on the first message, for the members `getMemberIds`
   * returns (Stream user IDs). Throws if the message can't be encrypted.
   */
  encryptMessage: (
    message: string,
    channelCid: string,
    getMemberIds: () => Promise<string[]>,
  ) => Promise<string>;
  /**
   * Decrypts a message of the channel `channelCid`. Throws if it can't be
   * decrypted, or if it was encrypted for another channel.
   */
  decryptMessage: (
    message: string,
    sessionId: string,
    channelCid: string,
  ) => Promise<string>;
  /**
   * Drops the session of a channel (or of all channels when no cid is given),
   * e.g. after its members changed. The next message creates a new session for
   * the current members.
   */
  resetChannelSession: (channelCid?: string) => void;
};

Next, we define the context's initial value and both the SealdContext and the SealdContextProvider objects. Until Seald is initialized, encrypting and decrypting throw instead of returning anything:

const initialValue: SealdState = {
  sealdClient: undefined,
  sealdId: undefined,
  userId: undefined,
  loadingState: "loading",
  error: undefined,
  initializeSeald: async () => {},
  encryptMessage: async () => {
    throw new Error("Seald is not initialized.");
  },
  decryptMessage: async () => {
    throw new Error("Seald is not initialized.");
  },
  resetChannelSession: () => {},
};

export const SealdContext = createContext<SealdState>(initialValue);

export const SealdContextProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [myState, setMyState] = useState<
    Pick<
      SealdState,
      "sealdClient" | "sealdId" | "userId" | "loadingState" | "error"
    >
  >({
    sealdClient: undefined,
    sealdId: undefined,
    userId: undefined,
    loadingState: "loading",
    error: undefined,
  });
  const initializationRef = useRef(false);

  // More code to be inserted here

  const store: SealdState = {
    sealdClient: myState.sealdClient,
    sealdId: myState.sealdId,
    userId: myState.userId,
    loadingState: myState.loadingState,
    error: myState.error,
    initializeSeald,
    encryptMessage,
    decryptMessage,
    resetChannelSession,
  };

  return (
    <SealdContext.Provider value={store}>{children}</SealdContext.Provider>
  );
};

export const useSealdContext = () => useContext(SealdContext);

The skeleton is set up, but we still need to add the functions, so let's do this now.

We start off with the initializeSeald function, which uses the initializationRef to run only once. Everything it does is wrapped in a try/catch: if something fails, the state's loadingState becomes "error" with the reason in error, and the ref is reset so the user can try again. First, we must load the variables from our .env file. Then, we create two variables for the databaseKey (we will define the function for that in a moment) and the databasePath. We use these to initialize the SealdSDK object and call the initialize function afterward:

const initializeSeald = useCallback(
  async (userId: string, password: string) => {
    if (initializationRef.current) return;
    initializationRef.current = true;
    setMyState((state) => ({
      ...state,
      loadingState: "loading",
      error: undefined,
    }));

    try {
      const appId = process.env.NEXT_PUBLIC_SEALD_APP_ID;
      const apiURL = process.env.NEXT_PUBLIC_SEALD_API_URL;
      const storageURL = process.env.NEXT_PUBLIC_KEY_STORAGE_URL;

      if (!appId) {
        throw Error("App ID can't be found.");
      }

      const databaseKey = await getDatabaseKey(userId);
      const databasePath = `seald-e2e-encrypted-chat-${userId}`;

      const seald = SealdSDK({
        appId,
        apiURL,
        databaseKey,
        databasePath,
        plugins: [SealdSDKPluginSSKSPassword(storageURL)],
      });
      await seald.initialize();

      // The identity and state code from the next steps goes here
    } catch (error) {
      console.error("[App] Seald initialization failed", error);
      // Allow another attempt.
      initializationRef.current = false;
      setMyState((state) => ({
        ...state,
        loadingState: "error",
        error: error instanceof Error ? error.message : String(error),
      }));
    }
  },
  [],
);

We create the database key and path to save the identity we create locally for the client. We can load it and avoid re-invoking identities whenever a new tab or something similar is opened.

To read more about this, we recommend following this documentation about using a persistent local database that stores the identity in a safe and encrypted way.

The third step is to get the identity we can use for encryption and decryption. For this we have to distinguish three cases. To tell them apart, we need the error message Seald's key storage plugin throws when it has no identity for a user. We define it at the top of SealdContext.tsx, above the SealdContext:

// What SSKS throws when no identity is stored for the user
// (@seald-io/sdk-plugin-ssks-password, lib/keyStorage.js).
const SSKS_IDENTITY_NOT_FOUND = "Couldn't find identity with this user id";

Here's the code first and we'll explain what we do afterwards:

let mySealdId: string | undefined = undefined;

try {
  // 1. The identity is already in this browser's local database.
  const accountInfo = await seald.getCurrentAccountInfo();
  mySealdId = accountInfo?.sealdId;
} catch {
  // Not in this browser.
}

if (!mySealdId) {
  try {
    // 2. The identity was saved from another browser or device.
    const accountInfo = await seald.ssksPassword.retrieveIdentity({
      userId,
      password,
    });
    mySealdId = accountInfo.sealdId;
  } catch (error) {
    // Register only when SSKS has no identity for this user. Any other
    // error (network, throttling, wrong password) must not replace the
    // stored identity, or the user loses access to their messages.
    if (
      !(error instanceof Error) ||
      !error.message.includes(SSKS_IDENTITY_NOT_FOUND)
    ) {
      throw error;
    }
    // 3. A new user: create the identity and save it.
    mySealdId = await registerUser(seald, userId, password);
  }
}

The first one is that we have already created an identity prior and with the initialization of the SealdSDK object it is automatically retrieved. This is possible because of the databaseKey and databasePath paramenters that we have passed upon initialization. For this we can use the getCurrentAccountInfo function to get the identity.

The second one is that the user created the identity in another browser or on another device. Then the local database is empty, but we can restore the identity from Seald's key storage with ssksPassword's retrieveIdentity function and the user's password.

If the key storage reports that it has no identity for this user, we need to register the user first. We only register on that specific error: any other failure (a network error, throttling, a wrong password) is rethrown, because registering would replace the stored identity and the user would lose access to their earlier messages. For that we need a JWT, that needs to be generated server-side (find a code sample here). With that we can first call the initiateIdentity function that we can then save using ssksPassword's saveIdentity function.

The final step is to update the current state with the updated values:

setMyState({
  sealdClient: seald,
  sealdId: mySealdId,
  userId,
  loadingState: "finished",
  error: undefined,
});

Now, we've used two functions here that we have not yet defined, specifically the getDatabaseKey and the registerUser functions. For them, we create a new folder in the project's root and call it lib.

First, let's create a getDatabaseKey.ts file. This should technically create a unique token for a user that identifies them in the browser. Since we don't cover the database aspect of user handling, we will use a simple hash function. Here's the code to create a unique database key for each user:

"use server";

export async function getDatabaseKey(userId: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(userId);
  const databaseKey = await crypto.subtle
    .digest("SHA-256", data)
    .then((hashBuffer) => {
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashHex = hashArray
        .map((byte) => byte.toString(16).padStart(2, "0"))
        .join("");
      return `seald_database_key_${hashHex}`;
    });

  return databaseKey;
}

Notice that the 'use server' directive makes sure that the function gets called on the server-side for security reasons. That makes use of React's new Server Actions that ship with Next.js (details here).

The other function we haven't added yet is the registerUser function, so let's create a file called registerUser.ts inside the lib folder. This should run client-side, so we add the 'use client' directive at the top of the function to ensure this. It will initiate the identity and save it using the SSKSPassword plugin.

However, for that to be possible, it will need a unique signup JWT. This one, on the other hand, needs to be created server-side, as it needs access to the JWT_SECRET and the JWT_SECRET_ID that we defined earlier in our .env file. To create the signup JWT we need to add three more dependencies to our project, so please run one of the following commands for this:

npm i -S jose buffer uuid
#or
yarn add jose buffer uuid

The JWT also gives the new identity a connector, so other users can find it. We build the connector in its own file, because we need the same one again when we encrypt messages for a channel's members. Create sealdConnector.ts inside the lib folder:

export async function sealdConnector(userId: string, appId: string) {
  const digest = await crypto.subtle.digest(
    "SHA-256",
    new TextEncoder().encode(userId),
  );
  const identifier = Array.from(new Uint8Array(digest))
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
  return { type: "AP" as const, value: `${identifier}@${appId}` };
}

Seald connectors have the form <identifier>@<appId> and are stored in clear text, so we use a SHA-256 hash of the Stream user ID as the identifier: it never contains an @ and doesn't expose the user ID.

Then, create a new file called createSignupJWT.ts inside the lib folder and add the following code (for more info on the functionality, see this link):

"use server";

import { SignJWT } from "jose";
import { v4 as uuidv4 } from "uuid";
import { Buffer } from "buffer";
import { sealdConnector } from "./sealdConnector";

export async function createSignupJWT(userId: string) {
  const jwtSecret = process.env.JWT_SECRET;
  const jwtSecretId = process.env.JWT_SECRET_ID;
  const appId = process.env.NEXT_PUBLIC_SEALD_APP_ID;

  if (!jwtSecret) {
    throw Error("No JWT Secret found");
  }

  if (!jwtSecretId) {
    throw Error("No JWT Secret ID found");
  }

  if (!appId) {
    throw Error("No Seald App ID found");
  }

  const token = new SignJWT({
    iss: jwtSecretId,
    jti: uuidv4(),
    iat: Math.floor(Date.now() / 1000),
    scopes: [3, 4], // PERMISSION_JOIN_TEAM, PERMISSION_ADD_CONNECTOR
    join_team: true,
    connector_add: await sealdConnector(userId, appId),
  }).setProtectedHeader({ alg: "HS256" });

  const signupJWT = await token.sign(Buffer.from(jwtSecret, "ascii"));
  return signupJWT;
}

Besides letting the new identity join our Seald team, the JWT's connector_add claim attaches the user's connector to it. Thanks to it, other users can encrypt messages for this user knowing only their Stream user ID. That's why the JWT secret needs the ADD_CONNECTOR permission. In this demo the user ID comes from the client; in production, take it from the authenticated session, or anyone could claim another user's connector.

With that, the content of registerUser.tsx becomes straightfoward:

"use client";

import type { SealdSDK } from "@seald-io/sdk/browser";
import { createSignupJWT } from "./createSignupJWT";

export async function registerUser(
  seald: SealdSDK,
  userId: string,
  password: string,
): Promise<string> {
  const signUpJWT = await createSignupJWT(userId);
  const identity = await seald.initiateIdentity({
    signupJWT: signUpJWT,
  });
  await seald.ssksPassword.saveIdentity({ userId, password });
  return identity.sealdId;
}

We have finished the code for initializing the SealdSDK.

Encrypting and Decrypting Chat Messages

After executing the initialization logic, we assigned all the necessary variables, specifically the sealdClient, sealdId, and userId, and updated the loading state to be finished. We need to have an Encryption Session ready to encrypt and decrypt messages.

Each channel can have different members, so we use one encryption session per channel, created for all of the channel's members. The first message sent in a channel creates its session. Every encrypted message carries the ID of its session, so readers can retrieve the session by that ID.

To find a member's Seald identity, we use the connector each identity got at signup, built with the sealdConnector helper from earlier. Every message we encrypt also carries the cid of its channel. When decrypting, we check it, so a cipher text copied into another channel isn't shown there. Inside SealdContext.tsx, above the SealdContext, we add the payload's type and a constant we use for decryption:

// How long a failed session retrieval is remembered before it's retried.
const FAILED_RETRIEVAL_TTL_MS = 60_000;

/**
 * What gets encrypted: the text together with the channel it was sent to, so a
 * ciphertext copied into another channel isn't shown there.
 */
type EncryptedPayload = { cid: string; text: string };

Then, inside the SealdContextProvider, below the initializationRef, we add two maps to cache the sessions: one by channel for encrypting and one by session ID for decrypting. We use refs, so updating them doesn't re-render the app:

// One encryption session per channel, keyed by the channel's cid. Caching the
// promise means concurrent sends to a new channel create one session.
const sessionsByChannel = useRef(
  new Map<string, Promise<EncryptionSession>>(),
);
// Sessions retrieved for decryption, keyed by session id.
const sessionsById = useRef(new Map<string, Promise<EncryptionSession>>());

Thanks to all the work we've already done, the encryption and decryption parts are becoming very straightforward.

The encryptMessage function gets the message, the channel's cid, and a getMemberIds function that returns the Stream user IDs of the channel's members (we write it in the next section). If the channel has no session yet, it creates one for all members' connectors. The current user is added automatically, because Seald encrypts for the creator of a session by default. With allowUnregisteredUsers, members who haven't opened the app yet are included too, and can decrypt once they sign up. Then it encrypts the message together with the channel's cid with a single function call (always wrapping it in a useCallback hook to avoid unnecessary re-renders):

const encryptMessage = useCallback(
  async (
    message: string,
    channelCid: string,
    getMemberIds: () => Promise<string[]>,
  ) => {
    const { sealdClient, userId } = myState;
    const appId = process.env.NEXT_PUBLIC_SEALD_APP_ID;
    if (!sealdClient || !userId || !appId) {
      throw new Error("Seald is not initialized.");
    }

    let sessionPromise = sessionsByChannel.current.get(channelCid);
    if (!sessionPromise) {
      sessionPromise = (async () => {
        const memberIds = await getMemberIds();
        // The current user is added through `encryptForSelf` (the default).
        const others = memberIds.filter((id) => id !== userId);
        const connectors = await Promise.all(
          others.map((id) => sealdConnector(id, appId)),
        );
        const session = await sealdClient.createEncryptionSession(
          { connectors },
          {
            metadata: channelCid,
            // Members who haven't opened the app yet have no Seald identity.
            // They're added by their connector and can decrypt once they
            // sign up, instead of blocking everyone else from sending.
            allowUnregisteredUsers: true,
          },
        );
        sessionsById.current.set(
          session.sessionId,
          Promise.resolve(session),
        );
        return session;
      })();
      sessionsByChannel.current.set(channelCid, sessionPromise);
      // Don't keep a failed session: the next message tries again.
      sessionPromise.catch(() => {
        if (sessionsByChannel.current.get(channelCid) === sessionPromise) {
          sessionsByChannel.current.delete(channelCid);
        }
      });
    }

    const session = await sessionPromise;
    const payload: EncryptedPayload = { cid: channelCid, text: message };
    return session.encryptMessage(JSON.stringify(payload));
  },
  [myState],
);

Notice that encryptMessage never returns the plain text. If Seald isn't ready or the channel's session can't be created, it throws, and as we'll see in the next section, the message then fails to send.

The same goes for the decrypting of a message. We look up the message's session in our cache by its ID, and retrieve it from Seald if we don't have it yet. A failed retrieval (for example, a session the user isn't a recipient of) is remembered for a minute, so re-renders don't flood Seald with requests. After decrypting, we check that the payload belongs to the channel the message is shown in. Messages written by earlier versions of the app hold the bare text rather than a payload, so we show those as they are. Here's the full code for our decryptMessage function:

const decryptMessage = useCallback(
  async (message: string, sessionId: string, channelCid: string) => {
    const sealdClient = myState.sealdClient;
    if (!sealdClient) {
      throw new Error("Seald is not initialized.");
    }

    let sessionPromise = sessionsById.current.get(sessionId);
    if (!sessionPromise) {
      sessionPromise = sealdClient.retrieveEncryptionSession({ sessionId });
      sessionsById.current.set(sessionId, sessionPromise);
      // Remember a failed retrieval for a while (e.g. a session this user
      // isn't a recipient of), so re-renders don't flood Seald with requests.
      const failed = sessionPromise;
      failed.catch(() =>
        setTimeout(() => {
          if (sessionsById.current.get(sessionId) === failed) {
            sessionsById.current.delete(sessionId);
          }
        }, FAILED_RETRIEVAL_TTL_MS),
      );
    }

    const session = await sessionPromise;
    const decrypted = await session.decryptMessage(message);
    let payload: Partial<EncryptedPayload> | undefined;
    try {
      payload = JSON.parse(decrypted);
    } catch {
      // Not a payload of this app.
    }
    // Messages encrypted by earlier versions of the app hold the bare text.
    if (typeof payload?.cid !== "string" || typeof payload.text !== "string") {
      return decrypted;
    }
    if (payload.cid !== channelCid) {
      throw new Error("This message was not encrypted for this channel.");
    }
    return payload.text;
  },
  [myState.sealdClient],
);

A channel's session is for the members it had when it was created. When members are added or removed, we drop the channel's session, so the next message creates a new one for the current members. Called without a cid, it drops the sessions of all channels. New members can't read messages sent before they joined:

const resetChannelSession = useCallback((channelCid?: string) => {
  if (channelCid) {
    sessionsByChannel.current.delete(channelCid);
  } else {
    sessionsByChannel.current.clear();
  }
}, []);

With this we have all the logic necessary for end-to-end encryption. The only thing left to do is combine this with Stream's Chat SDK.

Sending And Receiving E2E-Encrypted Messages

Before we start with the sending and receiving of encrypted messages, we need to make sure the SealdContext object is initialized correctly. For this, we open up the page.tsx file and wrap our MyChat component in a SealdContextProvider like this:

<SealdContextProvider>
  <MyChat {...homeState} />
</SealdContextProvider>;

Then, inside MyChat.tsx, we need to call the initializeSeald function from the SealdContext upon initialization using a useEffect hook. We add the following code below the call to the useCreateChatClient hook from earlier (and import useRef from react and useSealdContext from @/contexts/SealdContext):

const {
  initializeSeald,
  loadingState,
  error: sealdError,
  encryptMessage,
  resetChannelSession,
} = useSealdContext();
const initializationRef = useRef(false);

useEffect(() => {
  if (!initializationRef.current && loadingState === "loading") {
    initializationRef.current = true;
    initializeSeald(user.id, "password");
  }
}, [initializeSeald, user.id, loadingState]);

The initializationRef object ensures that this code is only called once (see useRef documentation). We also extend the loading check at the end of the component, so the chat only renders once Seald is ready: if (!chatClient || !paginator || loadingState === "loading"). If Seald couldn't be set up, we show the reason and a button to try again instead. Add this right above the loading check:

if (loadingState === "error") {
  return (
    <section className="w-screen h-screen flex flex-col items-center justify-center gap-4">
      <p>Encryption could not be set up: {sealdError}</p>
      <button
        className="rounded border px-4 py-2"
        onClick={() => initializeSeald(user.id, "password")}
      >
        Try again
      </button>
    </section>
  );
}

We need to inject additional code into the previously created chat setup in two places. First, whenever a user sends a message, we need to make sure that we encrypt it before sending it. Second, before a message is displayed, it needs to be decrypted.

Let's start with the encryption and open up MyChat.tsx. To create a channel's session, encryptMessage needs the channel's members. We add a small function above the MyChat component that reads them with queryMembers, page by page (add StreamChat to the type imports from stream-chat):

/** The Stream user IDs of all members of a channel. */
async function getMemberIds(client: StreamChat, cid: string) {
  const [type, id] = cid.split(":");
  const channel = client.channel(type, id);
  const memberIds: string[] = [];
  const limit = 100;
  for (let offset = 0; ; offset += limit) {
    const { members } = await channel.queryMembers({
      payload: { filter_conditions: {}, limit, offset },
    });
    memberIds.push(...members.map((member) => member.user_id));
    if (members.length < limit) return memberIds;
  }
}

The SDK sends every message through a request handler that we can register in client.config. The sendMessageRequest handler is just what we need.

We take the message's text, hand it to our previously defined encryptMessage function from the SealdContext together with the channel's cid, and then call the default request with the encrypted text. Plain text must never reach Stream, so the handler is strict about what it sends:

  • It refuses messages with content it can't encrypt (attachments, polls, shared locations, and custom data), and messages without text.
  • It forwards only a fixed list of fields: the encrypted text plus IDs, the thread, the quoted message, and mentions. Nothing else from the composer goes out.
  • If encryptMessage throws, the handler throws too. The SDK then marks the message as failed instead of sending it, so there's no plain-text fallback.

We also refuse edits, which would go out unencrypted, and turn off the composer features whose content we can't encrypt: attachments and file uploads, link previews (they would send the URLs you type to Stream while you type), polls, and location sharing. We register all of this in a useEffect hook below the previous one:

// Plain text must never reach Stream. Every outgoing message (channel and
// thread replies) is encrypted here, and a message that can't be encrypted
// fails to send (the SDK marks it as failed) instead of going out as is.
useEffect(() => {
  if (!chatClient) return;
  chatClient.config.set({
    channel: {
      requestHandlers: {
        sendMessageRequest: async (
          { localMessage, message, options },
          defaultRequest,
        ) => {
          const { text, attachments, poll_id, shared_location, mml, custom } =
            message ?? {};

          // Only the text is encrypted. Refuse anything that would carry
          // other content in plain text.
          if (
            attachments?.length ||
            poll_id ||
            shared_location ||
            mml ||
            (custom && Object.keys(custom).length)
          ) {
            throw new Error(
              "Only text messages can be encrypted. The message was not sent.",
            );
          }
          if (!text) {
            throw new Error("The message has no text to encrypt.");
          }

          const encryptedText = await encryptMessage(
            text,
            localMessage.cid,
            () => getMemberIds(chatClient, localMessage.cid),
          );

          // Send an allowlist of fields: the encrypted text plus metadata
          // (ids, thread, quote and mentions), never other content.
          return defaultRequest({
            localMessage,
            options,
            message: {
              id: message?.id,
              text: encryptedText,
              parent_id: message?.parent_id,
              show_in_channel: message?.show_in_channel,
              quoted_message_id: message?.quoted_message_id,
              mentioned_users: message?.mentioned_users,
              silent: message?.silent,
              type: message?.type,
            },
          });
        },
        // Edits would go out unencrypted, and the message UI offers no edit
        // action. Refuse them in case one is added later.
        updateMessageRequest: async () => {
          throw new Error("Editing encrypted messages is not supported.");
        },
      },
    },
    // Turn off composer features whose content can't be encrypted. Link
    // previews would send typed URLs to Stream for enrichment while the user
    // types, and store the preview as a plain-text attachment.
    messageComposer: {
      attachments: { enabled: false },
      linkPreviews: { enabled: false },
      location: { enabled: false },
      polls: { enabled: false },
    },
  });
}, [chatClient, encryptMessage]);

Finally, we reset a channel's session whenever its members change, so the next message creates a session for the current members. Member events can be missed while the connection is down, so we also reset every channel's session when the connection recovers:

// A channel's encryption session is for the members it had when it was
// created. When they change, the next message creates a new session. Member
// events missed while disconnected are covered by resetting every channel's
// session when the connection recovers.
useEffect(() => {
  if (!chatClient) return;
  const subscriptions = [
    ...(["member.added", "member.removed"] as const).map((eventType) =>
      chatClient.on(eventType, (event) => {
        if (event.cid) resetChannelSession(event.cid);
      }),
    ),
    chatClient.on("connection.recovered", () => resetChannelSession()),
  ];
  return () => subscriptions.forEach((s) => s.unsubscribe());
}, [chatClient, resetChannelSession]);

All messages sent are now being encrypted. For the decryption we need to define a custom component. We create a new file inside the components folder and call it EncryptedMessage.tsx.

We use a dependency injection mechanism to be able to access the message we want to display using the useMessageContext hook. Then we use a useEffect hook to call decryptMessage (from the SealdContext) to be run whenever the message.text variable changes. Normally, this should only run once, but if someone updates the message we make sure it gets re-run as well. We only decrypt messages with the received status: while a message is still being sent, the SDK already shows it from a local copy that holds the plain text, and only the copy the server returns is encrypted.

The effect is defensive in three ways. Parsing the session ID is wrapped in a try/catch, so a message that isn't a Seald payload (for example, one sent before we added encryption) is labeled instead of crashing the app. Decryption errors, including a message that was encrypted for another channel (we pass message.cid to decryptMessage), are caught and shown as a placeholder. And an ignore flag in the effect's cleanup makes sure a slow decryption can't overwrite the text of a newer render.

We use a state variable called displayedMessage to show the text, and a messageBubble CSS class to style it. A message that failed to send also gets a "Not sent." label. Here's the code for the entire component:

import { useSealdContext } from "@/contexts/SealdContext";
import { useEffect, useState } from "react";
import { useMessageContext } from "stream-chat-react";

export default function EncryptedMessage() {
  const { message } = useMessageContext();
  const { decryptMessage } = useSealdContext();
  const [displayedMessage, setDisplayedMessage] = useState<string | undefined>(
    message.text,
  );

  useEffect(() => {
    // Only messages the server has stored are encrypted: the optimistic copy of
    // a message that is still being sent (or failed to send) holds the plain text.
    if (!message.text || message.status !== "received") {
      setDisplayedMessage(message.text);
      return;
    }

    let ignore = false;
    let sessionId: string | undefined;
    try {
      sessionId = JSON.parse(message.text).sessionId;
    } catch {
      // Not a Seald payload, e.g. a message sent before encryption was added.
    }
    if (!sessionId) {
      setDisplayedMessage(`UNENCRYPTED MESSAGE: ${message.text}`);
      return;
    }

    decryptMessage(message.text, sessionId, message.cid)
      .then((decryptedMessage: string) => {
        if (!ignore) setDisplayedMessage(decryptedMessage);
      })
      .catch((error) => {
        console.error("Can't decrypt this message.", error);
        if (!ignore) setDisplayedMessage("Can't decrypt this message.");
      });

    return () => {
      ignore = true;
    };
  }, [message.text, message.status, message.cid, decryptMessage]);

  return (
    <div className="messageBubble">
      <p>{displayedMessage}</p>
      {message.status === "failed" && (
        <p className="messageError">Not sent.</p>
      )}
    </div>
  );
}

The two CSS classes go at the end of globals.css:

.messageBubble {
  max-width: 80%;
  background: lightblue;
  overflow: hidden;
  word-break: break-word;
  padding: 0.5rem 1rem;
  margin: 1rem 0;
  border-radius: 1rem;
}

.messageError {
  font-size: 0.75rem;
  color: #b91c1c;
}

The last step is to replace the default message UI of the SDK with our newly created custom one. For this, we go back to MyChat.tsx and set our component as the MessageUI override of a WithComponents wrapper around the chat like this:

// previous code
const overrides = { MessageUI: EncryptedMessage };
// ...
<WithComponents overrides={overrides}>
// following code

That will display our EncryptedMessage component for all messages, therefore decrypting all messages per default. With this we finished the implementation.

Test the End-to-End Encrypted Messages

In the project's root directory, launch the Terminal in VS Code, enter this command, and click the link to the localhost to see the chat interface in the browser. Then select the channel in the list to open it.

npm run dev

Since the chat has been decrypted in the previous section, the messages you send remain human-readable for the channel's members, while Stream only stores the cipher text.

Decrypted chat

Conclusion

Well done! You now know how to integrate the safety and privacy-preserving technology E2EE into web and mobile applications. We built a fully functioning React chat app with end-to-end encryption similar to WhatsApp Web. This article covered a basic working implementation of end-to-end encrypted messaging. Head to the chat and encryption SDKs to learn about advanced features and capabilities.

Want to learn fundamental E2EE concepts and how it works? Check out Encrypting an App End-to-End.