@alexcolls/nuxt-socket.io
v0.0.6
Published
Nuxt module for Socket.io (server & client)
Downloads
10
Readme
nuxtSocketIO
Nuxt module for Socket.io (server & client).
Features
- ⛰ Plug & Play
- 🚠 Websocket connection
- 🌲 Baz
Quick Setup
- Add
@alexcolls/nuxt-socket.io
dependency to your project
# Using pnpm
pnpm add @alexcolls/nuxt-socket.io
# Using yarn
yarn add @alexcolls/nuxt-socket.io
# Using npm
npm install @alexcolls/nuxt-socket.io
- Add
@alexcolls/nuxt-socket.io
to themodules
section ofnuxt.config.ts
import socketServer from "./server/sockets";
export default defineNuxtConfig({
modules: ["@alexcolls/nuxt-socket.io"],
nuxtSocketIO: {
initSocketServer: socketServer,
},
});
In the server folder create a file named sockets.ts (or a folder sockets/index.ts) with the init function for the socket server.
import { Server, Socket } from "socket.io";
const printUsersConnected = (usersConnected: number) => {
console.log(
`${usersConnected} user${usersConnected === 1 ? "" : "s"} connected`
);
};
export default function (io: Server) {
let usersConnected = 0;
io.on("connection", (socket: Socket) => {
// Connection/Disconnection events
usersConnected++;
printUsersConnected(usersConnected);
socket.on("disconnect", () => {
usersConnected--;
printUsersConnected(usersConnected);
});
// Socket events
socket.on("message", (message: object) => {
console.log("Server received:", message);
});
});
}
That's it! You can now use nuxtSocketIO in your Nuxt app ✨
Usage
You can access to the socket instance in the client just like this:
const { $socket } = useNuxtApp();
$socket.emit("event", "Hello from client!");
$socket.on("event", () => {
// Do something...
});
Development
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev
# Build the playground
npm run dev:build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Release new version
npm run release