Giter Club home page Giter Club logo

nuxt3-socket.io's Introduction

nuxt3-socket.io

Warning

This module will soon be deprecated in favor of the built-in WebSocket API.

Just another socket.io module for Nuxt 3.

This module uses the Vite server in development and req.socket.server in production.

Install

pnpm add nuxt3-socket.io
export default defineNuxtConfig({
  modules: ['nuxt3-socket.io'],
  socket: {
    // JSON serializable options only.
    // options object to pass when instantiating socket server.
    serverOptions: {}
  }
})

Usage

Client

<script setup>
// Default
const socket = useSocket()

const connected = ref(false)

onMounted(() => {
  socket.on('connect', () => {
    connected.value = socket.connected
  })

  socket.on('disconnect', () => {
    connected.value = socket.connected
  })
})

// Custom
const { $io } = useNuxtApp()

onMounted(() => {
  const socket2 = $io('http://localhost:3069')
})
</script>

<template>
  <div>Connected: {{ connected }}</div>
</template>

Server

By default, this module automatically creates a server instance. If you want access to that server instance, you can expose functions inside server/socket and use the defineIOHandler wrapper function:

// server/socket/example.ts
import { defineIOHandler } from 'nuxt3-socket.io/helpers'

export default defineIOHandler((io) => {
  io.on('connection', (socket) => {
    console.log('Connected ', socket.id)
  })
})

It's recommended to roll your own socket server if you need more customization other than what is specified here.

Development

  • Run npm run dev:prepare to generate type stubs.
  • Use npm run dev to start playground in development mode.

License

MIT

nuxt3-socket.io's People

Contributors

renegade1912 avatar simllll avatar wobsoriano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nuxt3-socket.io's Issues

Hot Reloading not working

When updating the socket.io server file in (e.g. /server/socket/example.ts the message) โœ” Nitro built in 232 ms appears in the console, but the changes are not applied until I do a full restart of the Nuxt dev server.

Is this a known issue?

Can not access globalThis.__io

When I access globalThis.__io, it always return undefined.
How can I fix it ?
Thank you for supporting.

Additional, I use environment io.to(roomId).emit('function') to send message to specific room in socket.
I think we need to guide to use it.

possibility to access server io?

is there a way to access the io server from e.g. an api route? e.g. I would like to retur na list of existing rooms:

return [...$io.of('/').adapter.rooms.keys()];

but right now I haven't found a way to access $io.

one possible "workaround" is that I actually implement this inside of socket/.. and return a list of rooms from there, and the api also connecs to the socket.io server. but this seems a bit "shady"?

Access runtimeconfig in handler

I require some of the nuxt config settings that would typically be available using useRuntimeConfig. However, that doesn't work from within the handler. Is there any way to retrieve these values?

useSocket composable

The useSocket composable initialises a socket straight away on the default endpoint "/". In my case the socket needs some auth data sent or else the server will reject it and an error will print in the console.

Is it possible to disable the useSocket and only use the useIO composables?

Doesn't work in production ?

Hi, thanks you for this module.

It seems it doesn't work in production.
I ran into the same issue #5 but fixed it by changing this module package.json to load mjs.
"exports": {
".": {
"import": "./dist/module.mjs",
"require": "./dist/module.mjs"
}
},
I don't know why but it fixed the following error
ERROR [unhandledRejection] (0 , _nuxt3Socket.defineIOHandler) is not a function

It works in dev mode, I can emit/listen to events but then I've build my nuxt app in production mode and i got this error :
[nuxt] error caught during app initialization H3Error: Page not found: /socket.io/?EIO=4&transport=polling&t=ORHw0wF

It seems it doesn't serve the routes to connect to the IO server

io is not a function and _nuxt3Socket.defineIOHandler is not a function

Hello,

I try to use this module, but I don't understand how to properly set it up based on the README.

I added nuxt3-socket.io to the modules and added

socket: {
    // JSON serializable options only.
    // options object to pass when instantiating socket server.
    serverOptions: {}
  } 

to my config. I also added the client example to a page. I had to remove const socket2 = io('http://localhost:3069') as it throws the error io is not a function. After that, the socket connects. Just for my understanding: this example connects to a default server socket that is included, running on the same port as the page? socket2 would be to connect to a different socket on a custom port & url?

