Nuxt 3 WebSockets

Add WebSockets in Nuxt 3 project with Nitro

3
0
Vue

Links

Nuxt Minimal Starter

Look at the Nuxt documentation to learn more.

Basic Implementation

export default defineWebSocketHandler({
  open(peer) {
    console.log("[ws] open: peer.id", peer.toString());
    // Join new client to the "chat" channel
    peer.send("Welcome to the server!");
    peer.subscribe("chat");
    // Notify every other connected client
    peer.publish("chat", `[system] ${peer.id} joined!`);
  },
  message(peer, message) {
    const data = JSON.parse(message.toString());
    // The server re-broadcasts incoming messages to everyone
    peer.publish("chat", JSON.stringify({ user: peer.toString(), message: message.toString() }));
    }
  },
  close(peer, event) {
    console.log("[ws] close");
    peer.publish("chat", JSON.stringify({ user: "server", message: `${peer} left!` }));
  },
  error(peer, error) {
    console.log("[ws] error");
  },
});

Setup

Make sure to install dependencies:

# npm
npm install

# pnpm
pnpm install

# yarn
yarn install

# bun
bun install

Development Server

Start the development server on http://localhost:3000:

# npm
npm run dev

# pnpm
pnpm dev

# yarn
yarn dev

# bun
bun run dev

Production

Build the application for production:

# npm
npm run build

# pnpm
pnpm build

# yarn
yarn build

# bun
bun run build

Locally preview production build:

# npm
npm run preview

# pnpm
pnpm preview

# yarn
yarn preview

# bun
bun run preview

Check out the deployment documentation for more information.