Navigate back to the homepage
Browse Repo

Rendering real-time data with Vue, Node, and

Obinna Okoro
July 21st, 2022 · 6 min read

Sockets are usually best for real-time data communications between clients and servers. They are very beneficial over REST APIs, especially for online games. They help users interact with their game and send their data to the server, and then the server forwards this data to other players in the game.

In this tutorial, I will show you how to render real-time data over the server and how sockets are used. We will create a very simple block game using Vue.Js, Node.Js, and We are using over REST APIs because we need real-time data, which is only deliverable over sockets. This game isn’t going to be very hardcore; all we will do is render 2D objects using an HTML canvas, and interact with them through various clients, as seen in the image below. Clicking on the buttons moves the block for all players. There will be various components involved in this tutorial.


Getting started at the server side

We will start with the server-side component, then head straight into the Vue.js client component afterward. I take it that you have Node.js installed. Create a directory for the server side and navigate to your directory, and input the following

1nnpm init -y
2touch index.js

If the touch command doesn’t seem to work on your end, you can create an index.js file manually inside the directory. This creates a package.json which will carry all the dependencies we will apply throughout this tutorial within the server. Before we proceed further, we will install some packages we would need for this project. We will need the nodemon package, and we need to configure it. Then we will require the express framework and the package.

1npm install express --save
2npm install nodemon --save-dev

We will focus now on our index.js file and quickly set things up. We will be tracking a player’s position, and we are going to store our player’s position server side. (This means when the server restarts, it terminates all of our data, which is OK for this tutorial.) So in the index.js, I will make an object named position to store the x and y values.

