DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Develop a Scraper With Node.js, Socket.IO, and Vue.js/Nuxt.js

Trending

  • Designing Agentic Systems Like Distributed Systems
  • Beyond Conversation: Mastering Context with Claude Code Skills and Agents
  • Spring Boot Done Right: Lessons From a 400-Module Codebase
  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning

Use Socket.IO With Nuxt.js/Vue.js

Learn how to implement the Socket.IO Javascript library with Nuxt.js and Vue.js. Plus learn more information about the socket.emit and socket.on methods.

By 
Malaya Mathur user avatar
Malaya Mathur
·
Updated Oct. 21, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

For one of my recent Nuxt.js projects, I had to use Socket.IO to send the data from the server to the users in real-time without reloading the whole page. Initially, I was using Vue.js, but then the client insisted on implementing Nuxt.js for the server-side rendering purpose.

First, I used Axios as a middleware to send and receive HTTP requests. Axios is a great library to send and receive data without loading the whole page. It works great with Vue.js and Node.js. But the problem with Axios is that it only sends the response once with res.send or res.end method. If you try to send two or more times with these methods, then the app crashes.

To solve this issue, I used the Socket.IO library. I already used Socket.IO with Vanilla Javascript and Node.js, but I had no idea how things are done with Nuxt.js and Vue.js. I had to research to figure out how this whole thing works. For that reason, I have shared how to set up Socket.IO with Nuxt.js. You can just copy the piece and paste it anywhere you want to.

The NPM packages you need to install before getting started:

  • Socket.IO: To use Socket.IO easily, you need to install Socket.IO package for Nuxt.js
  • Socket.IO client: Install this package to use socket.emit and socket.on methods on the client-side

You also need Express.js installed. If you are using Nuxt.js, then it installs by default. So, apart from Socket packages, you do not need to install anything else.

Let’s dive into the code now.

Install packages

Install NPM  and save socket.io and socket.io-client

Now, open the nuxt.config.js file and update the module block:

JavaScript
 
modules: [
   ['~/io'],
  ],

For my project, I created an app that gets the IP address of a user, and based on the location, it returns the price of the cryptocurrency in their currency. For example, if a user is from the US then the tool shows data in the US dollar. Along with that, with the help of Socket.IO, the price changes in real-time. To store the data, I converted all the decimals of an IP address into hexadecimal for safety purposes and when I had to show the IP address to the user, I converted hexadecimal to decimal number. Since this article is about implementing Socket.IO, I’m going to stick to that. But just to give an idea of how a hexadecimal to decimal converter can help store data, I shared the example.

Now, open the plugins folder placed at the root. Inside of the plugins folder, create a .js file and name it "socket.io.js." Copy and paste the following code inside of that socket.io.js file:

JavaScript
 
import io from 'socket.io-client'
const socket = io(process.env.WS_URL)

export default socket

Now, create a new folder and name it "io" at the root level. Inside of that root folder, create a new file and name it "index.js." Paste the following code inside that index.js file:

JavaScript
 
import socketIO from 'socket.io'
var network = require('network');
export default function () {
  this.nuxt.hook('render:before', (renderer) => {
    const server = http.createServer(this.nuxt.renderer.app)
    const io = socketIO(server)

    // overwrite nuxt.server.listen()
    this.nuxt.server.listen = (port, host) => new Promise(resolve => server.listen(port || 3000, host || 'localhost', resolve))
    // close this server on 'close' event
    this.nuxt.hook('close', () => new Promise(server.close))

    // Add socket.io events
    const messages = []
    io.on('connection', (socket) => {
      socket.on('last-messages', function (fn) {
network.get_public_ip(function(err, ip) {
socket.emit(‘ip’, ip); // should return your public IP address
})     
var x = new BigNumber(ip, 16)
    var dectobin = x.toString(10);
 })
    })
  })
}

All the server-side work is done. Now, you need to add the following code to the front-end Vue file. I have not added the HTML (the template part in the Vue), but just the script part.

JavaScript
 
<script>
import socket from '~/plugins/socket.io.js'
export default {

  data () {
    return { message: 'send', messages: [], isShowing: false, isShowing1: false, isShowing2: false }
  },
  beforeMount () {
    socket.on(ip', (ip) => {
      console.log(ip)
      this.messages.push(ip)
    })
  },

  methods: {
    senlocation () {
      socket.emit('last-messages ')
    },
    },
}
</script>

Front-End and Back-End Code Explanation

Apart from the two Socket.IO methods, there is everything Vue in the code. Here, in the code, we have used two Socket.IO methods heavily, socket.emit & socket.on on both front-end and back-end. 

Socket.emit method: This method is used whenever you want some data or an alert from or to the server.

Socket.on method: This method is used to listen to the socket.emit. This method constantly watches the socket and as soon as it gets data from the server, it shows it to the user without loading the whole page.

Socket.IO

Opinions expressed by DZone contributors are their own.

Related

  • Develop a Scraper With Node.js, Socket.IO, and Vue.js/Nuxt.js

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook