Mercure Provider - Real-time Made Easy

Overview

@setten/mercure

Download Version License

@setten/mercure is a Mercure client for AdonisJS.

Mercure allows you to use Server Sent Events to push data to your clients using Http.

Note

You must have a Mercure Hub instance running.


Getting Started

This package is available in the npm registry.

npm install @setten/mercure

Next, configure the package by running the following command.

node ace configure @setten/mercure

and... Voilà!

Configuration

You have to configure the package before you can use it. The configuration is stored in the config/mercure.ts file.

  • endpoint: The endpoint of the Mercure Hub.
  • adminToken: The JWT created to authenticate as an admin of the Mercure Hub.
  • jwt.alg: The algorithm used to sign the JWT - should correlate to Mercure Hub configuration.
  • jwt.secret: The secret used to sign the JWT - should correlate to Mercure Hub configuration.

Note that the adminToken must be generated using the same alg and secret used in the Mercure Hub with the following payload.

{
  "mercure": {
    "publish": [
      "*"
    ]
  }
}

For example, given the secret of ChangeMe and the algorithm of HS256, the JWT would be:

eyJhbGciOiJIUzI1NiJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.mx2ROlYlE1rp7udoDy-WCdnpLdPuKWzDxoBJXGMK4OE

Usage

The Mercure Provider gives you access to two classes.

  • Update: This class is used to publish updates to the hub.
  • Token: This class is used to generate a token for authentication.

You can easily send an update to the hub using the Update.send method.

import { Update } from '@ioc:Setten/Mercure';

Update.send('/users/1', { ... });

The send method takes three arguments.

  • topic: The topic to publish the update to.
  • data: The data to publish.
  • isPrivate: Whether the update is private or not.

More information on the topic and data arguments can be found in the Mercure documentation.

Frontend

The frontend can listen to changes using the standard EventSource web interface.

const url = new URL(/*  Mercure Endpoint */)
url.searchParams.append('topic', '/users/1')

const eventSource = new EventSource(url)
eventSource.onmessage = (event) => {
  console.log(event.data)
}

More information on the topic can be found in the Mercure documentation.

Authentication

You may want to send private messages. To do so, you need to set the update as private using the third argument of the Update.send method, and authenticate the client using a JWT stored in a cookie.

You can generate the JWT using the Token class.

import { Token } from '@ioc:Setten/Mercure';

// Generating the token allowing the user to listen on private events
// send to `/users/1`.
const token = await Token.generate({
  subscribe: ['/users/1'],
})

// Adding the token in a cookie name `mercureAuthorization`.
response.append(
  'set-cookie',
  `mercureAuthorization=${token}; Domain=.setten.io; Path=/.well-known/mercure; HttpOnly`
)

The cookie must be named mercureAuthorization and must be not encoded by AdonisJS (you cannot use response.cookie() at the moment for that reason).

Note that the Mercure Hub must run on the same domain as the client since cookies cannot be shared cross-domain.

Once done, you have to change your client's connection to use cookies.

const eventSource = new EventSource(url, { withCredentials: true })

More information on the topic can be found in the Mercure documentation.

You might also like...

Use real-time computing technology and web technology to build a big data Kanban l to solve the problem. Among them, practical technologies include MySQL, Kafka, Flink, Redis, Flask and Echarts

Use real-time computing technology and web technology to build a big data Kanban l to solve the problem. Among them, practical technologies include MySQL, Kafka, Flink, Redis, Flask and Echarts

实时计算(English Version) 运用实时计算技术、Web 技术构建一个大数据看板来解决问题。其中实用技术包括Mysql、Kafka、Flink、Redis、Flask和Echarts 目录 1.问题需求 2.方案分析 3.安装环境 4.环境启动命令和运行代码的方法 5.代码目录结构说明

Jan 8, 2022

A card for Home Assistant Lovelace for exploring the history of your entities interactively and in real time.

A card for Home Assistant Lovelace for exploring the history of your entities interactively and in real time.

History explorer card This is a custom history card for Home Assistant. This card offers a highly interactive and configurable way to view the history

Dec 31, 2022

Prototype of real-time comments and a proposal of how to make it "production-ready".

Prototype of real-time comments and a proposal of how to make it

Real-time comments prototype Simple demonstration of real-time commenting. Installation After forking it, run npm install, then you need two environme

Jan 16, 2022

Apollo - a JavaScript library to get real-time economic declarations such as inflation rates

Apollo is a JavaScript library to get real-time economic declarations such as inflation rates, unemployment rates or interest rates reported by governments or other entities.

Dec 10, 2022

Real-time event collaborating

