How to make websockets client work with Next.JS?

Hello friends!

I’m using AdonisJS as a backend and want to use Next.JS as a frontend.
So far, the experience is amazing!

However when trying to implement sockets, I really don’t understand how I should set them up!

If I add the regenerator plugin to my .babelrc as next.js declares:

    "presets": [
          "preset-env": {},
          "transform-runtime": {},
          "styled-jsx": {},
          "class-properties": {}
      "plugins": ["@babel/plugin-transform-regenerator"]

I get a weird error saying next.js

Which leads me to think this regenerator interferes with next.js.

any other way of loading the websocket client?

ps: since next.js does server side rendering, should I take care of not importing the websocket client when rendering on the server?

I don’t have experience with next, but I think you have to setup the websocket channel inside adonisjs'foo', 'FooController')

then from server broadcast a payload

            const foo = Ws.getChannel('foo').topic('foo')
                foo.broadcast('bar', {payload})

now on front-end you have to subscribe to that channel, this is Nuxt.js which is similar to Next.js

    created() {
            const ws = this.$ws.connect(
                    wsDomain: "ws://localhost:3333", 
                    jwtToken: null
                    path: 'ws', 
                    reconnectionAttempts: 300, 
                    reconnectionDelay: 5000 
            let subscription = ws.socket.getSubscription('foo')
            if (!subscription) {
                subscription = ws.subscribe('foo');
            subscription.on('bar', (data) => {
             // do shit

EDIT: For everyone else that may have the same problem:

Next.JS already includes the regenerator runtime polyfill, so you don’t need to configure anything.
Just be sure to only load the adonis client when you render on the client.
For example

useEffect(() => {
    const Ws = require('@adonisjs/websocket-client')
    const ws = Ws('ws://localhost:3333')
    return () => {
  }, [])
1 Like