1const Express = require("express")();
2const Http = require("http").Server(Express);
3const Socketio = require("")(Http, {
4 cors: {
5 origin: "*",
6 },
9//inputting our position values
10let position = {
11 x: 200,
12 y: 200,
15//listening to a PORT
16Http.listen(3000, () => {
17 console.log("Server up and running...");

The whole logic behind what will happen here is that the Vue client will never be in control of our player’s position: it will all be determined server-side. The server will broadcast the positions to all the clients, and they will just display the positions on the screen. The client will request the server to move, and the latter will change the position. We will not make any direct changes from the client level; it will all depend on the server, which would help prevent users from cheating and spoofing player positions.

We will do one more thing before we leave the server component, but we are not done with it just yet; we will return to it. We are going to listen for a particular event, as seen below.

1let position = {
2 x: 200,
3 y: 200,
6Socketio.on("connection", (socket) => {
7 socket.emit("position", position);

The connection above is a reserved kind of label for messages, so every time a client connects to the server, it will trigger the connection event. We will emit a particular message to that particular socket that just connected, and that message will contain the x and y value positions.

The client side

We will take a break from the server side and head into the Vue component. Assuming you have the Vue CLI installed, we can create a new Vue project and give it the project name.

1vue create client

We also need to install as we did earlier for the server component. After installation, quickly rename the file in the src folder to App.vue and the Hello-world file in the components folder to BlockGame.vue.


Once you have successfully changed the file names, the next thing we have to do is to set up the App.vue file. Navigate to App.vue and remove the template tag’s and style tag’s initial content, import the blockgame file into the script tag, and set the component object to BlockGame. Input the BlockGame component in the template tag wrapped in a div. Your App.vue file should look like this:

2 //calling the BlockGame to the template tag
3 <div id="app">
4 <BlockGame />
5 </div>
9//importing the BlockGame component into the app file
10import BlockGame from "./components/BlockGame.vue";
11export default {
12 name: "app",
13 components: {
14 BlockGame,
15 },

After setting up the App.vue file, we head into our BlockGame file in the component folder and set it up. Then we will add a canvas in the div tag and give it a reference name (game) because in Vue you cannot just access the DOM components with querySelectors; you have to use references. We will add width, height, and border information so that you can easily see what the canvas consists of. Now inside our script, we would need to import the we downloaded earlier and then declare a few variables inside the class object, including the socket connection object, which would be empty at the moment. We add a context object and a position object consisting of an x and y value so we don’t encounter null data floating around.

2 <!-- creating the HTML canvas -->
3 <div>
4 <canvas ref="game" width="640" height="480" style="border: 1px solid black">
5 </canvas>
6 <p>
7 <button v-on:click="move('right')">Right</button>
8 <button v-on:click="move('left')">Left</button>
9 <button v-on:click="move('up')">Up</button>
10 <button v-on:click="move('down')">Down</button>
11 </p>
12 </div>
15//importing the we installed
16import io from "";
17export default {
18 name: "BlockGame",
19 data() {
20 return {
21 socket: {},
22 context: {},
23 position: {
24 x: 0,
25 y: 0,
26 },
27 };
28 },
31<style scoped></style>

We now have the option to connect to our server, and then we have the option of listening to events and issuing events. First, we need to establish a connection, which is best done in the created lifecycle hook for Vue before the Vue renders. We would have to specify our host for the sockets we defined, which is done in the created method.

Once the Vue renders, we want to start listening to events. We want to start working alongside our canvas. To do this, we would have to use the mounted lifecycle event and then, grab the context object and then add some references (2d) to it. This would add a large empty square box to the left side of your web page. The next step is to draw a rectangle inside the empty square box, set its position, and give it a size. We will be using 20 by 20 pixels for the size of the rectangular block, which should create a small rectangular black block at the left end of the square box.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.


Start enjoying your debugging experience - start using OpenReplay for free.

Listening for messages

Now that we have the boxes and have initialized their position, we need to listen for messages. So just like we did for the server side, we will call the socket.on to listen for the position we emitted from the index.js file. We will add a data object which will carry our rectangular block in it, but it will not render until we get a position back from the application. To solve that, we are going to initialize the position to data. If you go into your web browser, you’d observe that the rectangular block has moved because of the x and y value positions (200, 200) we set in our index.js file. We will receive different positions from time to time, and because of that, we have to set our canvas to clear on each interval. The next step is to make the rectangle move. To do that, you have to create a method and set a moving object that would emit two things, the label name, and the directions. For now, if you go into your webpage and try moving it, the rectangle won’t move, but not to worry, we aren’t done yet.

1return {
2 socket: {},
3 context: {},
4 position: {
5 x: 0,
6 y: 0,
7 },
8 };
9 },
10 //the created lifecycle hook
11 created() {
12 //connecting to our host
13 this.socket = io("http://localhost:3000");
14 },
15 //the mounted lifecycle hook
16 mounted() {
17 //creating the 2d canvas
18 this.context = this.$"2d");
19 this.socket.on("position", (data) => {
20 this.position = data;
21 //clearing the rectangular block at intervals
22 this.context.clearRect(
23 0,
24 0,
25 this.$,
26 this.$
27 );
28 //creating a rectangular block sized 20x20
29 this.context.fillRect(this.position.x, this.position.y, 20, 20);
30 });
31 },
32 //creating a method to emit the directions to the server side
33 methods: {
34 move(direction) {
35 this.socket.emit("move", direction);
36 },
37 },
40<style scoped></style>

Next up, we need to create a couple of buttons in our template div to use the method we created. Inside these buttons, we will add an onclick listener, name it move, pass in a direction, and then close the tag and do the same for the rest of the buttons. Once done, we should have an up, down, left, and right button in the web browser.

2 <!-- creating the HTML canvas -->
3 <div>
4 <canvas ref="game" width="640" height="480" style="border: 1px solid black">
5 </canvas>
6 <!--create a p tag to format the button properly in your browser-->
7 <p>
8 <button v-on:click="move('right')">Right</button>
9 <button v-on:click="move('left')">Left</button>
10 <button v-on:click="move('up')">Up</button>
11 <button v-on:click="move('down')">Down</button>
12 </p>
13 </div>

So now, let’s go back into our index.js and start planning to listen to the directions. Head inside the sockets connection and set up a new socket.on to listen for the move messages and create a data object that would hold different switch events. In the first case (left), set the position x to equal -5, and then the socketio emits the position. Observe that we used socketio instead of just socket because sockets emit to just a particular client while socketio emits to all connected clients, then breaks the case. You are to do the same for the rest of the cases; the right should have a position x of +5, the up should have the position y of -5, and finally, the down should have the position y of +5 accompanied by their socketio emit to emit these positions and then break to end the cases.

1//connection to emit the positions to all connected clients
2Socketio.on("connection", (socket) => {
3 socket.emit("position", position);
4//connection to the move buttons and method to send back conditions to perform
5 socket.on("move", (data) => {
6 switch (data) {
7 case "left":
8 position.x -= 5;
9 Socketio.emit("position", position);
10 break;
11 case "right":
12 position.x += 5;
13 Socketio.emit("position", position);
14 break;
15 case "up":
16 position.y -= 5;
17 Socketio.emit("position", position);
18 break;
19 case "down":
20 position.y += 5;
21 Socketio.emit("position", position);
22 break;
23 }
24 });

If you head into your browser and click any of the buttons, you will observe that the rectangle will move in that clicked direction. The client is now receiving the positions we set earlier in the server and then broadcasting them to the browser to make all the various movements.



This is a good example of using and Vue.js. It’s a better example than just doing the typical chat server that everybody does! This game is pretty simple because it has no competitive angle; all we did was create a server with Node.js and a client with Vue.js. The server sends position information to the client, and the client uses this information to render the 2D canvas on your screen, which means we now have a game component to this, and we are using it as if it was a game server. It’s a great example of using sockets with vue.js and node.js.

Git repo:


More articles from OpenReplay Blog

JavaScript Types and Values, explained

An introduction to a most basic and important concept

July 20th, 2022 · 10 min read

PyScript: Python on the Web

Use Python, instead of JavaScript, to develop web pages

July 20th, 2022 · 5 min read
© 2022 OpenReplay Blog
Link to $ to $ to $