# reacting-squirrel

> React and Express framework for creating web apps.

Latest version **1.2.1** (published 2025-03-30) · MIT license · 0 weekly downloads

## Install

```sh
npm install reacting-squirrel
pnpm add reacting-squirrel
yarn add reacting-squirrel
bun add reacting-squirrel
```

Provides the commands `rs-bundle`, `rs-start-server`.

## Health

**Score 35/100 (D)** — status: maintenance-mode.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.2.1 |
| Published | 2025-03-30 |
| First published | 2018-05-09 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | >=16 |
| Dependencies | 50 |
| Unpacked size | 500.9 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Lukáš Mačuda |
| Maintainers | zabkwak |
| Keywords | react, express, socket.io, framework |

## Links

- npm: https://www.npmjs.com/package/reacting-squirrel
- Repository: https://github.com/zabkwak/reacting-squirrel
- Homepage: https://zabkwak.github.io/reacting-squirrel
- Issues: https://github.com/zabkwak/reacting-squirrel/issues
- npm.io page: https://npm.io/package/reacting-squirrel

## Dependencies (50)

- [md5](https://npm.io/package/md5.md) ^2.3.0
- [url](https://npm.io/package/url.md) ^0.11.0
- [sass](https://npm.io/package/sass.md) ^1.80.5
- [async](https://npm.io/package/async.md) ^2.6.4
- [cookie](https://npm.io/package/cookie.md) ^0.5.0
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [mkdirp](https://npm.io/package/mkdirp.md) ^1.0.4
- [uniqid](https://npm.io/package/uniqid.md) ^5.4.0
- [express](https://npm.io/package/express.md) ^4.18.2
- [postcss](https://npm.io/package/postcss.md) ^8.4.19
- [webpack](https://npm.io/package/webpack.md) ^5.75.0
- [react-dom](https://npm.io/package/react-dom.md) ^18.3.1
- [socket.io](https://npm.io/package/socket.io.md) ^4.5.4
- [ts-loader](https://npm.io/package/ts-loader.md) ^9.4.1
- [css-loader](https://npm.io/package/css-loader.md) ^6.7.2
- [prop-types](https://npm.io/package/prop-types.md) ^15.8.1
- [typescript](https://npm.io/package/typescript.md) ^5.6.3
- [@babel/core](https://npm.io/package/@babel/core.md) ^7.20.2
- [@types/node](https://npm.io/package/@types/node.md) ^20.17.6
- [args-parser](https://npm.io/package/args-parser.md) ^1.3.0
- [compression](https://npm.io/package/compression.md) ^1.7.4
- [querystring](https://npm.io/package/querystring.md) ^0.2.1
- [sass-loader](https://npm.io/package/sass-loader.md) ^12.6.0
- [smart-error](https://npm.io/package/smart-error.md) ^3.0.0
- [autoprefixer](https://npm.io/package/autoprefixer.md) ^10.4.13
- [babel-loader](https://npm.io/package/babel-loader.md) ^8.3.0
- [cli-progress](https://npm.io/package/cli-progress.md) ^3.11.2
- [loader-utils](https://npm.io/package/loader-utils.md) ^3.2.1
- [msgpack-lite](https://npm.io/package/msgpack-lite.md) ^0.1.26
- [route-parser](https://npm.io/package/route-parser.md) 0.0.5
- [runtime-type](https://npm.io/package/runtime-type.md) ^4.1.1
- [style-loader](https://npm.io/package/style-loader.md) ^3.3.1
- [cookie-parser](https://npm.io/package/cookie-parser.md) ^1.4.6
- [html-to-react](https://npm.io/package/html-to-react.md) ^1.5.0
- [@types/express](https://npm.io/package/@types/express.md) ^4.17.14
- [postcss-loader](https://npm.io/package/postcss-loader.md) ^6.2.1
- [@babel/polyfill](https://npm.io/package/@babel/polyfill.md) ^7.10.4
- [cookie-signature](https://npm.io/package/cookie-signature.md) ^1.2.0
- [http-smart-error](https://npm.io/package/http-smart-error.md) ^4.0.1
- [socket.io-client](https://npm.io/package/socket.io-client.md) ^4.5.4
- [texting-squirrel](https://npm.io/package/texting-squirrel.md) ^1.1.0
- [universal-cookie](https://npm.io/package/universal-cookie.md) ^7.2.2
- [@babel/preset-env](https://npm.io/package/@babel/preset-env.md) ^7.20.2
- [@babel/preset-react](https://npm.io/package/@babel/preset-react.md) ^7.18.6
- [combine-styles-processor](https://npm.io/package/combine-styles-processor.md) ^3.0.0
- [extra-watch-webpack-plugin](https://npm.io/package/extra-watch-webpack-plugin.md) ^1.0.3
- [@babel/plugin-proposal-decorators](https://npm.io/package/@babel/plugin-proposal-decorators.md) ^7.20.2
- [@babel/plugin-proposal-private-methods](https://npm.io/package/@babel/plugin-proposal-private-methods.md) ^7.18.6
- [@babel/plugin-transform-async-to-generator](https://npm.io/package/@babel/plugin-transform-async-to-generator.md) ^7.18.6
- [@babel/plugin-proposal-private-property-in-object](https://npm.io/package/@babel/plugin-proposal-private-property-in-object.md) ^7.18.6

## 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.2.1 (latest) — 2025-03-30
- 1.0.0-beta.37 (beta) — 2022-06-21
- 1.2.0 — 2024-11-30
- 1.1.0 — 2024-11-23
- 1.0.1 — 2024-11-22
- 1.0.0 — 2024-11-22
- 1.0.0-rc.1 — 2022-11-27
- 1.0.0-beta.36 — 2022-06-14
- 1.0.0-beta.35 — 2022-05-27
- 1.0.0-beta.33 — 2022-03-21
- 1.0.0-beta.32 — 2022-02-23
- 1.0.0-beta.31 — 2022-02-21
- 1.0.0-beta.30 — 2022-02-21
- 1.0.0-beta.29 — 2022-02-21
- 1.0.0-beta.28 — 2022-02-21
- … 142 more at https://npm.io/package/reacting-squirrel/versions

## README

# Reacting Squirrel
Framework for creation of the [React](https://reactjs.org/) apps using [Express](https://expressjs.com/) and [Socket.io](https://socket.io/). 
Sample app can be cloned from [GitHub](https://github.com/zabkwak/reacting-squirrel-sample).

## Requirements
- The module needs to be able to write in the app directory (config.appDir). It creates the directory where are stored the frontend maps.
- The module needs to be able to write in the css directory (config.cssDir). It creates one app style.
- The frontend needs the possibility to work with websockets (connection upgrade in nginx).

## Installation
```bash
npm install reacting-squirrel --save
```

## Usage
For base simple app is only required to run server (with code or cli) and create one route. If `createMissingComponents` option is set to `true` the components is not needed to be created manually. For development is recommended set `dev` option to `true`.

The server will create all necessary files and starts the webpack process. If the app is in `DEV` mode, watcher is also started.

### Simple app
Simple app structure
```
project (root)
|-- app (directory for client app)
	|-- ~rs (all RS internal files)
	|-- res (resources)
		|-- text.json (text dictionary for default locale)
	|-- home.js (Home page)
|-- public (directory for static files)
|-- index.js (the index file which runs the server)
```
```javascript
// ./index.js
import Server from 'reacting-squirrel/server';

const app = new Server();

app.registerRoute('get', '/', 'home', 'Home');

app.start();

// ./app/home.js
import React from 'react';
import { Page } from 'reacting-squirrel';

export default class HomePage extends Page {
    
    render() {
        return (
            <div>
                <h1>Home</h1>
            </div>
        );
    }
}
```
This code will start simple app on the default port with one page which will be the home page.

### App using websockets for load the user
```javascript
// ./index.js
import Server from 'reacting-squirrel/server';

import UserSocket from './socket.user';

import UserStore from './user-store';

const app = new Server({
    auth: (session, next) => {
        UserStore.load(session.id, (err, user) => {
            if (err) {
                next(err);
                return;
            }
            session.setUser(user);
            next();
        });
    }
});

app.registerRoute('get', '/', 'home', 'Home');

app.registerSocketClass(UserSocket);

app.start();

// ./socket.user.js
import { SocketClass } from 'reacting-squirrel/server';

export default class User extends SocketClass {

    load(socket, data, next) {
        next(null, this.getUser());
    }
}

// ./app/home.js
import React from 'react';
import { Page } from 'reacting-squirrel';

export default class HomePage extends Page {

    state = {
        user: null,
    };

    componentDidMount() {
        super.componentDidMount();
        this.request('user.load', (err, user) => {
            if (err) {
                alert(err.message);
                return;
            }
            this.setState({ user });
        });
    }
    
    render() {
        const { user } = this.state;
        return (
            <div>
                <h1>Home</h1>
                <h2>{user ? user.name : 'Loading...'}</h2>
            </div>
        );
    }
}
```
This code will start simple app on the default port. After the page load the `user.load` event is emitted and `UserSocket` class is trying to load the logged user and send it back to the page.

### CLI
The simple server can be started over the CLI using `./node_modules/.bin/rs-start-server` and creating `rsconfig.json` in application root.

### Providers
All components rendered by the application can be wrapped with `Provider` such as `Context.Provider` or `ThemeProvider`. Only thing needed is to register the provider with server method, rsconfig or plugin.

### Typescript
There can be issues with typings in the `app` directory because the IDE can't find `tsconfig.json` in `app/~rs` directory.
Workaround can be simply create the `tsconfig.json` in `app` directory that extends the generated configuration.
```json
{
	"extends": "./~rs/tsconfig.json"
}
```

## Core functions
### Routes register
The routes are registered on the server-side. The module is using express based routes registering.
```javascript
import Server from 'reacting-squirrel/server';

const app = new Server();

// On the route '/' will be rendered the content component located in {config.appDir}/home with 'Home' title.
app.registerRoute('get', '/', 'home', 'Home');

app.start();
```
### Socket events register
The socket events can be directly registered. It should be used for simple socket events which don't need authorization.
```javascript
import Server from 'reacting-squirrel/server';

const app = new Server();

// Frontend app can emit 'test' with some data. The event's listener emits the data back.
app.registerSocketEvent('test', (socket, data, next) => next(null, data));

app.start();
```
### Socket classes register
The socket classes can handle multiple socket events prefixed by the class name. After the registration of the socket class socket events are automatically registered to the server app.
```javascript
// ./socket.user.js
import { SocketClass } from 'reacting-squirrel/server';

export default class User extends SocketClass {

	// This method can be called from the client as 'user.load'
	// The approach with 'next' callback is not recommended.
    load(socket, data, next) {
        // sends the authorized user data after the 'user.load' socket request
        next(null, socket.getSession().getUser());
    }

	// This method can be called from the client as 'user.updateUser'
	async updateUser(socket, data) {
		await doSomeAsyncOperation();
		return socket.getSession().getUser().getUser();
	}
}

// ./index.js
import Server from 'reacting-squirrel/server';

import UserSocket from './socket.user';

import UserStore from './user-store';

const app = new Server({
    auth: (session, next) => {
        UserStore.load(session.id, (err, user) => {
            if (err) {
                next(err);
                return;
            }
            session.setUser(user);
            next();
        });
    }
});

// Registeres the socket class
app.registerSocketClass(UserSocket);

app.start();
```
### Components register
The module can register custom components which are rendered in custom DOM element in the layout. 
```javascript
import Server from 'reacting-squirrel/server';

const app = new Server();

// Frontend app tries to render component located at {config.appDir}/test to the DOM element with id 'test'
app.registerComponent('test', 'test');

app.start();
```
### RSConfig
RSConfig file can contain list of routes, list of components and the directory with the socket classes. By default the file `rsconfig.json` is searched in the `process.cwd()` directory. If the file doesn't exist nothing happens. The path to the file can by changed with config.rsConfig option.  

The schema for the file is located in `[pathToModule]/schemas/rsconfig.schema.json`.

```json
// rsconfig.json
{
	"$schema": "./node_modules/reacting-squirrel/schemas/rsconfig.schema.json",
    "routes": [
        {
            "route": "/",
            "component": "home",
            "title": "Home",
            "requiredAuth": false,
            "method": "GET"
        }
    ],
    "components": [
        {
            "id": "test",
            "component": "test"
        }
    ],
	"socketClassDir": "./dist/network/socket",
	"errorPage": "error-page"
}
```
Additional app config can be also be defined in the rsconfig.

#### ENV vars
Values in rsconfig that have `$env:[value]|[defaultValue]` prefix are replaced with `process.env[value]` in the server start.  
If the env var is not in the process the default value is used (if specified).

### Texts
In the startup process, the `res` directory is created in `app` directory. In that directory is created default text file `text.json`. The content of the text file is used as default dictionary using [texting-squirrel](https://www.npmjs.com/package/texting-squirrel) module.
#### Accessing text from the component
All components have `getText` method to access the text from the dictionary.
```javascript
import { Component } from 'reacting-squirrel';

export default class CustomComponent extends Component {

    render() {
        return <h1>{this.getText('title')}</h1>;
    }
}

```
#### Using Text component
The module contains a text component to handle dictionary directly from the JSX code.

```javascript
import { Component, Text } from 'reacting-squirrel';

export default class CustomComponent extends Component {

    render() {
        return <Text dictionaryKey="title" tag="h1" />
    }
}

```
#### Using texts on the server side (experimental)
The instance of the server has a property `Text` which is just `texting-squirrel` module with registered directories.  
Server option `locale` defines supported locales and dictionary text files are created (if not exist) and registered in the server startup.

##### Page titles
If the page title starts with the `:` the key (without the first character) is searched in the locale dictionary.

#### Translations
The dictionaries can be registered for different languages. The accepted languages should be set with the `locale.accepted` option on the server and dictionaries will be created in the `res` directory. The default language is taken from the browser (the dictionary must exist). 
##### Changing the locale
The locale can be changed on the client side using `Application.setLocale` method and it's handled on the server side (still experimental) with cookie `rs~locale`.  
<b>NOTE:</b> In case of setting locale to the default dictionary it has to be the `default` keyword instead of the value.

## Socket communication
The module is using socket.io as a default communication protocol. The payload is chunked (default 10kB per chunk) and sent to the server. 
### Uploading files
File upload can be diffucult over websocket. Without chunks big files disconnects the socket because of the `pingTimeout`. The file is sent to the server in chunks and converted to buffer on the server side.
```javascript
const file = 'get somehow a File instance';
Socket.emit('file.upload', undefined, { file }, (progress) => console.log(progress));
```
#### Limitations
The server limits the message size. If the size is bigger than allowed limit, the socket is disconnected. The module has 100MB cap for the message size.

## Error handling
### Server
Route errors are handled in error middleware and sent to `error.handler` from app config. If no handler is defined error page is rendered.
### App
#### Webpack watcher
In `DEV` mode all code error is checked with webpack watcher. All errors (if any) are logged in stdout and sent to client with `webpack.stats` event.
#### Component
All components are wrapped in `ErrorHandler` that can be also overridden in app config with `componentErrorHandler`. 
#### Application
The application has logging methods (`log[Error|Warning|Info]`) that emits `log` event. All client logging must be done manually.
##### Example
```javascript
Application.addListener('log', ({ severity, component, message, args }) => {
	if (severity === 'error' && !component) {
		// Log the error in logging service
	}
});
```

## Decorators
### SocketClass
Decorators are designed for the the `SocketClass` methods.
#### broadcast
Data returned in the method are broadcasted to the client side.
#### requireAuth
Before the method execution is checked the logged user in the session. If it's not the error is thrown.
#### notSocketMethod
The method is not registered as socket method and cannot be called from the client side.
### SocketRequest
#### castResponse
The response is casted to defined types using [runtime-type](https://www.npmjs.com/package/runtime-type) module.

## Plugins
The plugins can be registered with `Server.registerPlugin` method. The plugin should extent `Plugin` class in the module.
Plugin can:
- Inject script to the entry file.
- Add socket events.
- Add socket classes.
- Register route callbacks.
- Register before execution functions.
- Register scripts.
- Register styles.
- Register styles to merge.
- Add middleware.
- Register pages.
- Register components.
### Pages
The pages can be register using `getPages` method. The path to the component can be absolute so it must not be in the `app` directory. 
### Components
The components can be register using `getComponents` method. The path to the component can be also absolute. 

## Docs
Checkout the documentation [here](https://zabkwak.github.io/reacting-squirrel/).

### Deprecated
[https://trello.com/b/FepP7DPC/reacting-squirrel](https://trello.com/b/FepP7DPC/reacting-squirrel)

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