# SDK quickstart (/en/realtime-media/im/get-started-sdk/web)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

Instant messaging enhances user engagement by enabling users to connect and form a community within the app. Increased engagement can lead to increased user satisfaction and loyalty to your app. An instant messaging feature can also provide real-time support to users, allowing them to get help and answers to their questions quickly. The Chat SDK enables you to embed real-time messaging in any app, on any device, anywhere.

This page guides you through implementing peer-to-peer messaging into your app using the Chat SDK.

## Understand the tech [#understand-the-tech]

The following figure shows the workflow of sending and receiving peer-to-peer messages using Chat SDK.

<details>
  <summary>
    Chat SDK workflow
  </summary>

  ![understand](https://assets-docs.agora.io/images/im/get-started-sdk-understand.png)
</details>

1. Clients retrieve an authentication token from your app server.
2. Users log in to Chat using the App ID, their user ID, and token.
3. Clients send and receive messages through Chat as follows:
   1. Client A sends a message to Client B. The message is sent to the Agora Chat server.
   2. The server delivers the message to Client B. When Client B receives a message, the SDK triggers an event.
   3. Client B listens for the event to read and display the message.

## Prerequisites [#prerequisites]

In order to follow the procedure on this page, you must have:

* A valid [Agora account](/en/realtime-media/im/get-started/manage-agora-account#create-an-agora-account).
* An [Agora project](/en/realtime-media/im/get-started/manage-agora-account#create-an-agora-project) for which you have [enabled Chat](./enable#enable-).
* The [App ID](./enable#get-chat-project-information) for the project.
* Internet access.

  Ensure that no firewall is blocking your network communication.

      
  
      
  
      
    * A Windows or macOS computer that meets the following requirements:
      * A browser supported by the Agora Chat SDK:
        * Internet Explorer 9 or later
        * FireFox 10 or later
        * Chrome 54 or later
        * Safari 6 or later
      * Access to the Internet. If your network has a firewall, follow the instructions in [Firewall Requirements](https://docs.agora.io/en/Agora%20Platform/firewall) to access Agora services.
    * [Node.js and npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)

    
  
      
  
      
  
      
  
      
  
## Project setup [#project-setup]

      
  
      
  
      
    To create the environment necessary to add peer-to-peer messaging into your app, do the following:

    1. Use VITE to create a new project. If VITE is not installed, run `npm i vite -g` to install it. Then, run `npm create vite@latest agora_quickstart`. In this example, we choose "React + JavaScript" to create the project.

    The project directory now has the following structure:

    ```text
    agora_quickstart
    ├─ index.html
    ├─ main.js
    └─ package.json
    ```

    2. Integrate the Agora Chat SDK into your project through npm.
       Add 'agora-chat' and 'vite' to the 'package.json' file.

       ```json
        {
            "name": "agora_quickstart",
            "private": true,
            "version": "0.0.0",
            "type": "module",
            "scripts": {
                "dev": "vite",
                "build": "vite build",
                "preview": "vite preview"
            },
            "dependencies":{
                "agora-chat": "latest"
            },
            "devDependencies": {
                "vite": "^3.0.7"
            }
        }
       ```

    
  
      
  
      
  
      
  
      
  
## Implement peer-to-peer messaging [#implement-peer-to-peer-messaging]

This section shows how to use the Chat SDK to implement peer-to-peer messaging in your app, step by step.

      
  
      
  
      
    Copy the following code to the `App.jsx` file to implement the UI:

    ```jsx
    import { useEffect, useState, useRef } from "react";
    import "./App.css";
    import AgoraChat from "agora-chat";

    function App() {
      // Replaces <Your App ID> with your App ID.
      const appId = "<Your App ID>";
      const [userId, setUserId] = useState("");
      const [token, setToken] = useState("");
      const [isLoggedIn, setIsLoggedIn] = useState(false);
      const [peerId, setPeerId] = useState("");
      const [message, setMessage] = useState("");
      const [logs, setLogs] = useState([]);
      const chatClient = useRef(null);

      // Logs into Agora Chat.
      const handleLogin = () => {
        if (userId && token) {
          chatClient.current.open({
            user: userId,
            // Use agoraToken for v1.2.1 and earlier, but accessToken for 1.2.2 and later.
            accessToken: token,
          });
        } else {
          addLog("Please enter userId and token");
        }
      };

      // Logs out.
      const handleLogout = () => {
        chatClient.current.close();
        setIsLoggedIn(false);
        setUserId("");
        setToken("");
        setPeerId("");
      };

      // Sends a peer-to-peer message.
      const handleSendMessage = async () => {
        if (message.trim()) {
          try {
            const options = {
              chatType: "singleChat", // Sets the chat type as a one-to-one chat.
              type: "txt", // Sets the message type.
              to: peerId, // Sets the recipient of the message with user ID.
              msg: message, // Sets the message content.
            };
            let msg = AgoraChat.message.create(options);

            await chatClient.current.send(msg);
            addLog(`Message send to ${peerId}: ${message}`);
            setMessage("");
          } catch (error) {
            addLog(`Message send failed: ${error.message}`);
          }
        } else {
          addLog("Please enter message content");
        }
      };

      // Add log.
      const addLog = (log) => {
        setLogs((prevLogs) => [...prevLogs, log]);
      };

      useEffect(() => {
        // Initializes the Web client.
        chatClient.current = new AgoraChat.connection({
          appId: appId,
        });

        // Adds the event handler.
        chatClient.current.addEventHandler("connection&message", {
          // Occurs when the app is connected to Agora Chat.
          onConnected: () => {
            setIsLoggedIn(true);
            addLog(`User ${userId} Connect success !`);
          },
          // Occurs when the app is disconnected from Agora Chat.
          onDisconnected: () => {
            setIsLoggedIn(false);
            addLog(`User Logout!`);
          },
          // Occurs when a text message is received.
          onTextMessage: (message) => {
            addLog(`${message.from}: ${message.msg}`);
          },
          // Occurs when the token is about to expire.
          onTokenWillExpire: () => {
            addLog("Token is about to expire");
          },
          // Occurs when the token has expired.
          onTokenExpired: () => {
            addLog("Token has expired");
          },
          onError: (error) => {
            addLog(`on error: ${error.message}`);
          },
        });
      }, []);

      return (
        <>
          <div
            style={{
              width: "500px",
              display: "flex",
              gap: "10px",
              flexDirection: "column",
            }}
          >
            <h2>Agora Chat Examples</h2>
            {!isLoggedIn ? (
              <>
                <div>
                  <label>UserID: </label>
                  <input
                    type="text"
                    value={userId}
                    onChange={(e) => setUserId(e.target.value)}
                    placeholder="Enter the user ID"
                  />
                </div>
                <div>
                  <label>Token: </label>
                  <input
                    type="text"
                    value={token}
                    onChange={(e) => setToken(e.target.value)}
                    placeholder="Enter the token"
                  />
                </div>
                <button onClick={handleLogin}>Login</button>
              </>
            ) : (
              <>
                <h3>Welcome, {userId}</h3>
                <button onClick={handleLogout}>Logout</button>
                <div>
                  <label>Peer userID: </label>
                  <input
                    type="text"
                    value={peerId}
                    onChange={(e) => setPeerId(e.target.value)}
                    placeholder="Enter the peer user ID"
                  />
                </div>
                <div>
                  <label>Peer message: </label>
                  <input
                    type="text"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    placeholder="Input message"
                  />
                  <button onClick={handleSendMessage}>Send</button>
                </div>
              </>
            )}

            <h3>Operation log</h3>
            <div
              style={{
                height: "300px",
                overflowY: "auto",
                border: "1px solid #ccc",
                padding: "10px",
                textAlign: "left",
              }}
            >
              {logs.map((log, index) => (
                <div key={index}>{log}</div>
              ))}
            </div>
          </div>
        </>
      );
    }

    export default App;
    ```

    <a name="test" />

    
  
      
  
      
  
      
  
      
  
## Test your implementation [#test-your-implementation]

To ensure that you have implemented Peer-to-Peer Messaging in your app:

      
  
      
  
      
    Use vite to build the project. You can run below commands to run the project.

    ```bash
    $ npm install
    ```

    ```bash
    $ npm run dev
    ```

    The following page opens in your browser:

    ![Agora chat examples web](https://assets-docs.agora.io/images/im/agora-chat-examples-empty.png)

    To validate the peer-to-peer messaging you have just integrated into your Web app using Agora Chat:

    1. Log in

       Fill in the user ID of the sender (`Leo`) in the **user id** box and agora token in the **token** box, and click **Login** to log in to the app.

    2. Send a message

       Fill in the user ID of the receiver (`Roy`) in the **single chat id** box and type in the message ("Hi, how are you doing?") to send in the **message content** box, and click **Send** to send the message.

       ![Send a message](https://assets-docs.agora.io/images/im/send-message-web.png)

    3. Log out

       Click **Logout** to log out of the app.

    4. Receive the message

       Open the same page in a new window, log in as the receiver (`Roy`) and receive the message ("Hi, how are you doing?") sent from **Leo**.

       ![Receive a message](https://assets-docs.agora.io/images/im/receive-message-web.png)

    
  
      
  
      
  
      
  
      
  
## Reference [#reference]

This section contains content that completes the information in this page, or points you to documentation that explains other aspects to this product.

* For more code samples, see [Samples and demos](./downloads).

      
  
      
  
      
    For details:

    * [Manual install](./reference/manual-sdk-install) shows you how to integrate Chat SDK into your project manually.

    * [Sample code](https://github.com/AgoraIO/Agora-Chat-API-Examples/blob/main/Chat-Web/src/index.js) for getting
      started with Chat.

    * Install the [demo app](./reference/downloads).

    
  
      
  
      
  
      
  
      
  
### Next steps [#next-steps]

In a production environment, best practice is to deploy your own token server. Users retrieve a token from the token server to log in to Chat. To see how to implement a server that generates and serves tokens on request, see [Secure authentication with tokens](../develop/authentication).
