This repository is an experiment in using a WebSocket server to host an HTTP-like API for clients. The goal is to provide faster communication between client and server and allow easy handling of disconnect issues since we can track WebSocket connection live and provide real time status to the user. This is a very basic example that includes a signup and signin route to create and store user accounts, we automatically hash user passwords using Argon2 for greater security and handle authenticated requests with jwt (see notes below). You could easily extend this example to host more data and build out a full featured API.
- Run
cd Server && npm ito change to Server directory and install Server packages - Create
.envfile with the following parameters:MONGOOSE,JWT_SECRETwhereMONGOOSEis your MongoDB connection url andJWT_SECRETis your JWT secret (see Notes) - Run
npm startto start the server - Connect to
ws://localhost:8080with your choice of WebSocket tools (see Notes) - Send Sign Up request via socket as JSON for example
{ "route": "signup", "username": "Cryptobyte", "password": "password" } - Send Sign In request via socket as JSON for example
{ "route": "signin", "username": "Cryptobyte", "password": "password" }and note thetokenfield in response for next requests, this is your JWT for authention! - Send the example request to check if your JWT is valid, this is an example request to show how verifying authentication works, for example
{ "route": "get-data", "token": "YOUR_JWT" }
- Run
cd Server && npm ito change to Server directory and install Server packages - Create
.envfile with the following parameters:MONGOOSE,JWT_SECRETwhereMONGOOSEis your MongoDB connection url andJWT_SECRETis your JWT secret (see Notes) - Run
npm startto start the server - In a new terminal run
cd Client && npm ito install client packages - Run
cd app && npm ito install React app packages - Change to the Client directory
cd ..and runnpm start - Open http://localhost:3000 in your browser
- You should not use this as configured, you should look at the WebSocket (ws) library page and setup the server to use HTTPS and look at the jwt library page and setup a private key instead of a shared token first!
- You can test the server with various WebSocket tools, I use and recommend websocat