Quickstart: WebJS
Build a real-time web app in 5 minutes.
Prerequisites
- Modern browser with ES6+ support
- RelayX account with API key and secret
Install
npm install relayx-webjs
Or use via CDN:
<script type="module">
import { Realtime } from 'https://esm.sh/relayx-webjs';
</script>
HTML Example
<!DOCTYPE html>
<html>
<head>
<title>RelayX WebJS Demo</title>
</head>
<body>
<div id="messages"></div>
<input type="text" id="input" placeholder="Type a message..." />
<button id="send">Send</button>
<script type="module">
import { Realtime } from 'https://esm.sh/relayx-webjs';
const client = new Realtime({
api_key: 'your-api-key',
secret: 'your-secret'
});
await client.init();
await client.connect();
// Subscribe to messages
await client.on('chat.room1', (msg) => {
const div = document.getElementById('messages');
div.innerHTML += ``;
});
// Send message on button click
document.getElementById('send').onclick = async () => {
const input = document.getElementById('input');
await client.publish('chat.room1', {
user: 'web-user',
text: input.value
});
input.value = '';
};
</script>
</body>
</html>
React Example
import { useEffect, useState, useRef } from 'react';
import { Realtime } from 'relayx-webjs';
function Chat() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const clientRef = useRef(null);
useEffect(() => {
const connect = async () => {
const client = new Realtime({
api_key: 'your-api-key',
secret: 'your-secret'
});
await client.init();
await client.connect();
// Subscribe to messages
await client.on('chat.room1', (msg) => {
setMessages(prev => [...prev, {
user: msg.data.user,
text: msg.data.text
}]);
});
clientRef.current = client;
};
connect();
return () => {
clientRef.current?.close();
};
}, []);
const sendMessage = async () => {
if (!input.trim() || !clientRef.current) return;
await clientRef.current.publish('chat.room1', {
user: 'react-user',
text: input
});
setInput('');
};
return (
<div>
<div>
{messages.map((msg, i) => (
<p key={i}>{msg.user}: {msg.text}</p>
))}
</div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message..."
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}
export default Chat;
Run It
HTML: Save the file and open in your browser.
React: Import the component and use it in your app.
Messages will appear in real-time for all connected clients.