Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

next-plugin-websocket

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-plugin-websocket

Add WebSocket support to Next.js API routes

  • 0.1.0
  • npm
  • Socket score

Version published
Weekly downloads
2
decreased by-50%
Maintainers
1
Weekly downloads
 
Created
Source

next-plugin-websocket

Add WebSocket support to Next.js API routes

Features

  • Hot reloading - whenever an API route is modified, any TCP sockets open for that page will be automatically disconnected.

Compatibility

  • ✅ Next.js ^13 (with or without appDir)
  • output: "standalone"

Installation

yarn add next-plugin-websocket

Usage

Export a socket handler function from a Next.js API route. The first argument will be the WebSocket client and the second argument will be the original request object.

Basic example

import { appRouter } from "@/server/routers/_app";
import { NextApiHandler } from "next";
import { NextWebSocketHandler } from "next-plugin-websocket";

export const socket: NextWebSocketHandler = (client, req) => {
  client.on("message", (msg) => {
    client.send(msg);
  });
};

const handler: NextApiHandler = (req, res) => {
  res.status(405).end();
};

export default handler;

tRPC example

import { appRouter } from "@/server/routers/_app";
import { createNextApiHandler } from "@trpc/server/adapters/next";
import { applyWSSHandler } from "@trpc/server/adapters/ws";
import { NextWebSocketHandler } from "next-plugin-websocket";
import { WebSocketServer } from "ws";

export const socket: NextWebSocketHandler = (client, req) => {
  const wss = new WebSocketServer({ noServer: true });
  applyWSSHandler({ wss, router: appRouter });
  wss.emit("connection", client, req);
};

export default createNextApiHandler({
  router: appRouter,
});

Caveats

TODO

FAQs

Package last updated on 11 Feb 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc