Getting started with Weavy
This comprehensive guide will help you get started with Weavy. It covers all the basic steps to get it up and running, and explains best practices for configuring Weavy.
If you're new to Weavy, it's a good idea to start by getting familiar with important Weavy concepts.
This guide will apply to any web framework. If you're specifically using React, you can use the getting started with Weavy using React guide to get React specific guidance.
1. Check Weavy requirements
Weavy can be used in most systems, but your app must meet certain criteria for Weavy to work. In short, Weavy only works on top of an app or website with properly authenticated users, which usually requires a backend.
Your app must be able to:
- Fetch a Web API using a server function or endpoint, leveraging Bearer tokens for authentication.
- Store and provide an API key securely on the server, for example using environment variables.
- Pass fetched data from the server side to the client side.
- Have access to the currently signed-in user on the server side.
- Import a JavaScript library on the client side.
- Render Custom Elements (Web Components) on the client side.
2. Create Weavy account
If you haven’t already, go to https://www.weavy.com and sign up for a free account. Your Weavy account is where you manage your Weavy environment and set up AI Agents.
3. Create Weavy environment
Next, go to your account dashboard and create your first Weavy environment. Your Weavy environment is your own Weavy server and handles all communication, databases, the Web API, and serving files. There are both trial and free options, making it easy to get started.
Make a note of the environment URL—you’ll need it later. We'll reference this as {WEAVY_URL}.
It's also important to know which version you are using. This affects not only matching client and server versions, but also which API and syntax to use in your code. This guide is based on the latest version of Weavy, which can be found in the current changelog.
4. Create API key
On the environment management page, scroll down and create an API key. The API key is used for making server-to-server requests in 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}.
The API key must always be kept secure! It should always be stored and used server side, and never on the client side. It must never be available publicly. Store it, preferably encrypted, with limited access.
5. Set up environment variables
To configure our environment settings in the app we're adding Weavy to, we'll add the Weavy environment configuration to our environment variables. We need to create two environment variables, one for the Weavy environment URL and one for the Weavy API key for the server to use.
A great way is to store the environment variables as strings in an .env file in the root of the project. You can then exclude this file in .gitignore to make sure the credentials are not saved in your repository code. Use any built-in support for environment variables in your build system, otherwise you may read the variables from the .env file using the built-in .env file support in NodeJS 20 for example.
Note: Your build system may require variables to be prefixed to be available on client side. For instance, Vite uses the VITE_ prefix to expose environmental variables that can be used on the client side, exposed in code using the special import.meta.env object. Always check in client side code that the environment variable is actually available and has a value.
- Create an environment variable called
WEAVY_URLand let the value be the URL of your Weavy environment as a string, previously mentioned as{WEAVY_URL}. This variable is needed both server-side and client-side and should be available publicly in the client as well as on the server. UseVITE_WEAVY_URLwhen using Vite, to make it available both server side and client side. - Create an environment variable called
WEAVY_API_KEYand let the value be the API key to the Weavy environment as a string, previously mentioned as{WEAVY_API_KEY}. This variable must be kept secure and only be available on the server side, never on the client side.
Pitfall: Always check that the env variables aren't
undefinedin your code when using them. This helps you catch errors easily in your env configuration, and avoid time-consuming debugging.
6. Provide user data
All Weavy components rely on actions based on users. The Weavy has a user system that needs data from your user system to make the components well integrated into your app. Providing user data is done server-to-server through the Weavy Web API using the Weavy API key. Weavy users are later authenticated using access tokens provided via your server.
Ensure the Weavy API key is only used server-side when using the Weavy Web API, while the client only receives data from your server.
Here are some points for setting the strategy on providing user data.
- Make sure the user data is provided and available to Weavy at latest when an access token for the user is needed.
- For one user to be able to interact with other users, those users need to be provided to Weavy beforehand.
- Do not overload the Weavy environment with too many user data updates at a time. Avoid providing or updating all users at once; instead, divide them into batches of 20-50 users. Overloading the Weavy environment with user updates will slow down the performance of the components.
With that said, here are two recommended practical ways to do it:
- It's best to update all the users when the server starts if the users are known and there are fewer than 20 users.
- In other cases you can update the user the same time as you are fetching a user token.
Learn more about user endpoints and using the Web API.
/**
* User
*
* @typedef {object} User
* @property {string} username - Username
* @property {string} name - Full name of the user
* @property {string} email - Email of the user
* @property {string} picture - Optional avatar URL for the user
*/
/**
* Dummy user for this example.
* Replace the reference to this dummy user with an actual user from your system.
* @type {User}
*/
const dummyUser = {
name: "Daffy Duck",
username: "daffy",
email: "daffy@acme.corp",
picture: "https://i.pravatar.cc/150?u=daffy",
};
/**
* Creates or updates the user server-to-server.
*
* - Using `WEAVY_URL` environment variable for the base URL to the Weavy environment.
* - Using `WEAVY_API_KEY` environment variable for server authentication on the Weavy environment.
*
* @param {string} uid - The user identifier to insert/update.
* @param {User} userData - The data for the user. User properties should match the properties for users in the Weavy Web API. It should not contain a `uid` property.
* @see https://www.weavy.com/docs/reference/api/users#upsert-user
*/
export async function upsertUser(uid, userData) {
console.log("Upserting Weavy user", uid);
// Ensure the WEAVY_URL environment variable is set and available.
if (!process.env.WEAVY_URL) {
throw new Error("No WEAVY_URL defined in ENV.");
}
// Ensure the WEAVY_API_KEY environment variable is set and available.
if (!process.env.WEAVY_API_KEY) {
throw new Error("No WEAVY_API_KEY defined in ENV.");
}
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(userData),
}
);
if (!response.ok) {
throw new Error("Could not update user");
}
}
7. Create a user token endpoint
For a Weavy to be able to fetch and render data you need to supply it with an access_token for your logged in user. Issuing an access tokens should always be done server side with a server-to-server call from your backend to the Weavy environment using the Weavy Web API together with the API key we previously created. This way we can keep the Weavy API key safe on the server.
On the client side, Weavy will later be set up to call the endpoint whenever a token is needed. In cases where the token is expired or invalid, Weavy will call the endpoint with a refresh=true parameter to explicitly request a fresh new token.
For this example we'll create an endpoint for serving the access token using Express.js in NodeJS. The user information in this example is provided in session data for the express server. You should provide the data from your currently authenticated user and map it to the user data needed by Weavy to match your user.
Ensure the Weavy API key is only used server-side for working with the Weavy Web API, while the client only receives the access tokens.
Learn more about authentication.
// Cache for current tokens
const _tokens = new Map();
/**
* User token response data
*
* @typedef {object} UserToken
* @property {string} access_token - The issued access token
* @property {number} expires_in - Time in seconds until the token is expired
* @see https://www.weavy.com/docs/reference/api/users#issue-access-token
*/
/**
* GET /api/token?refresh=true
* @summary Weavy environment user token.
* @description Gets an authentication token server-to-server for the currently authenticated user. Using token cache to avoid unnecessary token request to the Weavy environment.
* @param {string} refresh.query - Request the token to be refreshed - true
* @return {UserToken} 200 - success response - application/json
* @example response - 200 - success response example
* {
* "access_token": "wyu_qf2llm...",
* "expires_in": 3600
* }
*/
app.get("/api/token", async (req, res) => {
// Ensure the WEAVY_URL environment variable is set and available.
if (!process.env.WEAVY_URL) {
throw new Error("No WEAVY_URL defined in ENV.");
}
// Ensure the WEAVY_API_KEY environment variable is set and available.
if (!process.env.WEAVY_API_KEY) {
throw new Error("No WEAVY_API_KEY defined in ENV.");
}
/**
* The current user - Replace this with data for the currently logged in user from your user system, for example using `req.session.user`.
* It's important that the user only can get an access token for their own user account and not for any other user account, as that would compromise security.
* @type {User}
**/
const currentUser = dummyUser;
// Desired uid for the user. The uid is used for referencing and mentions in Weavy.
const uid = currentUser.username;
// Check the query parameters if a refresh token is requested
const refresh = req.query.refresh === "true";
// Get token from cache or by a server-to-server fetch
// Try using a cached token if refresh isn't requested
if (!refresh) {
const token = _tokens.get(currentUser.username);
if (token) {
// Return cached token
res.json(token);
return;
}
}
// Upsert the user, as we don't need the response, we can skip awaiting this to enhance performance.
void upsertUser(uid, currentUser);
try {
// Fetch access_token from server
// - Using `WEAVY_URL` environment variable for the base URL to the Weavy environment.
// - Using `WEAVY_API_KEY` environment variable for server authentication on the Weavy environment.
const response = await fetch(
new URL(`/api/users/${uid}/tokens`, process.env.WEAVY_URL),
{
method: "POST",
headers: {
"content-type": "application/json",
Authorization: `Bearer ${process.env.WEAVY_API_KEY}`,
},
body: JSON.stringify({ expires_in: 3600 }),
}
);
if (response.ok) {
const token = await response.json();
// Cache the token
_tokens.set(uid, token);
// Return fetched token
res.json(token);
} else {
// Forward any response codes from the Weavy environment
res.status(response.status).json({ access_token: "" });
}
} catch {
// Return 400 error to let Weavy handle it properly.
res.status(400).json({ access_token: "" });
}
});
8. Importing the Weavy lib
To be able to configure Weavy on the client side and render all the Weavy web components, we make use of the Weavy UI kit lib. The lib contains all the Weavy web components and also a Weavy class for configuration. The Weavy class automatically provides a global context provider to all the Weavy web components, so that the configuration can be placed anywhere and only needs to be done one time for all web components together.
The UI kit lib is provided as ESM for optimal performance. It registers all Weavy web components in the custom element registry so they are available in the DOM. It doesn't register anything globally in the window object, so you should import everything where you need it, as you normally do.
- We need to import the UI kit lib in the client. This will give access to the Weavy class to make a configuration and provide authentication for the components. The
Weavyclass needs to be imported properly as an ESM module as it's not exposed globally in thewindowobject. - The Weavy web components will be available after the script has loaded and they have been registered by the script. Load the lib as early as possible to provide optimal rendering performance for the Weavy web components.
- The version of the UI kit lib must always match the version of the Weavy environment. When loading the lib directly from the Weavy environment, the versions are guaranteed to match. When installing via
npmand importing the@weavy/uikit-webmake sure to match the package version with the Weavy environment version. When the Weavy environment version is unknown, always use the latest npm package version for the UI kit lib. Note that you must always be somewhat aware of which version you intend to use to use the correct API and syntax in your code.
There are two locations to import the lib from and they provide the same lib. It can be imported directly from the Weavy environment or installed using npm.
Learn more about installing Weavy.
Importing the UI kit from the Weavy environment
The lib is available for import directly from the Weavy environment. Loading directly from the Weavy environment is optimal when you want to make sure that the Weavy environment version match. This is recommended when npm is not available or if the exact Weavy environment version is unknown.
To be able to import the lib in the browser you can simply use the native dynamic imports to load the lib as a module. Dynamic imports can be used in any async function or in scripts that has type="module".
<script type="module">
// Import the lib directly from the Weavy environment to make sure the lib version and the environment version always are matching.
// Note: The ESM script does not expose the Weavy class in the globalRoot or window object, so you should use it within this script.
// A dynamic import may be used in script with `type="module"` or in any async function.
// Make sure to replace {WEAVY_URL} with the url to your Weavy environment. Always check that it's defined correctly.
const { Weavy } = await import("{WEAVY_URL}/uikit-web/weavy.esm.js");
// Weavy configuration goes here...
</script>
Installing the UI kit from npm
The Weavy UI kit is available as @weavy/uikit-web for installation using npm. This is optimal if you have npm available and know the exact version of your Weavy environment. This may provide much smoother usage and the possibility for your build system to perform tree shaking and optimizations of the bundle.
When using TypeScript in your project, you should always use the @weavy/uikit-web npm package if possible, as it contains type definitions for the whole library, which helps you improve your code and makes debugging easier.
Install the Weavy UI kit package
Make sure you have NodeJS and npm installed already.
npm install @weavy/uikit-web
Import the lib in your code
import { Weavy } from "@weavy/uikit-web";
// Weavy configuration goes here...
9. Configure Weavy in your app
Now that the library is imported and we have access to all modules, we can configure Weavy. There are several ways to provide the configuration, but the configuration always has the same properties and it essentially always creates an instance from the Weavy class.
When created, the instance makes itself available to all Weavy components as a context provider globally on the documentElement (which essentially is the <html> node in the DOM). This means only one Weavy instance is needed, so make sure to avoid creating multiple instances, as this only will raise memory consumption. Note that components placed inside iframes have their own DOM and need their own Weavy instance.
Weavy components can safely be rendered both before and after the configuration is ready, as they automatically will wait for a Weavy configuration to become available.
The Weavy instance needs to be configured at least with a URL and authentication. The following properties are required to configure the Weavy instance.
url- The required URL to the Weavy environment.tokenUrlortokenFactory- The authentication can either usetokenUrlfor an url to an api endpoint ortokenFactoryfor an async function returning a string token. It's recommended to use thetokenUrlin most cases, when you have an endpoint returning the access token as JSON in the normal{ "access_token": "wyu_*****" }format. When you want to customize how to retrieve or provide the access token, you may use thetokenFactoryinstead. ThetokenUrlortokenFactorywill not be used until a validurlproperty also is set.- When using a
tokenFactory, it's good practice to await any dependencies you may have before returning the token as well as making use of the booleanrefreshparameter passed to the function when called, to make sure the function returns a fresh token when requested by Weavy. If needed, it's allowed to initially return a nullish token or empty token while waiting for a valid token to become available.
Import the UI kit and configure the Weavy instance once on each HTML page, anywhere in your code. For single-page apps, you can do this once; for traditional websites, you have to do this on each page. Then you may use Weavy web components anywhere you like on those pages. Replace the {WEAVY_URL} placeholders with the URL to your Weavy environment.
import { Weavy } from "@weavy/uikit-web";
// The configured Weavy instance is available to all children of the documentElement in the DOM.
const weavy = new Weavy();
// Ensure the WEAVY_URL environment variable is set and available.
if (!process.env.WEAVY_URL) {
throw new Error("No WEAVY_URL defined in ENV.");
}
// The URL to the Weavy environment.
weavy.url = `${process.env.WEAVY_URL}`;
// The URL to the user access token endpoint. This replaces the need for a full `tokenFactory` function and automatically handles communication with the user access token endpoint.
weavy.tokenUrl = "/api/token";
10. Create a component
Finally, you’ll want to add a Weavy component client-side in your application. For this example, we're creating a <wy-chat> component, but you may use any Weavy components you like.
You can add as many Weavy components to the DOM as you like. Here we use the <wy-chat> component, but you may also use other components such as <wy-comments>, <wy-copilot>, <wy-files>, <wy-messenger>, or <wy-posts>. See the UI kit reference for all available components.
You don't have to wait for your configuration to be ready before rendering the components. The components handles loading states automatically for you, and loads everything as soon as a valid configuration is available.
All Weavy components have predefined styles for optimal rendering in flex and grid layouts, with predefined, adaptable height and width with built-in scrolling when needed. Always try to use a flex or grid layout for the parent container where the Weavy component is placed; otherwise, you may have to specify the height of the Weavy component instead (which is not optimal). For components that feature reverse scrolling, such as <wy-chat>, <wy-copilot>, and <wy-messenger>, it's recommended to also have a predefined height on the container and not let it grow with the content. This will enable proper reverse infinite scrolling; otherwise, all messages may load at once when the component first renders. See the documentation on each component to get a full understanding of the layout.
The content within many of the components is per default aligned to the edges of it's own box and designed to not be placed next to a edge or border. It's recommended to adjust the layout with your default padding. Setting the --wy-padding-outer to your default padding will allow the component to still fill the are where it's placed, but with proper padding within the scrollable area of the component. If you want to make the component go all the way to the edges without padding or any outermost roundness instead, set --wy-padding-outer: 0; and --wy-border-radius-outer: 0; to make the component fit nicely with the edge.
Complete client-side example in HTML
<!DOCTYPE html>
<html>
<head>
<script type="module">
// Import the lib directly from the Weavy environment to make sure the lib version and the environment version always are matching.
// Note: The ESM script does not expose the Weavy class in the globalThis or window object, so you should use it within this script.
// Make sure to replace {WEAVY_URL} with the url to your Weavy environment. Always check that it's defined correctly.
const { Weavy } = await import("{WEAVY_URL}/uikit-web/weavy.esm.js");
// The configured Weavy instance is available to all children of the documentElement in the DOM.
const weavy = new Weavy();
// The URL to the Weavy environment.
weavy.url = "{WEAVY_URL}";
// The URL to the user access token endpoint. This replaces the need for a full `tokenFactory` function and automatically handles communication with the user access token endpoint.
weavy.tokenUrl = "/api/token";
</script>
</head>
<body>
<style>
.my-container-layout {
/** Make the Weavy component inside the container align itself to the container layout. */
display: "flex";
/** Set the default padding used in your app to make the component fill the container, but with padding. */
--wy-padding-outer: 0.5rem;
/** When using `--wy-padding-outer` make sure the container does not have additional padding so it can properly fill the area. **/
padding: 0;
}
</style>
<div class="my-container-layout">
<!-- The wy-chat needs a `uid` with a name that is related to where it's placed in the app. -->
<wy-chat uid="test-chat"></wy-chat>
</div>
</div>
</body>
</html>
You should now have a fully functional chat in your application — send your first message and start chatting away!
11. Basic styling
To match the visual style of the Weavy components to your app, you can provide some basic styling that makes the component match your theme better.
CSS variables
You only need a few CSS variables (aka CSS custom properties) to set the overall appearance of the Weavy components to match your own theming. The CSS variables can be set on any parent node of the Weavy components. You can have globally applied CSS variables in :root or applied per-component.
It's recommended to match the Weavy styles to the visual style of your app. Just linking theme color, padding and roundness will make the components feel integrated with everything else as Weavy adapts most of the styling great per default.
All the CSS variables are optional. Set the ones you need to match your theme. There is no need to provide a CSS variable for the font as the style is inherited from parent nodes.
: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;
}
Additional styling
Read even more about how to customize the style and appearance further.
12. Troubleshooting
- If Weavy is loaded it should normally it should show 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 thew browser console log saying that Weavy wasn't configured in a reasonable time, you need to check that your Weavy configuration is correct. It's very common that environment variables used in the configuration may be
undefined, so you should check that they are provided and available correctly. - If the editor in a component is not editable or not working correctly, you might have issues with a mismatch between the Weavy environment version and the used client lib version. Check the browser console log for warnings or errors about version mismatch. Ensure that
@weavy/uikit-weband 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
urlfor the Weavy environment and that the Weavy environment url can be accessed.
When things are not working as expected, always check the output in the browser console as it usually gives you extensive hint's on what to do. You can also ask for help in the support chat.
Next steps
Now you're ready to use Weavy components in your project. We recommend adding notifications and AI agents for an immersive user experience.
Weavy components
There are a lot of UI kit components ready to use, that greatly empowers your project with very few lines of code. Dive into the details of any component to see what it's capable of or how to customize it.
Where applicable, all Weavy components feature rich text, images, file uploads, cloud files, video meetings, office integration, polls, 100+ format image/media/docs/code file previews, embedded link content, emoji reactions, AI agents and rich comments. They can also be provided with context data for any predefined AI agents to use for analyzing content on the page.
| Weavy component | Description |
|---|---|
<wy-chat> |
Displays a single conversation between any number of members. Useful for discussions in a specific place or around a specific context. |
<wy-comments> |
Rich comment list. Intended to complement any existing entity or context with comments. |
<wy-copilot> |
Provides one-to-one conversations with an AI agent. Use in combination with context data for a customized dynamic copilot experience. |
<wy-files> |
File uploads and cloud files (Google Drive, Box, Dropbox, Microsoft OneDrive) complete with comments, version handling, Office integration and full browser previews for 100+ formats. |
<wy-messenger> |
Full conversation handler for one-to-one chats and chat rooms. Switch between different chats from a list. Displays well in both a side panel and full size. |
<wy-messenger-badge> |
Displays a small badge with the number of unread conversations updated in realtime. Fits well with a button or similar. |
<wy-messenger-button> |
Complete icon button + Messenger. A button with a realtime badge for unread conversations. The button opens an overlay with a the Messenger. |
<wy-notifications> |
A list of all notifications. Works well together with a notification badge and notification toasts for a full notification experience. |
<wy-notification-badge> |
Displays a small badge with the number of unread notifications updated in realtime. Fits well with a button or similar. |
<wy-notification-button> |
Complete icon button + Notification list. A button with a realtime badge for unread notifications. The button opens an overlay with a list of unread notifications. |
<wy-notification-toasts> |
Displays rich in-browser toasts or browser notifications for new notifications and incoming chat messages in realtime. Works great by itself or as a complement to a notification list or the messenger. |
<wy-posts> |
A feed or rich posts with comments on each post. Usable for social posts, sharable content and news. |
Web API
You might also want to learn more about the Web API, and how to use webhooks.
Additional platforms
If your app is built using a specific framework or platform and you are curious about how to integrate Weavy, check out our webpage for demos and in-depth tutorials.