npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-plugin-websocket

v0.1.2

Published

Add WebSocket support to Next.js API routes

Downloads

27

Readme

next-plugin-websocket

Add WebSocket support to Next.js API routes

Features

  • Zero configuration - Just install the package and you're good to go
  • Hot reloading - Whenever an API route is modified, any open sockets will be automatically disconnected
  • URL routing - The connection URL will get correctly mapped to the corresponding Next.js /api page

Compatibility

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 instance and the second argument will be the original request object.

Basic example (echo server)

import { NextApiHandler } from "next";
import { NextWebSocketHandler } from "next-plugin-websocket";

export const socket: NextWebSocketHandler = (client, req) => {
  console.log("Client connected");

  client.on("message", (msg) => {
    client.send(msg);
  });

  client.on("close", () => {
    console.log("Client disconnected");
  });
};

// You still need to expose a regular HTTP handler, even if you only intend to
// use this API route for WebSocket connections.
const handler: NextApiHandler = (req, res) => {
  res.status(426).send("Upgrade Required");
};

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

This plugin works by injecting a couple of micro-patches into the Next.js core in node_modules. It also uses a syntax tree parser to ensure that it ends up in exactly the right place, which makes it more resilient to changes over time. However, there are a couple of things to be aware of when using this module:

  1. It may not work with every permutation of Next.js, as it relies on patching at install time and Next.js may change internals relied upon by the syntax parser / patch injection pipeline
  2. Any node package manager that doesn't use a node_modules folder won't work, as that's how the patch is applied. This means no Yarn PnP support (yet)
  3. Because it still relies on having access to a HTTP server instance to bind the HTTP upgrade handler, it won't work in environments that take full control of how Next.js is deployed (i.e. it doesn't use the server.js file generated in the standalone output mode, or next start). This means that serverless environments might be hit or miss depending on whether or not they provide an instance of http.Server to Next.js
  4. You still must expose a regular HTTP handler from an API route, even if you only intend to use the socket handler