Adding Weavy to your web app

This comprehensive guide will help you get started with Weavy. It covers all the basic steps to get you up and running, and explains best practices for configuring Weavy. If you're new to Weavy, we suggest familiarizing yourself with some important Weavy concepts before continuing.

Requirements

Weavy works with all major web frameworks, and whether you’re a hardcore full stacker, or a DIY developer using a Low Code platform, Weavy is for you. When adding Weavy to your web application there are just 3 prerequisites:

  • You must be able to add Weavy components to pages and views in your UI.
  • Your application must have a way to identify the currently logged in user.
  • There must be some way to make an API call from your backend to the Weavy environment.

Install Weavy

Go to get.weavy.com and create an environment (if you haven't already). The environment is your own Weavy server with a secure storage area and serves the Web API which handles all communication between your app and Weavy.

Make a note of the URL —you’ll need it later. We'll reference this as {WEAVY_URL}.

Create API key

On the environment management page, create an API key. The API key is used for making server-to-server requests with the Web API. Take note of the created key—you’ll need it in the next step. We will reference the API key as {WEAVY_API_KEY}.

Configure app settings

Next, add settings for the Weavy environment URL and Weavy API key to your application's configuration (how you add configuration settings depends on your framework and build system, but a common option is using .env files).

  • Create a configuration setting for the {WEAVY_URL}. This setting does not require any special protection.
  • Create a configuration setting for the {WEAVY_API_KEY}. This setting must be kept secure.

Warning

It is very important that the API key is stored securely and never exposed in client side code or similar!

Sync user data

Users in your application are automatically added to Weavy as part of the authentication processs, but syncing them in advance or on a schedule can improve the experience for features like @mentions and direct messages.

To keep user details (name, email, profile picture etc) up-to-date in Weavy, we recommend calling the Upsert user endpoint in the Web API whenever a user is updated in your application, such as during sign-up or when a user updates their profile.

Below you'll find some example code for syncing user data from your application to Weavy.

/**
 * Sync user data to Weavy.
 *
 * @param {string} uid - User identifier of the user to insert/update.
 * @param {User} user - Profile data for the user.
 */
export async function syncUser(uid, user) {
  console.log("Syncing user", uid, user);

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

  if (!response.ok) {
    throw new Error("Could not update user");
  }
}
/// <summary>
/// HttpClient for accessing the Weavy API.
/// </summary>
static readonly HttpClient WeavyClient = new () {
    BaseAddress = new Uri(WEAVY_URL),
    DefaultRequestHeaders = {
        Authorization = new AuthenticationHeaderValue("Bearer", WEAVY_API_KEY)
    }
};

/// <summary>
/// Sync user data to Weavy. 
/// </summary>
/// <param name="uid">User identifier of the user to insert/update.</param>
/// <param name="user">Profile data for the user.</param>
/// <returns></returns>
static async Task SyncUser(string uid, User user) {
    _log.Debug("Syncing {user}", user);
    var response = await WeavyClient.PutAsJsonAsync($"{WEAVY_URL}/api/users/{uid}", user);
    response.EnsureSuccessStatusCode();                
}

Create token endpoint

For a Weavy to be able identify your users you need to create a token endpoint on your server that returns an access_token for your authenticated user. The Weavy UIKit will automatically call this endpoint whenever a token is needed to make authenticated API requests to the Weavy environment.

The responsibility of the token endpoint is to return an access_token for the logged in user. That usually involves the following steps:

  1. Identify the logged in user (in most web applications users are identified with an authentication cookie).
  2. Fetch an access_token for the user (from local application storage or from the Weavy environment).
  3. Return the access_token to the tokenFactory.

For information on how to add and implement the token endpoint see the authentication article.

Add the UIKit

The Weavy UIKit is a JavaScript library that you add to your app or website. It contains the Weavy UI components and a Weavy class for configuration. We recommend loading the UIKit as ECMAScript modules (ESM) from your Weavy environment, but it can also be installed with npm install @weavy/uikit-web.

With the library installed, you need to initialize an instance of the Weavy class. When created, the instance makes itself available to all Weavy components as a global context provider on the documentElement (the <html> node in the DOM). This means your should only create one Weavy instance. For single-page apps, you can do this once anywhere in your code; but for traditional server rendered websites, you have to do this on each page.

<script type="module">
  // Import the lib from your Weavy environment to avoid version mismatch
  // NOTE: Remember to replace the {WEAVY_URL} placeholder
  const { Weavy } = await import("{WEAVY_URL}/uikit-web/weavy.esm.js");

  // Initialize a Weavy instance
  const weavy = new Weavy();

  // Set URL to Weavy environment 
  // NOTE: Remember to replace the {WEAVY_URL} placeholder
  weavy.url = "{WEAVY-URL}";
  
  // Set URL to your token endpoint for authentication
  weavy.tokenUrl = "/token";
</script>
// Import Weavy from the npm package
import { Weavy } from "@weavy/uikit-web";

// Initialize a Weavy instance
const weavy = new Weavy();

// Set URL to Weavy environment 
// NOTE: Remember to replace the {WEAVY_URL} placeholder
weavy.url = "{WEAVY-URL}";
  
// Set URL to your token endpoint for authentication
weavy.tokenUrl = "/token";

For more options see adding the UIKit.

Add components

Finally, you’re ready to add Weavy components to your application. For this example, we're adding a <wy-messenger> component, but you can of course use any other Weavy component such as <wy-chat>, <wy-comments>, <wy-feed> or <wy-files>.

All components are context-aware and handle loading and off-line states automatically. This means you don't have to wait for the Weavy instance to be fully configured before adding components. As soon as a valid Weavy instance is available, the components will load their data and re-render.

Example: A complete client-side example in HTML

<!DOCTYPE html>
<html>
  <head>
    <script type="module">
    // Import the lib from your Weavy environment to avoid version mismatch
    // NOTE: Remember to replace the {WEAVY_URL} placeholder
    const { Weavy } = await import("{WEAVY_URL}/uikit-web/weavy.esm.js");

    // Initialize a Weavy instance
    const weavy = new Weavy();

    // Set URL to Weavy environment 
    // NOTE: Remember to replace the {WEAVY_URL} placeholder
    weavy.url = "{WEAVY-URL}";
  
    // Set URL to your token endpoint for authentication
    weavy.tokenUrl = "/token";
    </script>
  </head>
  <body>      
      <wy-messenger></wy-messenger>
  </body>
</html>

You should now have a fully functional chat in your application — send your first message and start chatting away!

Customize styling

Weavy components can adapt some of their styling automatically. But for a more cohesive look, you can customize a few settings. By simply adjusting theme color, padding, and roundness the components will feel seamlessly integrated into your app.

:root {
  /* Sets the accent color, which generates a full theme palette based on this color. Any valid CSS color. */
  --wy-theme-color: #00ffcc;

  /* Sets dark mode for the color palette. Set to `dark` or `light`. Defaults to `light` */
  --wy-color-scheme: dark;

  /* Sets the base roundness. Any valid CSS measurement unit. */
  --wy-border-radius: 4px;

  /* Sets the base padding. Any valid CSS measurement unit. */
  --wy-padding: 1rem;
}

Read more about custom styling and appearance.

Troubleshooting

  • If Weavy is loaded correctly it should output the package name and version (e.g. @weavy/uikit-web@30.2.0) once in the browser console log. If you don't see this or if you see it several times, you need to check that you load Weavy correctly.
  • If you're seeing and endless spinner when components load or if you are getting a message in the browser console log saying that Weavy wasn't configured in a reasonable time, you should double-check that your Weavy configuration is correct. A common problem is that WEAVY_URL is undefined.
  • If the editor in a component is not editable or working correctly, you might have a version mismatch between the Weavy environment and UIKit. Check the browser console log for warnings or errors about version mismatch. Ensure that @weavy/uikit-web and the Weavy environment is exactly the same version.
  • If you see a message about the server being offline, check that the Weavy environment is running and check that you have provided the correct url to your Weavy environment.

When things are not working as expected, always check the output in the browser console as it usually contains infomation about the problem and sometimes a hint on what needs to be fixed.

Next steps

Now you're ready to use Weavy in your project. Next, we recommend adding notifications and AI agents for an immersive user experience. You might also want to learn more about the Web API, and how to use webhooks.