{"title":"JavaScript Client","description":"","section":"guides/websockets","version":"v1.5","path":"guides/websockets/javascript-client","canonical_url":"https://amberframework.org/docs/v1.5/guides/websockets/javascript-client","markdown_url":"https://amberframework.org/docs/v1.5/guides/websockets/javascript-client.md","inherited":true,"content_markdown":"# JavaScript Client\n\n## Example Usage\n\nFor use with web based applications, a JavaScript library \\(`amber.js`\\) is included.\n\n### Create a single connection to the server\n\nThe first step in instantiating a socket connection with the server through JavaScript, is by using the library \nprovided by Amber. Place the route that was created on the server side in the `routes.cr` as the endpoint to which\nthe front end will connect to.\n\n```javascript\nlet socket = new Amber.Socket('/chat')\nsocket.connect() # returns a promise\n  .then(() => {})\n```\n\n### Join a channel\n\nAfter the promise passes, include the following code in the function from within the `.then` that will be triggered.\n\n```javascript\nlet channel = socket.channel('chat_room:123')\nchannel.join()\n```\n\nIn the above example, `chat_room` is the channel that was created on line 2 of the `ChatSocket` struct. You can dynamically\ncreate separate channels within the prefix of `chat_room:` by appending any character after the colon. This allows for the \ncreation of chatrooms that will allow different clients to connect to it.\n\n### Send events / messages\n\nWhen you need to send a message after a user submits the form that includes their message, you'll want to push it \nout to the server for it to be rebroadcast to all connected clients.\n\n```javascript\nchannel.push('message_new', { message: 'amber websockets are the bomb diggity!' })\n```\n\n### Subscribe to events / messages\n\nAfter a message is sent, you'll need to have a listener that listens to a specific subject from within the socket channel.\nFor example, below the subject of `message_new` is being listened to from within the `chat_room:123` channel. You may also \nhave a listener on the subject of `user_join` to notify active connections of a new user to the chatroom.\n\n```javascript\nchannel.on('message_new', (message) => {\n  // handle new message here\n})\n\nchannel.on('user_join', (message) => {})\n```"}