If I try to customise the default server socket by creating the file /server/socket/test.ts with the example from the README, I get the following error when starting nuxt:
ERROR [unhandledRejection] (0 , _nuxt3Socket.defineIOHandler) is not a function
What did I do wrong in both cases?

It would be great if you can point me in the right direction.

ERROR Cannot start nuxt: (0 , _nuxt3Socket.defineIOHandler) is not a function

Nuxt 3.6.5
nuxt3-socket.io 0.2.0

Error in dev and prod

 ERROR  Cannot start nuxt:  (0 , _nuxt3Socket.defineIOHandler) is not a function  

  at server\socket\index.ts:36:34
  at evalModule (node_modules\jiti\dist\jiti.js:1:255106)
  at jiti (node_modules\jiti\dist\jiti.js:1:253034)

I solved it through #6 's solution

"exports": {
    ".": {
      "import": "./dist/module.mjs",
      "require": "./dist/module.mjs"
    }
  }

ESMLoader error

Hey. Look at some error
OS win10 x64

npm run dev

`Nuxi 3.0.0 03:44:56
Nuxt 3.0.0 with Nitro 1.0.0 03:44:56
03:44:57

Local: http://localhost:3000/
Network: http://192.168.1.50:3000/

i Using Tailwind CSS from ~/assets/css/tailwind.css nuxt:tailwindcss 03:44:58
i Tailwind Viewer: http://localhost:3000/_tailwind/ nuxt:tailwindcss 03:44:58

ERROR Cannot start nuxt: Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'd:'

at new NodeError (node:internal/errors:372:5)
at throwIfUnsupportedURLScheme (node:internal/modules/esm/resolve:1120:11)
at defaultResolve (node:internal/modules/esm/resolve:1200:3)
at ESMLoader.resolve (node:internal/modules/esm/loader:580:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18)
at ESMLoader.import (node:internal/modules/esm/loader:380:22)
at importModuleDynamically (node:internal/modules/esm/translators:106:35)
at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)
at /D:/apps/nuxt3-mysql-docker/node_modules/nuxt3-socket.io/dist/module.mjs:50:27
at /D:/apps/nuxt3-mysql-docker/node_modules/hookable/dist/index.mjs:39:82`

package:
{ "private": true, "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", "postinstall": "nuxt prepare", "start": "node .output/server/index.mjs" }, "devDependencies": { "@nuxtjs/tailwindcss": "^6.2.0", "nuxt": "3.0.0", "prisma": "^4.8.0" }, "dependencies": { "@prisma/client": "^4.8.0", "nuxt3-socket.io": "^0.0.11", "puppeteer": "^19.4.1", "socket.io": "^4.5.4", "socket.io-client": "^4.5.4" } }

nuxt.config
// https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ modules: [ '@nuxtjs/tailwindcss', 'nuxt3-socket.io', ], })

Error: io-dev-functions

After install i got this

] ERROR Cannot start nuxt: Cannot find module '/PROJECT/.nuxt/io-dev-functions' imported from /PROJECT/node_modules/nuxt3-socket.io/dist/module.mjs
[0]
[0] at new NodeError (node:internal/errors:387:5)
[0] at finalizeResolution (node:internal/modules/esm/resolve:429:11)
[0] at moduleResolve (node:internal/modules/esm/resolve:1006:10)
[0] at defaultResolve (node:internal/modules/esm/resolve:1214:11)
[0] at nextResolve (node:internal/modules/esm/loader:165:28)
[0] at ESMLoader.resolve (node:internal/modules/esm/loader:844:30)
[0] at ESMLoader.getModuleJob (node:internal/modules/esm/loader:431:18)
[0] at ESMLoader.import (node:internal/modules/esm/loader:528:22)
[0] at importModuleDynamically (node:internal/modules/esm/translators:110:35)
[0] at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)

`socket.on` function is not firing in client.js

Here is my client.js

<template>
  <div>Connected: {{ connected }}</div>
</template>

<script setup>
import { onMounted, ref } from "vue";

const socket = useSocket();

const connected = ref(false);

onMounted(() => {
  socket.on("connect", () => {
    connected.value = socket.connected;
  });

  socket.on("disconnect", () => {
    connected.value = socket.connected;
  });
});
</script>

I find socket.on function is not firing. But server.js has output in console.

Connected  AVAWGi-9qUpNL2LuAAAt

package.json

 "nuxt3-socket.io": "^0.3.0",

Did I miss something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.