Smartlist Collaborate Collaborate on your events in real-time! An product by Smartlist 🧪 This product is still in development, and some features mig

Mar 17, 2022

Clubhouse is a new type of social network based on voice—where people around the world come together to talk, listen and learn from each other in real-time.

Clubhouse is a new type of social network based on voice—where people around the world come together to talk, listen and learn from each other in real-time.

Awesome Clubhouse The clubhouse is a new type of social network based on voice—where people around the world come together to talk, listen and learn f

Nov 9, 2022

Cryptostat is a Node.js based CLI that gets you the real-time stats of your favorite cryptocurrency.

Cryptostat-CLI Cryptostat is a Node.js based CLI that gets you the real-time stats of your favorite cryptocurrency. Installation Use the npm package m

Dec 15, 2022

A serverless, real-time, wordle-inspired, multiplayer game.

A serverless, real-time, wordle-inspired, multiplayer game.

fivebysix.com A multiplayer, worlde-inspired web app. Demo Technologies 100% TypeScript (including IAC via CDK) Vite React / Redux AWS AppSync Dynamo

Jan 1, 2023

A Kubernetes monitoring tool to visualize large-scale activity and real-time comprehensive metrics within your cluster.

A Kubernetes monitoring tool to visualize large-scale activity and real-time comprehensive metrics within your cluster.

Armada A light-weight Kubernetes health monitoring tool. Summary Armada is an open-source tool for monitoring the health of your Kubernetes cluster. I

Nov 2, 2022
Releases(0.1.1)
Owner
Setten
Powering Terra with fast and reliable infrastructure
Setten
Open source project that make it easy to sync your calendars in real time.

Syncit 2.0 - We make it easy to sync your calendars in real time. This is an Open source project! Installation Run yarn in order to install all depend

Tikal Knowledge, Ltd. 6 Dec 15, 2022
Use Matrix as a backend for local-first applications with the Matrix-CRDT Yjs provider.

Matrix CRDT Matrix-CRDT enables you to use Matrix as a backend for distributed, real-time collaborative web applications that sync automatically. The

Yousef 604 Jan 7, 2023
Web3.js provider to interact with the VeChain Thor protocol

web3-providers-connex Web3.js provider implemented using Connex.js. It makes it possible to use web3.js and ethers.js to interact with VeChain Thor pr

null 13 Dec 26, 2022
🌱 Ethereum provider solution for Dapp&Wallets, 🏷 If you have good suggestions, please submit issues

English | 简体中文 | 日本 ETH Wallet Modal An Ethereum Provider Solution for Integrated Wallets and Dapps ⚠️ Notice If you need to reduce unnecessary import

Dan Xu 35 Dec 19, 2022
☁️ Application using Node.js, AdonisJs, Adonis ACL, Adonis Kue Provider, Adonis Mail, Adonis Lucid Slugify, Adonis Validator, AdonisJs Redis, ESLint and pg

Node.js - SaaS ☁️ Application using Node.js, AdonisJs, Adonis ACL, Adonis Kue Provider, Adonis Mail, Adonis Lucid Slugify, Adonis Validator, AdonisJs

null 4 Aug 19, 2022
Cross provider map drawing library, supporting Mapbox, Google Maps and Leaflet out the box

Terra Draw Frictionless map drawing across mapping providers. TerraDraw centralises map drawing logic and provides a host of out the box drawing modes

James Milner 106 Dec 31, 2022
📊🌍 Super small, light, privacy-focused, self-hostable web statistics provider

femtostats Update: It turns out Fathom Lite does everything I wanted to do except custom events for free, so I'm going to stop working on this for now

Ian Langworth ☠ 12 Nov 17, 2022
A "Basic-to-Lisp" compiler. But Basic is not real Basic, and Lisp is not real Lisp.

Basic2Lisp A "Basic-to-Lisp" compiler. But Basic is not real Basic, and Lisp is not real Lisp. Syntax Print-Sth Put some-value to standard output. PRI

Hana Yabuki 5 Jul 10, 2022
🚀AI拟声: 5秒内克隆您的声音并生成任意语音内容 Clone a voice in 5 seconds to generate arbitrary speech in real-time

English | 中文 Features ?? Chinese supported mandarin and tested with multiple datasets: aidatatang_200zh, magicdata, aishell3, and etc. ?? PyTorch work

Vega 25.6k Dec 29, 2022
A pure JavaScript Web Page to retrieve real-time OTP through a web page and generate/scan QR codes.

2FA-Solver A pure JavaScript Web Page to retrieve real-time OTP through a web page and generate/scan QR codes. It can be used as an offline web page b

Yuthan K 8 Dec 7, 2022