SkillAgentSearch skills...

Primus

:zap: Primus, the creator god of the transformers & an abstraction layer for real-time to prevent module lock-in.

Install / Use

/learn @primus/Primus
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Primus

Version npmCICoverage Status

Primus, the creator god of transformers but now also known as universal wrapper for real-time frameworks. There are a lot of real-time frameworks available for Node.js and they all have different opinions on how real-time should be done. Primus provides a common low level interface to communicate in real-time using various real-time frameworks.

Advantages

  1. Effortless switching between real-time frameworks by changing one single line of code. No more API rewrites needed when your project requirements change, the framework gets abandoned or simply breaks down.
  2. Built-in reconnect, it just works. The reconnect is controlled by a randomised exponential back-off algorithm to reduce server stress.
  3. Offline detection, Primus is smart enough to detect when users drop their internet connection (switching WIFI points/cell towers for example) and reconnects when they are back online.
  4. Automatically encodes and decodes messages using custom parsers. Can be easily switched for binary encoding for example.
  5. A clean, stream-compatible interface for the client and server. You can just stream#pipe data around. In addition to that, the client works on Node.js as well, write once, run it everywhere.
  6. Fixes various of bugs in the supported frameworks and additional stability patches to improve real-time communication.
  7. Comes with an amazing plugin interface to keep the core library as fast and lean as possible while still allowing the server and the client to be extended.
  8. Last but not least, Primus is built with love, passion and dedication to the real-time web.

Installation

Primus is released on npm and can be installed using:

npm install primus --save

Before Starting

If you deploy your application behind a reverse proxy (Nginx, HAProxy, etc.) you might need to add WebSocket specific settings to its configuration files. If you intend to use WebSockets, please ensure that these settings have been added. There are some example configuration files available in the observing/balancerbattle repository.

Table of Contents

Getting started

Primus doesn't ship with real-time frameworks as dependencies, it assumes that you as user add them yourself as a dependency. This is done to keep the module as lightweight as possible. This works because require in will walk through your directories searching for node_module folders that have these matching dependencies.

Primus needs to be "attached" to a HTTP compatible server. These includes the built-in http and https servers but also the spdy module as it has the same API as node servers. Creating a new Primus instance is relatively straightforward:

'use strict';

var Primus = require('primus')
  , http = require('http');

var server = http.createServer(/* request handler */)
  , primus = new Primus(server, {/* options */});

The following options can be provided:

Name | Description | Default --------------------|-------------------------------------------|--------------- authorization | Authorization handler | null pathname | The URL namespace that Primus can own | /primus parser | Message encoder for all communication | JSON transformer | The transformer we should use internally | websockets plugin | The plugins that should be applied | {} pingInterval | Interval at which heartbeats are sent | 30000 global | Set a custom client class / global name | Primus compression | Use permessage-deflate / HTTP compression | false maxLength | Maximum allowed packet size, in bytes | 10485760 transport | Transformer specific configuration | {} idGenerator | Custom spark id generator function | undefined origins | cors List of origins | * methods | cors List of accepted HTTP methods | GET,HEAD,PUT,POST,DELETE,OPTIONS credentials | cors Allow sending of credentials | true maxAge | cors Cache duration of CORS preflight | 30 days headers | cors Allowed headers | false exposed | cors Headers exposed to the client | false

The options that are prefixed with cors are supplied to our access-control module which handles HTTP Access Control (CORS), so for a more detailed explanation of these options check it out.

The transport option allows you to use any configuration option supported by the underlying real-time framework. Its use is discouraged as these options are framework specific and no longer work if you change transformer. Our advise is to use it only if you know what you are doing and if you need fine-grained control over the real-time framework. Please also keep in mind that some of these options are overriden by Primus.

The pingInterval option specifies the interval at which heartbeats are transmitted. It is possible to completely disable the heartbeats by setting the value of the pingInterval option to false.

The idGenerator option can be used to define a function which will be called to set each spark.id. The generator function should return a unique string each time it is invoked. If idGenerator is not defined, Primus will try to use ids provided by the transformer. If the transformer does not provide ids, Primus will use nanoid to generate Spark ids.

If you don't have a pre-existing server where you want or can attach your Primus server to you can also use the Primus.createServer convenience method. The createServer method will automatically:

  • Setup a HTTP, HTTPS or SPDY server for you on the given port number.
  • Setup your Primus server with the given configuration.
  • Listen on the HTTP, HTTPS, SPDY server.
  • Attach a primus.on('connection') listener.
  • Return the created Primus instance.
Primus.createServer(function connection(spark) {

}, { port: 8080, transformer: 'websockets' });

In the above example we automatically create a HTTP server which will listen on port 8080, a primus instance with the websockets transformer and start listening for incoming connections. The supplied function in the Primus.createServer method is optional. You can just listen for incoming connections your self using the returned Primus instance. If you want to listen to a HTTPS or SPDY server, which is recommended, you can directly pass the SPDY and HTTPS certs/keys/pfx files in the options object:

var primus = Primus.createServer({
  port: 443,
  root: '/folder/with/https/cert/files',
  cert: 'myfilename.cert',
  key: 'myfilename.cert',
  ca: 'myfilename.ca',
  pfx: 'filename.pfx',
  passphrase: 'my super sweet password'
});

primus.on('connection', function (spark) {
  spark.write('hello connnection');
});

Primus.createServer returns a warning when it starts a HTTP server. The warning advises you to use a HTTPS server and can be disabled setting the option iknowhttpsisbetter to true.

Client library

As most libraries come with their own client-side framework for making the connection we've also created a small wrapper for this. The library can be retrieved using:

primus.library();

Which returns the client-side library as a string (which can then be minified or even have more code added to it). It does not come pre-minified as that is out of the scope of this project. You can store this on a CDN or on your static server. Do whatever you want with it, but remember to regenerate it every time you change Primus server options. This is important because some properties of the client are set using the server configuration. For example if you cha

Related Skills

View on GitHub
GitHub Stars4.5k
CategoryDevelopment
Updated7d ago
Forks269

Languages

JavaScript

Security Score

100/100

Audited on Mar 17, 2026

No findings