# @cs125/koa-easy-ws

> Simple Koa middleware for websocket handling

Latest version **1.1.3** (published 2020-08-10) · MIT license · 0 weekly downloads

## Install

```sh
npm install @cs125/koa-easy-ws
pnpm add @cs125/koa-easy-ws
yarn add @cs125/koa-easy-ws
bun add @cs125/koa-easy-ws
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.3 |
| Published | 2020-08-10 |
| First published | 2020-08-10 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 15.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 76 |
| Author | Ben Snow |
| Maintainers | geoffrey.challen |
| Keywords | koa, websocket, ws |

## Links

- npm: https://www.npmjs.com/package/@cs125/koa-easy-ws
- Repository: https://github.com/b3nsn0w/koa-easy-ws
- Homepage: https://github.com/b3nsn0w/koa-easy-ws#readme
- Issues: https://github.com/b3nsn0w/koa-easy-ws/issues
- npm.io page: https://npm.io/package/@cs125/koa-easy-ws

## Dependencies (2)

- [ws](https://npm.io/package/ws.md) ^7.2.3
- [debug](https://npm.io/package/debug.md) ^4.1.1

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 1.1.3 (latest) — 2020-08-10

## README

Simple, easy to use, composable middleware for websocket handling in Koa

# Usage

```javascript
const Koa = require('koa')
const websocket = require('koa-easy-ws')

const app = new Koa()

app.use(websocket())
app.use(async (ctx, next) => {
  // check if the current request is websocket
  if (ctx.ws) {
    const ws = await ctx.ws() // retrieve socket

    // now you have a ws instance, you can use it as you see fit
    return ws.send('hello there')
  }
  
  // we're back to regular old http here
  ctx.body = 'general kenobi'
})
```

First, you need to pass the koa-easy-ws middleware before the one handling your request. Remember to call it as a function, `app.use(websocket())`, not `app.use(websocket)`. This sets up on-demand websocket handling for the rest of the middleware chain.

The middleware adds the `ctx.ws()` function whenever it detects an upgrade request, calling which handles the websocket and returns a [ws][ws] instance. If not called, regular Koa flow continues, likely resulting in a client-side error.

# Features

 - No magic. This is a middleware, it doesn't turn your Koa app into a KoaMagicWebSocketServer. It knows its place.
 - Integrates [ws][ws], one of the fastest and most popular websocket libraries.
 - Full composability. Since this is just a middleware, it's not picky on what other libraries you use.
 - Minimal, unopinionated 40 SLOC codebase. Seriously, this readme alone contains more code than what's imported into your project. (sorry about the tests though)
 - Two dependencies only, and it's the ws library and [debug][debug] (because apparently logs are not a bad idea). No need for more clutter in your node_modules.

# Examples and advanced configuration

You can easily compose koa-easy-ws with a routing library:

```javascript
const Koa = require('koa')
const Router = require('koa-router')
const websocket = require('koa-easy-ws')

const app = new Koa()
const router = new Router()

app
  .use(websocket())
  .use(router.routes())
  .use(router.allowedMethods())

router.get('/pow/obi', async (ctx, next) => {
  if (ctx.ws) {
    const ws = await ctx.ws()
    ws.send('chancellor palpatine is evil')
  }
})

router.get('/pow/ani', async (ctx, next) => {
  if (ctx.ws) {
    const ws = await ctx.ws()
    ws.send('the jedi are evil')
    ws.send('404')
  }
})
```

If `ctx.ws()` isn't enough for you, the websocket server instance is also exposed:

```javascript
const Koa = require('koa')
const websocket = require('koa-easy-ws')

const app = new Koa()
const websocketMiddleware = websocket()
const websocketServer = websocketMiddleware.server // this is where the fun begins

app.use(websocketMiddleware) // we already have the instance here

// <insert rest of the app>
```

This gives you access to the [ws][ws] server object, allowing to pass down custom listeners, connection validators, etc.

In case `ctx.ws` conflicts with something else in your code, koa-easy-ws doesn't mind changing the property name, just pass it as a property. This also lets you use multiple websocket middlewares if you ever find a reason to do so:

```javascript
const Koa = require('koa')
const websocket = require('koa-easy-ws')

const app = new Koa()

app.use(websocket('sidious')) // we just renamed ctx.ws to ctx.sidious
app.use(websocket('maul')) // attach another one for no good reason

app.use(async (ctx, next) => {
  // the first middleware detected an upgrade request
  if (ctx.sidious) {
    const socket = await ctx.sidious()
    return socket.send('this is getting out of hand')
  }

  // the second middleware detected the same upgrade request
  if (ctx.maul) {
    const socket = await ctx.maul()
    return socket.send('now there are two of them')
  }
})
```

Note: in this example `ctx.maul` is never used because there is no limit on the authority of `ctx.sidious`. However, if you define custom logic this technique could sort incoming requests to separate websocket servers.

From here, the sky is the limit, unless you work for SpaceX.

# Special usage for Node 9 or earlier

Node's HTTP server doesn't send upgrade requests through the normal callback (and thus your Koa middleware chain) prior to version 10, preventing koa-easy-ws from handling them. Because of this, if you target Node 9 or earlier, you must pass your HTTP server to the middleware which handles the workaround:

```javascript
const server = http.createServer(app.callback())

app.use(websocket('ws', server))

// alternatively, you can pass it as part of the options object:
app.use(websocket('ws2', {
  server: server
}))

server.listen(process.env.PORT) // use this function instead of your app.listen() call
```

koa-easy-ws then automatically feeds any upgrade request into your regular middleware chain. If you wish to opt out and do this yourself, use the `noServerWorkaround` option:

```javascript
app.use(websocket('ws', {
  noServerWorkaround: true
}))
```

# Contributing

Pull requests are welcome. As always, be respectful towards each other and maybe run or create tests, as appropriate. It's on `npm test`, as usual.

koa-easy-ws uses the MIT license. Was considering the WTFPL, but I like the "no warranty" clause.

[ws]: https://github.com/websockets/ws
[debug]: https://github.com/visionmedia/debug

---
_Source: https://npm.io/package/@cs125/koa-easy-ws · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
