<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PP7S83N" height="0" width="0" style="display:none;visibility:hidden">
Get started

Add Weavy to your React SSR/Next.js app

This guide will show how to add Weavy to your SSR powered React app and render our chat component. Have your project ready, and let's get started.

1. Weavy API Key

We need an API key to communicate with the Weavy backend.

2. Create a Next.js project

If you don't have a Next.js project already, you can create a sample project. Make sure your project is using the App Router.
Create a Next.js project in your terminal
npx create-next-app@latest

3. Install UIKit React

Weavy has a dedicated UIKit for React with regular React components and additional React hooks for easy configuration and usage.
Run npm in your terminal
npm install @weavy/uikit-react

4. Configure environment variables

To securely handle the Weavy configuration, we provide the environment url and the API key as environment variables. The API key will only be available server side, while the Weavy environment url is available both server side and client side.

Create an .env file in the root of your example project and place the Weavy configuration there.

Copy into an .env file in the root of your project
NEXT_PUBLIC_WEAVY_URL="WY_BACKEND_URL"
WEAVY_APIKEY="WY_API_*****************"

5. Create a demo user

For this tutorial, we're creating a demo user, and for that, we need a display name (what the end user sees) and a unique identifier.

Store the demo user in a file. You can later replace the user with functionality to get the current user from the authentication provider in your app.

Create a app/weavy/demo-user.json file with JSON data
{
    "uid": "USER_ID",
    "name": "USER_NAME"
}

6. Create a user server action

We need to create the user in the Weavy environment to use it for authentication. This must be done server side, so we will create a server action for it.

To sync the user to our Weavy environment, we will make user of the Upsert User endpoint in the Web API.

Create a server action in app/weavy/user-server-action.ts
'use server'
import demoUser from "./demo-user.json"

/**
 * Creates or updates the current user server-to-server.
 */
export const upsertUser = async () => {
  
  // TODO: Replace the demo user with the currently authenticated user
  const user = demoUser;

  console.log("Updating weavy user", user.uid)

  const response = await fetch(new URL(`/api/users/${user.uid}`, process.env.NEXT_PUBLIC_WEAVY_URL), {
    method: "PUT",
    headers: {
      "content-type": "application/json",
      Authorization: `Bearer ${process.env.WEAVY_APIKEY}`,
    },
    body: JSON.stringify(user),
  })

  if (!response.ok) {
    throw new Error("Could not update user")
  }
}
The current user is currently hard-coded in the JSON file. Connect the function to your user-system to provide the currently authenticated user instead.

7. Create a token factory

To provide authentication for Weavy we will create a server action that handles authentication on the server side. This server action can then be referenced directly from the client side configuration. 

Create a server action in app/weavy/authentication-server-action.ts
'use server'
import demoUser from "./demo-user.json"

// Cache for current tokens
const _tokens = new Map<string, string>()

/**
 * Gets an authentication token server-to-server for the currently authenticated user.
 *
 * @param refresh - Whether to request a fresh token or use an existing token
 * @returns {string} The current user token
 */
export const tokenFactory = async (refresh: boolean = false) => {

  // TODO: Replace the demo user with the current user from your system
  const user = demoUser;

  console.log("Requesting token")

  // Try using a cached token if refresh isn't requested
  if (!refresh) {
    const token = _tokens.get(user.uid)
    if (token) {
      console.log("Using cached token", user.uid)
      return token
    }
  }

  // fetch access_token from server
  const response = await fetch(new URL(`/api/users/${user.uid}/tokens`, process.env.NEXT_PUBLIC_WEAVY_URL), {
    method: "POST",
    headers: {
      "content-type": "application/json",
      Authorization: `Bearer ${process.env.WEAVY_APIKEY}`,
    },
    body: JSON.stringify({ expires_in: 3600 }),
  })

  if (response.ok) {
    const data = await response.json()
    const token = data.access_token as string

    // Cache the token
    _tokens.set(user.uid, token)

    console.log("Requesting token", token)

    // return token to UIKit
    return token
  } else {
    throw new Error("Could not fetch token")
  }
}

This function is requesting tokens for the defined user server side.

The current user is currently hard-coded in the JSON file. Connect the function to your user-system to provide the currently authenticated user instead.

8. Configure the weavy context

To use Weavy components we need to configure the authentication we created. When using server components it's recommended to use the <WyContext> provider to configure Weavy, since it's easier to use in SSR apps. 

We will add the context to the layout, so we can use Weavy components wherever we like in our app.

For this demo purpose, we also make sure to create or update the user here. This can otherwise be done when the current user signs in.

Add <WyContext> and upsertUser() to app/layout.tsx
import type { Metadata } from "next"
import { Geist, Geist_Mono } from "next/font/google"
import { tokenFactory, upsertUser } from "./weavy/server-actions"
import { WyContext } from "@weavy/uikit-react"
import "./globals.css"

// ...

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode
}>) {

  // Create or update current user when initialized
  upsertUser();

  return (
    <html lang="en">
      <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
        <WyContext url={process.env.NEXT_PUBLIC_WEAVY_URL} tokenFactory={tokenFactory}>
          {children}
        </WyContext>
      </body>
    </html>
  )
}

9. Add chat component

Now, it's time to add the chat component to your React app.

All web components in the Weavy UIKit are available as React components but with tag names adapted to the React framework, for example <WyChat> instead of <wy-chat></wy-chat>. Property binding for attributes using prop={value} syntax may be used normally just as expected.

Add the WyChat component to your app/page.tsx
import { WyPosts } from "@weavy/uikit-react";

// ...

export default function Home() {
  return (
    ...
    <WyPosts uid={"next-posts"} />
    ...
  );
}

10. Build

Now, let's compile the project.
Run in your terminal
npm run build

11. Start

Start the project.
Run in your terminal
npm start
Once up and running you can open the preview at http://localhost:3000 to see the example in full action.

12. Done!

You should now have a group chat component up and running in your React app. This tutorial's goal was to quickly introduce the concepts of Weavy, especially the understanding of handling users and providing access tokens.

Now it's time to start building for real - try adding more Weavy components or integrating your user system into the server actions.

Support

To access live chat with our developer success team you need a Weavy account.

Sign in or create a Weavy account