Client Side (Socket) - VanillaJS
Client-side code:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io("urlofyourserver");
// Send the JWT token to the server to authenticate the user
socket.emit("auth", token);
// Send when you want to logout
// socket.emit("unauth");
// Handle user logout when the window is closed
window.addEventListener("beforeunload", () => {
socket.emit("unauth");
});
</script>In this example, we've included the Socket.IO client library and created a Socket.IO instance. We've then sent a JWT token to the server using the auth event to authenticate the user. If the user is authenticated, the server will emit the authorized event, and if the user is not authenticated, the server will emit the unauthorized event.
Note that you will need to implement the authentication and authorization logic on the server-side using the JWT token. You can use a library like jsonwebtoken to decode and verify the token, and then use the information in the token to determine if the user is authorized to access the requested resource.
Also, make sure to handle the disconnect event on the client-side and send the unauth event to the server to log out the user.
Last updated
Was this helpful?