Nuxt.js: How to create a websocket connection in my custom JS file and multiple components can use socket.send function

Created on 16 Jun 2017  Â·  7Comments  Â·  Source: nuxt/nuxt.js

case 1:

custom JS file

var wsUrl = 'ws://localhost:8080';
var socket = new WebSocket(wsUrl);

Nuxt.js Error:

WebSocket is not defined

case2

custom JS file

if(typeof(window) !== 'undefined'){
    var wsUrl = 'ws://localhost:8080';
    var socket = new WebSocket(wsUrl);
 }

export {socket};

.vue file

import { socket } from '~assets/js/socket.js';
...
    mounted(){
        console.log(socket); //undefined
    }
...

chrome console:


How can I create websocket in custome Js file connection and can use in Vue file?

This question is available on Nuxt.js community (#c770)

Most helpful comment

@ausir0726 Hey, Can you please update the link. Current one is not working.

All 7 comments

you can use plugin ( both vue and nuxt 😆 )

https://glitch.com/edit/#!/join/33b8a7d9-09a5-4601-8432-4cbf67301105

@ausir0726 Can you describe detailedly? what plugin for nuxt or vue?

@jasmineY

you can see source on glitch
plugins/websocket.js and nuxt.config.js

first, write a vue websocket plugin inject to Vue global method

doc here
https://vuejs.org/v2/guide/plugins.html

second, add this js to nuxt.js plugin at nuxt.config.js , remember add ssr : false

doc here
https://nuxtjs.org/guide/plugins/#vue-plugins
example here
https://nuxtjs.org/examples/plugins

@ausir0726 Ok,thank you ,I will have a try

Just finding this now. @ausir0726 does this mean that websockets aren't supported with SSR?

@ausir0726 Hey, Can you please update the link. Current one is not working.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vadimsg picture vadimsg  Â·  3Comments

o-alexandrov picture o-alexandrov  Â·  3Comments

jaredreich picture jaredreich  Â·  3Comments

mattdharmon picture mattdharmon  Â·  3Comments

nassimbenkirane picture nassimbenkirane  Â·  3Comments