# Multiplayer UI - Create login screen and friends list (Part 1)

> Making a multiplayer game requires users to log into their account before playing. User accounts are essential for connecting players in the game and lobby.

> Documentation index: https://coherent-labs.com/llms.txt lists every page of this documentation as Markdown; the full text is in https://coherent-labs.com/llms-full.txt.

Source: https://coherent-labs.com/blog/uitutorials/multiplayer-ui/login-friends/

## Multiplayer UI - Create login screen and friends list (Part 1)

ui tutorials

7/31/2024

Kaloyan Geshev

1. Prerequisites
2. Showcase Overview
3. Source location
4. Getting started - Backend
   1. Server index
   2. API routes
   3. Middlewares
   4. User database schema
   5. Sessions database schema
   6. User controller
5. Getting started - Frontend
   1. React router and routes
   2. Making requests to the backend
   3. Login and register pages
   4. Home page
   5. Friends list page
   6. Adding friends page

This tutorial is the first part of the posts about creating a UI for a multiplayer game.

You can find the rest Multiplayer UI series here.

Making a multiplayer game requires users to log into their account before playing. User accounts are essential for connecting players in the game and lobby. They also enable features like adding friends, chatting, viewing other players’ stats, and inviting users to game sessions.

## Prerequisites

In this tutorial, we will use [`React 18` ](https://react.dev/)with `React Router 6` for the frontend and [`Express` ](https://expressjs.com/)for the Backend part. Additionally, we’ll utilize our components: [scrollable container ](https://coherentlabs.github.io/GameUIComponents/en/components/scrollable-container/)and [Grid ](https://coherentlabs.github.io/GameUIComponents/en/components/grid/).

## Showcase Overview

In this example, we will create a multiplayer game UI featuring login and registration screens, and a friends list that shows their names, with options to add or remove friends.

The game server will handle API calls from the UI.

**Note: When testing the sample, avoid entering sensitive information during registration. Passwords are stored as plain text in the database for testing purposes.**

## Source location

You can find the complete sample source within the `${Gameface package}/Samples/uiresources/UITutorials/MultiplayerUI` directory.

- `src` folder contains the UI source code.
- `api` folder contains the Express server source code.

Refer to the `README.md` file in this directory for information on running the sample locally or previewing it without building or starting any processes.

## Getting started - Backend

We will begin by setting up the backend using Express. To start, install the required modules:

```shell
npm i express mongoose express-session cors connect-mongo
```

### Server index

The `index.js` file for our server will establish a connection to the database and start the server on port 3000. We have already set up a cloud MongoDB database and hardcoded the URL into the server index file.

```js
const express = require('express');
const mongoose = require('mongoose');
const router = require('./config/router');
const session = require('express-session');
const cors = require('cors');
const app = express();
const port = 3000;
const MongoStore = require('connect-mongo');
const { createServer } = require('node:http');
const path = require('node:path');
const server = createServer(app);

app.use(express.static(path.join(__dirname, '../dist'))); // Serve the frontend build folder if we choose to load the UI from the server. However, we suggest not loading your UI from the server and instead directly loading the index.html file in Gameface

app.use(cors())
app.use(express.json());
const mongoUrl = 'mongodb+srv://kaloyang:788DaVnkzXAfh8Q6@clsamples.pgjogro.mongodb.net/CLSampleDB?retryWrites=true&w=majority&appName=CLSamples';
mongoose.connect(mongoUrl);

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
    console.log('Connected to MongoDB');
});

app.set('trust proxy', 1)
app.use(session({
    secret: 'some secret',
    resave: false,
    name: 'api-session-key',
    saveUninitialized: true,
    store: MongoStore.create({ mongoUrl }),
    cookie: { maxAge: 1000 * 60 * 60 }, // 1 hour
}))

app.use('/api', router);

// Serve the index.html for any GET requests if we load the UI from the server, which is an option that works in Gameface but not suggested.
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../dist', 'index.html'));
});

// Start the server
server.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});
```

Here, the frontend is expected to be built inside the `../dist` folder so the server can serve it.

### API routes

With the entry file for the server set up, we need to configure API routes. In this sample, we have user-related routes with the following entry points:

```js
const express = require('express');
const router = express.Router();

require('./routes/user')(router);

module.exports = router;
```

```js
const UserController = require('../../controllers/userController');
const auth = require('../../middlewares/auth');
const idValidator = require('../../middlewares/idValidator');

module.exports = (router) => {
    router.post('/login', UserController.login); // Handle user login
    router.post('/logout', UserController.logout); // Handle user logout
    router.post('/register', UserController.register); // Handle new user registration
    router.get('/users/:id', auth, idValidator, UserController.getUser); // Get the user data
    router.put('/users/:id', auth, idValidator, UserController.updateUser); // Update the user data
    router.get('/users/:id/potential-friends', auth, UserController.getPotentialFriends); // Get potential friends for a specific user
    router.get('/users/:id/friends', auth, idValidator, UserController.getUserFriends); // Get the friends list of a user
    router.post('/users/:id/add-friend', auth, idValidator, UserController.addFriend); // Add another user as a friend
    router.post('/users/:id/remove-friend', auth, idValidator, UserController.removeFriend); // Remove user from friends list
};
```

### Middlewares

Certain routes are protected using middlewares such as `auth`, which verifies if a user is logged in, and `idValidator`, which checks if a valid user ID is present in the request parameters.

```js
const sessions = require("../db/sessions");

module.exports = async (req, res, next) => {
    const sessionId = req.headers['session-id'];
    if (!sessionId) return res.status(404).send('Unauthorized');

    const session = await sessions.findOne({ _id: sessionId });
    if (session && session.expires >= new Date()) return next();

    res.status(404).send('Unauthorized');
}
```

To authenticate a user, we check for an existing session and confirm that it has not expired. The session expiration date is stored in the database. Since Gameface does not store session cookies on the frontend, requests should include the `session-id` header containing the session ID generated by the backend and stored in Gameface’s `localStorage`.

```js
const { ObjectId } = require("mongodb");

module.exports = (req, res, next) => {
    if (!ObjectId.isValid(req.params.id)) return res.status(404).send('Not valid id!');
    next();
}
```

This middleware validates whether the request from the frontend includes a valid MongoDB ID in the `id` parameter.

### User database schema

After connecting to the database, we need to define the schema for the `users` table.

```js
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    password: String,
    status: Boolean,
    friends: [{ type: String }]
});

module.exports = mongoose.model('user', schema);
```

Once the schema is defined, we can use the model to access user data in the database.

### Sessions database schema

To store user sessions when they log in, we need an additional table in the database with the following structure.

```js
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    expires: Date,
    session: String,
    _id: String,
});

module.exports = mongoose.model('sessions', schema);
```

### User controller

The User Controller manages requests and returns relevant responses by performing operations with the database.

For example, fetching user data is accomplished with the following code:

```js
...
const User = require('../db/users'); // Get the user model so we can make calls to the database
...
class UserController {
   ...
   async getUser(req, res) {
      const user = await User.findById(req.params.id); // Find the user by id and return its data
      if (!user) {
         return res.status(404).send('User not found');
      }
      res.json(user);
   }
   ...
}
```

Attention needs to be given to how users can log in or log out of our game. For user login, the backend should receive the user’s email, password, and session data. **As previously mentioned, we store the `session-id` in `localStorage` in Gameface since there are no cookies. The frontend must pass the session-id header when making a login request to check if the user is already logged in.**

Once the session is checked, we need to validate the user’s email and password. If the database does not contain a user with the provided email and password, the login request is denied. If the credentials are correct, the user’s status is set to `true`, and the `sessionId` along with user data is returned so the frontend can recognize a successful login.

Logging out is straightforward: change the user’s status to `false` and delete the relevant session from the database.

```js
class UserController {
   ...
   async login(req, res) {
      const sessionId = req.headers['session-id'];
      if (sessionId && await sessions.findOne({ _id: sessionId })) return res.send(sessionId);

      const user = await User.findOne({ email: req.body.email, password: req.body.password });
      if (!user) return res.status(404).send('Wrong email or password!');
      user.status = true; // Change the user status to true
      await user.save(); // Save the changed status
      res.json({ id: user._id.toString(), sessionId: req.sessionID, firstName: user.firstName, lastName: user.lastName });
   }
   ...
   async logout(req, res) {
      const sessionId = req.headers['session-id'];
      const userId = req.headers['user-id'];
      if (!sessionId) return res.status(200).send(); // If there is no session there is no user for logging out

      if (!await changeUserStatus(userId, sessionId, false)) return res.status(200).send(); // Change the status to false
      await sessions.deleteOne({ _id: sessionId }); // Delete the session from the sessions table
      res.status(200).send();
   }
   ...
}
```

```js
async function changeUserStatus(userId, sessionId, status) {
    if (!userId) return false;
    if (!sessionId && !await sessions.findOne({ _id: sessionId })) return false;

    const user = await users.findById(userId);
    if (!user) return false;
    user.status = status;
    await user.save();

    return true;
}
```

For more information on other handlers, refer to `/api/controllers/userController.js`.

With this basic backend setup, we can proceed to the frontend.

## Getting started - Frontend

For the frontend, we will use the `React` framework. To avoid going into extensive detail, you can open the entire project in `${Gameface package}/Samples/uiresources/UITutorials/MultiplayerUI` and check the following:

- README.md - Contains information on how to run the sample.
- package.json - Includes scripts for building the frontend, starting the server, etc.
- webpack.config.js - Contains the webpack configuration that bundles the frontend source.
- src folder - Holds the frontend source code.

Now, let’s focus on some details about the frontend.

### React router and routes

We want our sample to have three pages: `Login`, `Register`, and `Home`. For this, we can use `React Router`. The home screen will have sub-routes for the friends list and adding friends.

```jsx
const App = () => (
    <HashRouter basename='/'>
        <AuthProvider>
            <Routes>
                <Route path='/' element={<ProtectedRoute><Home /></ProtectedRoute>} >
                    <Route index element={<Friends />} />
                    <Route path="/add-friends" element={<AddFriends />} />
                </Route>
                <Route path='/register' element={<Register />} />
                <Route path='/login' element={<Login />} />
            </Routes>
        </AuthProvider>
    </HashRouter>
);
```

Here, the `<ProtectedRoute>` component acts as a wrapper to grant access to the home page if you are logged in. If not, you will be redirected to the login page.

```jsx
export const ProtectedRoute = ({ children }) => {
    const { user } = useAuth();
    if (!user) return <Navigate to="/login" />

    return children;
}
```

The protected route checks for a logged-in user via the `useAuth` hook, which utilizes the `AuthContext` to provide user data.

```jsx
import React, { createContext, useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useLocalStorage } from "./useLocalStorage";
const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useLocalStorage("user", null);
    const navigate = useNavigate();

    const login = async (data) => {
        setUser(data);
    };

    const logout = () => {
        setUser(null);
        navigate("/login", { replace: true });
    };

    const value = useMemo(
        () => ({
            user,
            login,
            logout,
        }),
        [user]
    );
    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = () => {
    return useContext(AuthContext);
};
```

To handle user data in `localStorage`, we use an additional hook, `useLocalStorage`. This hook stores or retrieves an item from `localStorage` based on the provided key. It also uses a default value if the key is not found in `localStorage`.

```jsx
import { useState } from "react";

export const useLocalStorage = (key, defaultValue = null) => {
    const [storedValue, setStoredValue] = useState(() => {
        try {
            const value = localStorage.getItem(key);
            if (value) return JSON.parse(value);

            localStorage.setItem(key, JSON.stringify(defaultValue));
            return defaultValue;
        } catch (err) {
            return defaultValue;
        }
    });

    const setValue = (newValue) => {
        try {
            localStorage.setItem(key, newValue);
        } catch (err) {
            console.log(err);
        }
        setStoredValue(newValue);
    };

    return [storedValue, setValue];
};
```

### Making requests to the backend

As a frontend developer, you typically use the `fetch` method to make requests to the backend. However, `fetch` is not supported by Gameface, so you should use `XMLHttpRequest` instead. Since we’ll be making these requests frequently, it’s practical to create a reusable hook. Additionally, we need to send the session ID and user ID as headers with each request. To facilitate this, we can use other hooks like `useLocalStorage` within our custom `useFetch` hook to retrieve the user data.

```jsx
import { useNavigate } from 'react-router-dom';
import { useLocalStorage } from './useLocalStorage';

const useFetch = () => {
    const [user, setUser] = useLocalStorage('user');
    const navigate = useNavigate();

    const fetch = (method, url, body) => {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open(method, url);
            if (user) {
                xhr.setRequestHeader('session-id', user.sessionId);
                xhr.setRequestHeader('user-id', user.id);
            }
            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
            xhr.send(JSON.stringify(body));
            xhr.onload = function () {
                if (xhr.status === 200) return resolve([xhr, null]);

                if (xhr.responseText === 'Unauthorized') {
                    setUser(null);
                    navigate('/login');
                }
                console.error(`Error ${xhr.status}: ${xhr.responseText}`);
                return resolve([xhr, `${xhr.responseText}`]);
            };
            xhr.onerror = function () {
                resolve([xhr, `An error occured!`]);
            };
        })
    }

    return fetch;
}

export default useFetch;
```

In this hook, `const [user, setUser] = useLocalStorage('user');` retrieves the user data.

If user data is stored in `localStorage`, we set the request headers after opening the xhr.

```js
const xhr = new XMLHttpRequest();
xhr.open(method, url)
if (user) {
      xhr.setRequestHeader('session-id', user.sessionId);
      xhr.setRequestHeader('user-id', user.id);
}
```

We also handle `Unauthorized` responses, ensuring that if the user is not authorized by the server, they are redirected to the login page to log in and try again.

```js
xhr.onload = function () {
      if (xhr.status === 200) return resolve([xhr, null]);

      if (xhr.responseText === 'Unauthorized') {
         setUser(null); // Remove the user data from the localstorage
         navigate('/login'); // Navigate to the login page
      }
      console.error(`Error ${xhr.status}: ${xhr.responseText}`);
      return resolve([xhr, `${xhr.responseText}`]);
};
```

### Login and register pages

These pages are straightforward as they include a few input fields for user data. Since Gameface does not support the `form` element, we need to handle data submission manually. Here is an example for the login page, which is similar to the register page.

```jsx
const Login = () => {
    const [user] = useLocalStorage('user');
    const navigate = useNavigate();
    const [error, setError] = useState('');
    if (user) {
        return <Navigate to='/' />; // Navigate to home page if user is already logged in.
    }

    // Keep references to the email and password inputs to access their values on submit.
    const [emailRef, passowrdRef] = [useRef(null), useRef(null)];
    const { login } = useAuth();
    const fetch = useFetch();
    const onSubmit = async () => {
        setError(''); // Reset error message
        const email = emailRef.current.value;
        const password = passowrdRef.current.value;
        const [xhr, error] = await fetch('POST', `${process.env.SERVER_URL}/api/login`, { email, password }); // Make login POST request
        if (error) {
            setError(error); // Display error if any
            return console.error(error);
        }

        login(xhr.responseText); // Log in the user and save user data from the server to localStorage
    }

    return (
        <div className="login-wrapper">
            <div className="login-screen">
                <div className='form-item email'>
                    <span className='label'>Email:</span>
                    <input ref={emailRef} type="text" />
                </div>
                <div className='form-item password'>
                    <span className='label'>Password:</span>
                    <input ref={passowrdRef} type="password" />
                </div>
                {error && <span className='error-message'>{error}</span>}
                <button className="login" onClick={onSubmit}>Login</button>
            </div>
        </div>
    )
}

export default Login;
```

The register page follows a similar pattern. Here is a snippet for handling the submit request:

```jsx
const onSubmit = async () => {
   setMessage({ text: '', type: '' });
   const email = emailRef.current.value;
   const firstName = firstNameRef.current.value;
   const lastName = lastNameRef.current.value;
   const password = passowrdRef.current.value;
   const [xhr, error] = await fetch('POST', `${process.env.SERVER_URL}/api/register`, { email, password, firstName, lastName }); // Make post register request to the server
   if (error) {
      setMessage({ text: error, type: 'error' }); // Display error if any
      return console.error(error);
   }
   setMessage({ text: 'Successfully registered! You will be redirected to the login page in a few seconds', type: 'success' });
   // Redirect to the login page after 3 seconds
   setTimeout(() => {
      navigate("/login");
   }, 3000);
}
```

### Home page

The home page contains a container with friends and a logout button. To display the subroutes defined for the home page, we use the `Outlet` component from React Router.

```jsx
const Home = () => {
    const { logout } = useAuth();
    const fetch = useFetch();
    const onLogout = useCallback(async () => {
        const [xhr, error] = await fetch('POST', `${process.env.SERVER_URL}/api/logout`);
        if (error) return;
        logout();
    }, []);

    return (
        <div id="main-screen">
            <div className='friends-container-wrapper'>
                <div className='friends-navigation'>
                    <NavLink className='nav-btn' to="/">Friends</NavLink >
                    <NavLink className='nav-btn' to="/add-friends">Add friends</NavLink >
                </div>
                <div className="friends-container">
                    <Outlet />
                </div>
            </div>
            <button className='logout-btn nav-btn' onClick={onLogout}>Log out</button>
        </div>
    )
}

export default Home;
```

### Friends list page

For the friends list page, we’ll use `gameface-scrollable-container` to enable scrolling through the list and `gameface-grid` to structure the list items. Our database schema stores an array of friend IDs for each user. Since this array doesn’t contain full friend information, we’ll fetch detailed data for each friend when needed.

```jsx
const Friends = () => {
   const [user] = useLocalStorage('user');
   const [friends, setFriends] = useState([]);
   const fetch = useFetch();

   useEffect(() => {
      updateFriendsList();
   }, []);

   const removeFriend = useCallback(async (event) => {
      const userId = event.target.dataset.userId;

      const [xhr, error] = await fetch('POST', `${process.env.SERVER_URL}/api/users/${user?.id}/remove-friend`, { friendId: userId }); // Remove friend form the user's friends list
      if (error) return console.error(error);

      await updateFriendsList();
   }, [])

   const updateFriendsList = useCallback(async () => {
      const [xhr, error] = await fetch('GET', `${process.env.SERVER_URL}/api/users/${user?.id}/friends`); // The the user's friends ids
      if (error) return;

      const friendsIds = JSON.parse(xhr.responseText);
      const friendsArr = [];

      for (const friendId of friendsIds) {
         const [friendXhr, errorFriend] = await fetch('GET', `${process.env.SERVER_URL}/api/users/${friendId}`); // Get data for a user that is a friend to the current one
         if (errorFriend) continue;

         const friendData = JSON.parse(friendXhr.responseText);
         friendsArr.push(friendData);
      };

      setFriends(friendsArr);
   });

   return (

      <div className="all-friends-wrapper">
         <div className="friends">
               <gameface-scrollable-container automatic className="scrollable-container-component">
                  <component-slot data-name="scrollable-content">
                     <div className='friends-list'>
                           {friends.map((friend, index) => {
                              return <div key={friend._id} className='friend guic-row'>
                                 <div className='guic-col-11 friend-info'>
                                       <div className='name'>{friend.firstName} {friend.lastName}</div>
                                 </div>
                                 <div className='guic-col-1 remove-btn'>
                                       <span className='remove-icon' data-user-id={friend._id} onClick={removeFriend}>-</span>
                                 </div>
                              </div>
                           })}
                     </div>
                  </component-slot>
               </gameface-scrollable-container>
         </div>
      </div>
   )
}

export default Friends;
```

### Adding friends page

This page works similarly to the friends list page. It fetches all users from the database who are not the current user and are not already friends with the current user. These users are displayed in a list, and they can be added as friends by clicking the `+` button.

```jsx
const AddFriends = () => {
   const [user] = useLocalStorage('user');
   const [users, setUsers] = useState([]);
   const fetch = useFetch();

   useEffect(() => {
      updateUsersList();
   }, []);

   const updateUsersList = useCallback(async () => {
      const [xhr, error] = await fetch('GET', `${process.env.SERVER_URL}/api/users/${user?.id}/potential-friends`); // Gets the potential friends for the current user from the server
      if (error) return;

      setUsers(JSON.parse(xhr.responseText));
   }, [])

   const addFriend = useCallback(async (event) => {
      const userId = event.target.dataset.userId;

      const [xhr, error] = await fetch('POST', `${process.env.SERVER_URL}/api/users/${user?.id}/add-friend`, { friendId: userId });
      if (error) return console.error(error);

      await updateUsersList(); // Update the users list when we added a friend
   }, []);

   return (
      <div className="all-users-wrapper">
         <div className="all-users">
               <gameface-scrollable-container automatic fixed-slider-height className="scrollable-container-component">
                  <component-slot data-name="scrollable-content">
                     {users.map((user, index) => {
                           return <div key={user.id} className='user guic-row'>
                              <div className='guic-col-10 user-info'>
                                 <div className='name'>{user.firstName} {user.lastName} &#40;{user.email}&#41;</div>
                              </div>
                              <div className='guic-col-1 add-btn'>
                                 <span className='add-icon' data-user-id={user.id} onClick={addFriend}>+</span>
                              </div>
                           </div>
                     })}
                  </component-slot>
               </gameface-scrollable-container>
         </div>
      </div>
   )
}

export default AddFriends;
```

## On this page
