Skip to content

Commit 93a4c03

Browse files
committedMar 27, 2023
Add Node.js client code
1 parent a00c98e commit 93a4c03

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
 

‎backend/package.json

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"dependencies": {
77
"dotenv": "^6.2.0",
88
"jsonwebtoken": "^8.5.1",
9+
"eventsource": "^2.0.2",
910
"request": "^2.88.0",
1011
"request-promise-native": "^1.0.5"
1112
},

‎backend/subscriber.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// This is a simple example of a Mercure-Hub client in Node.js.
2+
// This is not usual to connect from Node.js and you shouldn't probably using this code but use the example in "frontend" which will show you how to connect from a browser.
3+
const EventSource = require('eventsource');
4+
5+
const endpoint = '<XXXXXX>.stackhero-network.com'; // PUT YOUR SERVER URL
6+
7+
// Caution: this is not your subscriber JWT defined in Stackhero's console.
8+
// To get you subscriber JWS (with a final S, not T like in JWT), you have to generate it on the server side.
9+
// An example is available in the `backend/subscriberJwsGenerator.js`
10+
const subscriberJws = ''; // PUT YOUR SUBSCRIBER JWS
11+
12+
13+
const url = new URL('https://' + endpoint + '/.well-known/mercure');
14+
15+
// Add topic to listen to
16+
url.searchParams.append('topic', `https://${endpoint}` + '/books/1');
17+
18+
const eventSource = new EventSource(
19+
url.toString(),
20+
{
21+
headers: {
22+
Authorization: `Bearer ${subscriberJws}`
23+
}
24+
}
25+
);
26+
27+
eventSource.onmessage = e => console.log(e);

0 commit comments

Comments
 (0)