Getting Started with Appwrite Realtime for Web Developers
Tags: webdev, javascript, opensource, news
Published: 2021-09-03 07:46:12

For all those who have been waiting for Appwrite's realtime service, we have good news. The latest version of Appwrite has been released with a realtime service and using it is as simple as Appwrite's REST API. There's been a few updates since we released the realtime alpha and the getting started tutorial. In this tutorial, we learn to use Appwrite's updated realtime service by building a simple [Kanban board project](https://infallible-villani-a88afd.netlify.app/).

![Social Media posts (7)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67l9rabvrwzl5e08xcay.gif)
 
 
## 📝 Prerequisites

In order to continue with this tutorial, you need to have access to an Appwrite console with a project. If you have not already installed Appwrite, please do so. Installing Appwrite is really simple following Appwrite's official [installation docs](https://appwrite.io/docs/installation). Installation should only take around 2 minutes. Once installed, login to your console and **create a new Project**.

## 💾 Setup Database

Once you have logged in to the console and selected your project, from the left sidebar in the dashboard click on the **Database** option to get to the database page.

Once on the database page, click on the **Add Collection** button.

![Create Collection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a2o41fj3ogxyzzz1iq1q.png)
 

In the dialog that pops up, set the collection name to **Tasks** and click on the **Create** button to create the collection, and you will be redirected to the new collection's page where we can define its rules. Define the following rules, then click the **Update** button. Also note down the **Collection ID** from the right side of the settings page as we will need that later in our code.

- **Title**
    - label: Title
    - Key: title
    - Rule Type: Text
    - Required: true
    - Array: false
- **Column**
    - label: Column
    - Key: column
    - Rule Type: Text
    - Required: true
    - Array: false
- **userId**
    - label: UserId
    - Key: userId
    - Rule Type: Text
    - Required: true
    - Array: false

![Add Collection Rules](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbzlri8sjfnua8xg281u.png)
 
In the permissions, set the read and write permission both to `role:member` so that any logged in user can read and write to collection.

Now that the collection we can begin working with our project.

## ➕️ Add Web Platform

To initialize the Appwrite SDK and start interacting with Appwrite services, you first need to add a new web platform to your project. To add a new platform, go to your Appwrite console, select your project, and click the **Add Platform** button on the project Dashboard. Choose **New web app**.

In the dialog box that appears enter a name and a hostname. Your hostname will be **localhost** (or your domain if not running locally).

By registering a new platform, you are allowing your app to communicate with the Appwrite API.

## ⚙️ Setup Project and Dependencies

We have a starter project for a simple Kanban board with Svelte. You can download the starter project from our [GitHub Repository](https://github.com/lohanidamodar/demo-web-realtime).

Once you've downloaded project locally, open it in your favorite text editor. Open **src/service/appwrite.js**, and update your endpoint and your collection id. If you look at this file, you'll see we have all the methods for adding, deleting and updating tasks, as well as login and logout methods in place. We are importing and using these functions in **src/App.svelte**.

To run this project, from your terminal first run `npm install` to install the dependencies and then run `npm run dev` to run the project locally in development mode. You can now access the app from your browser at [http://localhost:3000](http://localhost:3000). 

> To avoid cookie issues, please ensure the endpoint URL is using the same protocal (**http** or **https**) as your client.

Right now if you add tasks, you will only be able to view it after you refresh your page. Also if you update or delete tasks, you will be able to view the changes after refreshing the page only. We will solve this by using Appwrite's realtime service.

## 👩‍🔧 Realtime

We will start by adding a subscribe method to **src/service/appwrite.js** that will connect to Appwrite realtime server and listen to any changes that we want to listen to. For our use case, we will be listening to changes to documents of our tasks collection that we created above. To do that write following function:

```js
subscribe = (callback) => {
  return this.appwrite.subscribe(`collections.${this.tasksCollection}.documents`, callback);
}
```

This method will accept a callback and will subscribe to **collections.[ID].documents** so that we will get updates to any changes made to the documents of our tasks collection. The callback will be called every time server sends any update.

Now if we go to **src/App.svelte**, there is already a function named `subscribe`, we just need to update the function body to subscribe to changes and update our tasks array. Update the subscribe function as follows.

```js
function subscribe() {
  appwrite.subscribe((payload) => {
    switch (payload.event) {
      case 'database.documents.create':
        tasks.push(payload.payload)
        tasks = tasks
        break
      case 'database.documents.update':
        tasks = tasks.map((task) => {
          if (task.$id === payload.payload.$id) {
            return payload.payload
          } else {
            return task
          }
        })
        break
      case 'database.documents.delete':
        tasks = tasks.filter((task) => task.$id !== payload.payload.$id)
        break
    }
  })
}
```

Here, we are calling the subscribe method that we added earlier in **src/service/appwrite.js** and passing our callback function that receives the realtime payload that server sends.

The payload we receive will contain an `event`, and as we are subscribing to **collections.[ID].documents**, the event will be one of `database.documents.create`, `database.documents.update` or `database.documents.delete`. So we are handling each event and the payload received with that event will be the related document.

Based on the event, we are adding, removing or updating our tasks array to reflect the changes. As we update the tasks array, svelte will automatically handle the UI updates. Easy as that.

## 🥂 Conclusion

I hope you enjoyed this tutorial building a realtime Kanban board as much as I enjoyed wirting this tutorial and building project. You can view the live preview of the application [here](https://infallible-villani-a88afd.netlify.app/) and the complete source code for this application is available at [GitHub repository](https://github.com/lohanidamodar/demo-web-realtime/tree/final). Feel free to get back to us if you have any queries or comments. Excited to see what the community will build with Flutter and Appwrite Realtime. 

## 🎓 Learn More

- [Getting Started With Web](https://appwrite.io/docs/getting-started-for-web)
- [Web Playground](https://github.com/appwrite/playground-for-web)
- [Appwrite Docs](https://appwrite.io/docs)