Skip to content
Chandan Kumar

Remix: Web Socket connection Tutorial under 5 minutes, and beyond

remix, react1 min read

To setup Socket.io with Remix we need to do the following

  • Setup Remix App with Express
  • Add Web socket dependencies
  • Tweak package.json to run dev server concurrently
  • Update Remix route with Socket.io connection

Source code: https://github.com/ch4nd4n/practice/tree/master/remix/socket-ex

Create a remix app with express server, I am using the name socket-ex but this could be anything of your choice.

1npx create-remix@latestsock

Will use express

1R E M I X
2
3💿 Welcome to Remix! Let's get you set up with a new project.
4
5? Where would you like to create your app? socket-ex
6? Where do you want to deploy? Choose Remix if you're unsure, it's easy to change deployment targets. Express Server
7? TypeScript or JavaScript? TypeScript
8? Do you want me to run `npm install`? Yes

Change to socket-ex folder to start the development

1cd socket-ex

Install socket.io dependency

1npm install socket.io socket.io-client

At the point of writing this post, I figured that one is better off by updating package.json with concurrently dependency that allows development easier

1npm install -D concurrently

Update package.json

1"dev": "concurrently \"remix watch\" \"cross-env NODE_ENV=development node server/index.js\"",

Validate that server starts up by running npm run dev

To configure socket.io on server side update server/index.js with following

1const http = require("http");
2const { Server } = require("socket.io");
3const server = http.createServer(app);
4const io = new Server(server);
5
6io.on("connection", (socket) => {
7 console.log("a user connected");
8 socket.on("disconnect", () => {
9 console.log("user disconnected");
10 });
11});
12
13// Get rid of app.listen and update it with following
14
15server.listen(port, () => {
16 console.log(`Express server listening on port ${port}`);
17});

Update index.tsx

index.tsx
1import { useEffect } from "react";
2import io from "socket.io-client";
3
4export default function Index() {
5 useEffect(() => {
6 io();
7 }, []);
8 return (
9 <div>
10 <h1>Remix Socket Example</h1>
11 </div>
12 );
13}

Extending this a little further, what we can do is that whenever a user connects we broadcast it to everyone on the server side and then update client side to pick up this broadcast and update the UI

1socket.broadcast.emit("serverMsg", `user: ${socket.id}`);

Update Index route

index.tsx
1const [messages, setMessages] = useState();
2
3//
4
5const socket = io();
6 socket.on("serverMsg", function (msg) {
7 setMessages(msg);
8 });

Links

  1. https://socket.io/
  2. Express Adapter https://remix.run/docs/en/v1/other-api/adapter

Comments

Copyleft. WTH
Theme by LekoArts