Outsmartly
Search…
MessageBus
The MessageBus is used to send and receive messages in a decoupled way, both client-side and edge-side.

Usage

Client-side

Outsmartly provides a React Hook to gain access to the MessageBus from anywhere in your UI components:
1
import { useMessageBus } from '@outsmartly/message-bus';
2
3
export function Home() {
4
const messageBus = useMessageBus();
5
const [clickCount, setClickCount] = useState(0);
6
7
useEffect(() => {
8
// Passing data as a second argument is optional
9
messageBus.emit('YourCustomMessages.HOME_COMPONENT_MOUNTED');
10
}, []);
11
12
return (
13
<button
14
onClick={() => {
15
setClickCount((clickCount) => {
16
const newClickCount = clickCount + 1;
17
const data = {
18
count: newClickCount,
19
};
20
messageBus.emit('YourCustomMessages.BUTTON_CLICKED', data);
21
22
return newClickCount;
23
});
24
}}
25
>
26
You have clicked me {clickCount} times
27
</button>
28
);
29
}
Copied!

Edge-side

At the edge, you can gain access to the MessageBus from any OutsmartlyEvent passed to middleware, interceptors, or overrides:
1
export default {
2
host: 'example.outsmartly.app',
3
environments: [
4
{
5
name: 'production',
6
origin: 'https://my-example-website.vercel.app',
7
},
8
],
9
// All routes will have this middleware applied
10
middleware: [
11
async function firstMiddleware(event, next) {
12
event.messageBus.once('YourCustomMessages.COMPONENT_OVERRIDDEN', (message) => {
13
event.log('Message received!', message);
14
});
15
return await next();
16
},
17
],
18
routes: [
19
{
20
path: '/some-base-path/*',
21
overrides: [
22
{
23
component: 'ExampleComponent',
24
async getOverrideProps(event) {
25
const headline = 'hello, world';
26
// Perhaps you want to notify some middleware that
27
// something happened
28
event.messageBus.emit('YourCustomMessages.COMPONENT_OVERRIDDEN', {
29
headline,
30
});
31
32
return {
33
props: {
34
headline,
35
},
36
};
37
},
38
},
39
],
40
},
41
],
42
};
Copied!
When listening, it's more common to want to set up a global listener once, when the edge starts up. This can be done using the plugin interface:
1
export function myCustomPlugin(options) {
2
return {
3
name: '@yourcompany/outsmartly-plugin-does-something',
4
setup({ config, messageBus }) {
5
// Listening for messages, globally
6
messageBus.on('YourCustomMessages.COMPONENT_OVERRIDDEN', async (message) => {
7
// do something with it, such as call fetch()
8
});
9
},
10
};
11
}
Copied!
Copy link