Setting up Socket.IO
To set up the Socket.IO server, we are going to base our code on what we had in Chapter 6, Adding Authentication and Roles with JWT, as it already includes some boilerplate for a backend and frontend with JWT authentication. Later in this chapter, in the Adding authentication by integrating JWT with Socket.IO section, we are going to make use of JWT to add authentication to Socket.IO:
- Copy the existing
ch6folder to a newch13folder, as follows:$ cp -R ch6 ch13
- Open the
ch13folder in VS Code. - Now, we can start setting up Socket.IO. First, install the
socket.iopackage in the backend folder by running the following commands:$ cd backend/ $ npm install socket.io@4.7.2
- Edit
backend/.envand changeDATABASE_URLso that it points to a newchatdatabase:DATABASE_URL=mongodb://localhost:27017/chat
- Edit
backend/src/app.jsand import thecreateServerfunction fromnode:httpand theServerfunction fromsocket.io:import { createServer } from &apos...