# express-socket.io-middleware

> This middleware allows you to use the existing HTTP REST API as a WebSocket.

Latest version **0.0.4** (published 2021-11-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install express-socket.io-middleware
pnpm add express-socket.io-middleware
yarn add express-socket.io-middleware
bun add express-socket.io-middleware
```

## Health

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

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.4 |
| Published | 2021-11-24 |
| First published | 2021-09-21 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 9 |
| Unpacked size | 24.8 KB |
| Known vulnerabilities | 0 (+26 in 2 direct dependencies) |
| Install scripts | no |
| GitHub stars | 1 |
| Maintainers | stegano |
| Keywords | express, socket.io, socketio, chat, websocket |

## Links

- npm: https://www.npmjs.com/package/express-socket.io-middleware
- Repository: https://github.com/stegano/express-socket.io
- Homepage: https://github.com/stegano/express-socket.io#readme
- Issues: https://github.com/stegano/express-socket.io/issues
- npm.io page: https://npm.io/package/express-socket.io-middleware

## Dependencies (9)

- [axios](https://npm.io/package/axios.md) ^0.21.4
- [express](https://npm.io/package/express.md) ^4.17.1
- [ts-node](https://npm.io/package/ts-node.md) ^10.2.1
- [socket.io](https://npm.io/package/socket.io.md) ^4.2.0
- [jsonwebtoken](https://npm.io/package/jsonwebtoken.md) ^8.5.1
- [@types/express](https://npm.io/package/@types/express.md) ^4.17.13
- [@types/jsonwebtoken](https://npm.io/package/@types/jsonwebtoken.md) ^8.5.5
- [eslint-config-prettier](https://npm.io/package/eslint-config-prettier.md) ^8.3.0
- [eslint-plugin-prettier](https://npm.io/package/eslint-plugin-prettier.md) ^4.0.0

## 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

- 0.0.4 (latest) — 2021-11-24
- 0.0.3 — 2021-09-21
- 0.0.2 — 2021-09-21
- 0.0.1 — 2021-09-21

## README

# Express Socket.io Middleware
> This middleware allows you to use the existing HTTP REST API as a WebSocket.

## Installation

The easiest way to install `express-socket.io-middleware` is with [npm](https://www.npmjs.com/package/express-socket.io-middleware).

```bash
npm install express-socket.io-middleware
```

Alternately, download the source.

```bash
git clone https://github.com/stegano/express-socket.io-middleware.git
```

## Example
This middleware allows you to process all rest api requests and responses implemented as websockets.
### Server
```ts
...
const app = express();
const server = http.createServer(app);
const io = new Server(server, { 
  path: '/ws',
});

app
  .use(socketIoMiddleware(io, 'http://localhost:3000', 'secret!'))
  .get('/test', (_, res) => {
    res.send({message: 'Hello World'})
  });

server.listen(3000);
...
```

### Clients
* You can change the event name in configuration. Please check the [Configuration](#configuration) section.
#### Client With Socket.io
> Request through websocket and receive a response
```ts
// 1) Create and connect socket object
const socket = io({
      path: '/ws',
      transports: ['websocket']
    });

// 2) Send request using WebSocket
socket.emit('request', {
  pathanme: '/test',
  method: 'GET',
  data: {},
  params: {}
});

// 3) Receive response using WebSocket
socket.on('response', (data) => {
  console.log(data); // `{ request: {...}, response: { ..., data: 'Hello World' }} }`
});
```

#### Client With HTTP API and Socket.io
> Request using REST API and receive response using WebSocket
```ts
// 1) Create and connect socket object
const socket = io({
      path: '/ws',
      transports: ['websocket']
    });

// 2) Receive auth token via WebSocket
socket.on('token', ({token}) => {
  // 3) Send REST API request with `authentication` header
  axios.get('/test', {
    headers: {
      authorization: `Bearer ${token}`
    }
  })
});


socket.on('response', (data) => {
  // 4) Receive REST API response as WebSocket
  console.log(data); // `{ request: {...}, response: { ..., data: 'Hello World' }} }`
});
```

## Configuration
```ts
  /**
   * Send an error message to the socket
   * When an unexpected error occurs during internal processing of socketIoMiddleware.
   */
  unexpectedErrorMessage?: string
  /**
   * This setting can transform the response payload data to be sent to the socket.
   */
  transformResponsePayload?: (data: ResponsePayload) => any
  /**
   * This setting can change the socket event name.
   */
  eventNames?: {
    /**
     * When a socket is connected, it sends a JWT. This token contains authentication information
     * about the socket to connect to when making an API request.
     */
    token?: string
    /**
     * The name of the event to request with the websocket.
     */
    request?: string
    /**
     * The name of the event that will receive a response to information requested by the websocket.
     */
    response?: string
  }
  __advanced__?: {
    /**
     * Whether keepalive is enabled when communicating with the server internally
     */
    httpKeepAlive?: boolean
    /**
     * Setting up the axios library that is internally communicating with the server
     * @see https://github.com/axios/axios#request-config
     */
    axiosRequestConfig?: AxiosRequestConfig
  }
```

## Internal Implementation
This middleware internally sends an HTTP request to the web server and sends the received response value to the connected web socket.

---
_Source: https://npm.io/package/express-socket.io-middleware · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
