<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Booker on Medium]]></title>
        <description><![CDATA[Stories by Alex Booker on Medium]]></description>
        <link>https://medium.com/@bookercodes?source=rss-9f4bc2e3bf30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-txlbTRRm6AhTRTsfP_bWA.jpeg</url>
            <title>Stories by Alex Booker on Medium</title>
            <link>https://medium.com/@bookercodes?source=rss-9f4bc2e3bf30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:44:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bookercodes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebSocket security: How to prevent 9 common vulnerabilities]]></title>
            <link>https://medium.com/ably-realtime/websocket-security-how-to-prevent-9-common-vulnerabilities-fdb32027df85?source=rss-9f4bc2e3bf30------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdb32027df85</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Alex Booker]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 14:50:08 GMT</pubDate>
            <atom:updated>2023-11-28T14:50:08.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJPDFCnDRYmQ5UuLg0E8bg.png" /></figure><p>The <a href="https://hubs.la/Q02b9T9L0">WebSocket</a> communication protocol is used for a range of purposes, including transmitting sensitive information and running actions with elevated privileges. This makes it an increasingly attractive attack vector for malicious actors.</p><p>The best defense against common WebSocket vulnerabilities is to be aware of them and implement the proper controls to reduce exposure.</p><p>In this post, we’ll look at the most common WebSocket security vulnerabilities and how to prevent them through a combination of modern security approaches and testing tools.</p><h3>Broken authentication</h3><p>WebSockets don’t prescribe any particular way for servers to authenticate clients, putting the responsibility on us, the developers, to devise and implement a mechanism to confirm our user’s identity and securely manage their session.</p><p>The lack of a standard way to authenticate incoming WebSocket connections leaves room to make critical security mistakes.</p><h4>Impact of broken authentication</h4><p>The impact of a WebSocket authentication vulnerability is severe. Once an attacker has bypassed authentication, they have access to all the data and functionality that the compromised account has.</p><h4>Prevention of broken authentication</h4><p>Preventing broken authentication involves authenticating the <a href="https://hubs.la/Q02b9VDr0">handshake</a> before establishing the WebSocket connection, either with a cookie or token</p><p>When using cookie authentication, the browser automatically sends cookies to the server with the WebSocket handshake. Just beware of Cross-Site WebSocket Hijacking (more on that in the section below).</p><p>Token authentication is a bit more tricky.</p><p>Browsers don’t allow arbitrary headers with the WebSocket connection request, meaning you need to find another medium to send the token to the server.</p><p>It can be tempting to send the authentication token in the query string, however, this should be approached with extreme caution. Query strings form part of the URL, which is plaintext and may appear in logs and be used in an attack.</p><p>One possible solution is to use your long-lived authentication token to make a HTTP request for an ephemeral one-time token from your authentication service. Send this one-time token with the WebSocket connection in the query string then discontinue it on the server-side. This way, if the token is logged somehow or shared accidentally, it’s no longer usable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*lE2Wm_UIggg6WpLzWEVCeQ.png" /></figure><p>If you’d like to learn more about how to implement a token-based authentication flow, Senior Software Engineer Jimmie Potts has a <a href="https://nuvalence.io/insights/websocket-token-based-authentication/">concise post</a> on the subject.</p><h3>Broken access control</h3><p>In the previous section, we looked at authentication, which confirms the client is who they say they are. Access control, on the other hand, involves granting or denying access to specific resources or actions based on the authenticated identity.</p><p>Suppose Lord Voldemort authenticates with a password. Surely he shouldn’t be authorized to subscribe to Harry Potter and the gang’s WebSocket channel.</p><h4>Impact of broken access control</h4><p>Broken access control is <a href="https://owasp.org/Top10/A01_2021-Broken_Access_Control/">the most commonly encountered</a> and often a critical security vulnerability. It happens when a user can in fact access some resource or perform some action that they are not supposed to be able to access. Failures typically lead to unauthorized information disclosure, modification, or destruction of all data, or performing a business function outside the user’s limits.</p><h4>Prevention of broken access control</h4><ul><li>Unless a resource is intended to be publicly available, deny access by default.</li><li>Explicitly declare the access that is allowed for each resource.</li><li>Thoroughly audit and test access controls to ensure they’re working as designed.</li></ul><p>While the design and management of access control is a complex and dynamic problem, most issues can be solved with the above best practices.</p><p>Many developers rely on obfuscation for WebSocket security, but security through obscurity is not security at all.</p><p>WebSocket URLs are normally tucked away in code and the paths themselves often contain identifiers that seem random and impossible to predict, creating a false sense of security.</p><p>Today, it’s trivial for a malicious actor to use a WebSocket traffic inspectors like <a href="https://portswigger.net/burp/documentation/desktop/tutorials/testing-websockets">Burp</a> or even <a href="https://blittle.github.io/chrome-dev-tools/network/websockets.html">Chrome’s WebSocket inspector</a> to recognise and exploit a pattern, making it more important than ever to double-check every resource is behind an access rule.</p><h3>Insecure Direct Object References (IDOR)</h3><p>Insecure Direct Object References (IDOR) is a subcategory of access control vulnerabilities. It’s one of the most common access control weaknesses, so we wanted to call it out directly.</p><p>An IDOR vulnerability allows a malicious actor to exploit a WebSocket application by manipulating a “direct object reference” in the WebSocket request, such as a file name or query parameter.</p><p>In an IDOR attack, the request succeeds due to missing access control checks, which fail to verify whether a user should be allowed to access specific data.</p><p>To give an example — in a post entitled <a href="https://footstep.ninja/posts/idor-via-websockets/">IDOR via WebSockets</a>, Security Engineer Shuaib Oladigbolu describes how they managed to comment as another user simply by tampering with the authorID parameter in the WebSocket comment request — sometimes it’s <em>that</em> easy for an attacker to cause problems.</p><h4>Impact of IDOR</h4><p>IDOR vulnerabilities are among the most commonly-reported and are trivial to execute. They can result in unauthorized data exposure, leakage of personally identifiable information, and even create the potential for data manipulation or deletion.</p><ul><li>Implement access control checks for each object that users try to access.</li><li>Use complex identifiers like GUIDs instead of predictable incremental IDs as a defense-in-depth measure (but remember that access control is crucial even with these identifiers).</li></ul><p>For more information on IDOR, The Open Web Application Security Project (OWASP) has a handy <a href="https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html">IDOR prevention cheat sheet</a> — they are a non-profit dedicated to application security and have many educational resources dedicated to the security subjects described on this page.</p><h3>Injection attacks (SQL Injection, XSS, etc.)</h3><p>Injection is an attacker’s attempt to send data to an application, with the intention of exploiting vulnerabilities in the application’s processing. It’s one of the most common vulnerabilities with HTTP, and it applies to WebSockets as well, which are often used to transmit sensitive information and run actions with elevated privileges.</p><p>Common types of injection attacks include SQL injection, where attackers manipulate database queries, and cross-site scripting (XSS), where malicious scripts are injected into web pages viewed by other users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*9E9SErGPhcAiEoBjpAnRHg.png" /></figure><h4>Impact of injection attacks</h4><p>Injections are among the oldest and most dangerous attacks aimed at web applications in general and often arise in relation to WebSockets. They can lead to unauthorized access, data loss, denial of service, or even full system compromise if not properly mitigated.</p><h4>Prevention of injection attacks</h4><ul><li>Escape special characters in user inputs before incorporating them into queries or commands. This prevents them from being interpreted as code.</li><li>Treat all user-supplied input as untrusted. Validate all inputs on the server, and use an allowlist of acceptable inputs.</li><li>Examine and remove unwanted key characters, such as HTML tags that are deemed to be unsafe. Keep the safe data and remove any potentially unsafe characters.</li><li>Most instances of SQL injection can be prevented by using parameterized queries (also known as prepared statements) instead of string concatenation within the query.</li></ul><h3>Denial of Service (DoS)</h3><p>A Denial of Service (DoS) attack exploits vulnerabilities in your WebSocket implementation to crash the WebSocket server, making it inaccessible for your genuine users.</p><p>DoS attacks accomplish this by flooding the WebSocket server with traffic, or sending it information that causes a crash.</p><p>A DoS attack can be compared to a phone system being flooded with constant, non-stop calls from prank callers, jamming the lines and preventing legitimate callers from getting through, thus disrupting trade and losing the business money.</p><h4>Impact of DoS</h4><p>A successful DoS results in sluggish behavior or a total system crash. In both instances, the DoS attack deprives genuine users of the service they expected.</p><p>Though DoS attacks don’t typically result in unauthorized access to sensitive data, they can have a devastating impact on critical services, leading to direct financial loss and reputational damage.</p><h4>Prevention of DoS</h4><ul><li>Only allow authenticated users to open a WebSocket connection to prevent an attacker from flooding the WebSocket server with a large number of connection requests.</li><li>Ensure that your authentication mechanism is efficient so that DoS attacks using an invalid token can be quickly and cheaply refused.</li><li>Limit the number of requests that can be made to the WebSocket server from the same IP address over a specific time period.</li><li>Limit the number of connections allowed to the WebSocket server to circumvent a <a href="https://en.wikipedia.org/wiki/Resource_exhaustion_attack">resource exhaustion attack</a>.</li><li>Limit message size to a reasonable number to prevent message size attacks.</li></ul><p>DoS is not a specific attack but rather, a category of attacks. It would be outside the scope of this post to list every type of DoS however, I can highly recommend this post on <a href="https://cqr.company/web-vulnerabilities/denial-of-service-dos-via-websockets/">DoS via WebSockets by CQR</a>. They go into more detail about the above vulnerabilities and touch on a few others as well — for example, a pesky type of DoS called a WebSocket SYN Flood DoS.</p><h3>Distributed Denial of Service (DDoS)</h3><p>An additional type of DoS attack is the Distributed Denial of Service (DDoS) attacks.</p><p>DDoS attacks are more sophisticated and impactful than DoS attacks. They involve a coordinated effort from multiple sources — often compromised computers or devices forming a <a href="https://www.cloudflare.com/en-gb/learning/ddos/what-is-a-ddos-botnet/">botnet</a>. These sources simultaneously DoS the WebSocket server, making it even more challenging to defend against or mitigate.</p><h4>Impact of DDoS</h4><p>The most immediate and obvious impact of a DDoS is that your WebSocket server becomes overwhelmed and crashes. Suppose you’re building a <a href="https://hubs.la/Q02b9Yn10">chat experience</a> or <a href="https://hubs.la/Q02b9Ysd0">realtime collaborative experience</a> over WebSockets — if your WebSocket server is compromised, your entire website may as well be down. As your service becomes intermittent, users may lose faith in the experience and use another service altogether.</p><p>Since the attack is distributed, connections will likely come from all around the world. It will be hard to distinguish malicious and genuine connections due to the fact the botnet is composed of compromised systems that otherwise seem like genuine users. This makes a DDoS difficult to mitigate, resulting in intermittent disruptions to the service, often leading to reputational damage or straight up financial loss.</p><h4>Prevention of DDoS</h4><ul><li>Ensure your server is not vulnerable to DoS attacks (see section above).</li><li>Use a hosted WebSocket infrastructure like ours at <a href="https://hubs.la/Q02b9Z7s0">Ably </a>— our near-limitless scale means we can mitigate huge increases in traffic and defend against DDoS attacks — so you benefit from our scale as attacks have no effect on your own servers.</li><li>Proxy WebSocket connections through a content delivery network (CDN) that offer DDoS protection services that can detect and mitigate attacks in realtime.</li><li>Distribute WebSocket connections across multiple servers and data centers, making it harder for attackers to overwhelm a single server.</li><li>Have a plan in place for responding to a DDoS attack, including procedures for notifying stakeholders, isolating affected systems, and restoring services.</li></ul><p>For more information on how DDoS attacks work in the real world (and some guidance on how to mitigate them), CloudFlare has an <a href="https://www.cloudflare.com/en-gb/learning/ddos/what-is-a-ddos-attack/">in-depth post</a> on the subject. As it happens, CloudFlare is a CDN that offers DDoS protection. We use them at <a href="https://hubs.la/Q02b9Z7s0">Ably</a>.</p><h3>Cross-site WebSocket hijacking</h3><p>Cross-site WebSocket hijacking (also known as cross-origin WebSocket hijacking) is a security vulnerability that occurs when a malicious actor makes an unauthorized WebSocket connection to a different origin (site) than the one the user is currently on.</p><p>It arises when the WebSocket handshake request relies solely on HTTP cookies for authentication and isn’t relevant to you if you’re using token-based authentication.</p><p>Modern browsers ordinarily prevent <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">cross-origin resource sharing</a> (CORS) with a same-origin policy — while this applies to HTTP, counterintuitively, this does not apply to WebSocket connections, introducing a potentially surprising attack vector — unless you happen to know better. Good job you’re reading this post!</p><h4>Impact of cross-site WebSocket hijacking</h4><p>The implication of a cross-site WebSocket hijacking vulnerability depends on the scope of the attack and the hacker’s ability to leverage it.</p><p>At a minimum, a successful cross-site WebSocket hijacking attack enables malicious actors to abuse the established WebSocket connection to perform actions on the user’s behalf without their consent, potentially compromising their data or executing unintended actions. In many cases, the user won’t know they’ve been exploited until it’s too late, making it hard to react and defend their own data.</p><p>In a serious case of cross-site WebSocket hijacking, an attacker managed to <a href="https://snyk.io/blog/gitpod-remote-code-execution-vulnerability-websockets/">execute arbitrary JavaScript in a subdomain of the domain where the WebSocket communication was occurring</a></p><h4>Prevention of cross-site WebSocket hijacking</h4><ul><li>On the server side, validate the origin of incoming WebSocket connections. Only allow connections from trusted domains by checking the Origin header. Reject connections from unexpected or unauthorized origins.</li><li>Introduce a session-individual token (like a <a href="https://analyticssteps.com/blogs/all-you-need-know-about-csrf-tokens">CSRF token</a>) into the user’s session, which is then included in the WebSocket connection request sent to the server. This token is not known to malicious actors, making it difficult for them to forge requests.</li></ul><h3>Sensitive information disclosure over a network</h3><p>When transmitting sensitive information from one client to another over WebSockets, it must traverse the network. Malicious actors may exploit vulnerabilities to eavesdrop on the communication and steal personally identifiable information, such as account details, sensitive health data, private communications, and intellectual property.</p><p>Broadly speaking, this is known as a <a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">man-in-the-middle</a> attack and is the equivalent of a mailman opening your bank statement, writing down your account details, and then resealing the envelope and delivering it to your door — you might not know you’ve been hacked until it’s too late!</p><h4>Impact of sensitive information disclosure over a network</h4><p>The most immediate impact of a data leak is the violation of privacy for your users whose personal information has been exposed. At a minimum, users will lose faith in your ability to secure their information, leading to reputational damage and potentially loss of business as well. Depending on the nature of the breach, you may incur legal consequences and regulatory fines also.</p><p>The severity of the impact can vary based on the nature of the data exposed, and the motivation of the attackers. By intercepting or manipulating sensitive data, a malicious actor could steal intellectual property or even use data obtained from the breach to carry out a secondary attack, possibly causing wider operational disruptions.</p><h4>Prevention of sensitive information disclosure over a network</h4><ul><li>Always use the WebSocket Secure (wss) protocol instead of WebSocket (ws) to ensure data exchanged between the client and server is encrypted using SSL (TLS), making it difficult for attacks to intercept or decipher.</li><li>Ensure that the SSL certificate used for security the WebSocket connection is valid and issued by a trusted <a href="https://www.ssl.com/faqs/what-is-a-certificate-authority/">certificate authority</a>.</li><li>Regularly review the information sent over WebSockets to determine if a justifiable business need exists for transmitting each item present. Any items deemed unnecessary should be removed.</li></ul><h3>Using vulnerable or outdated WebSocket libraries</h3><p>When building with WebSockets, it’s common to use a library like <a href="https://hubs.la/Q02b9-lZ0">Socket.IO</a> to help you get up and running more quickly. These libraries tend to implement features you probably need — like automatic reconnection and message acknowledgements, as well as provide patterns for grouping connections by “rooms” or “topics” (<a href="https://hubs.la/Q02b9-zg0">Pub/Sub</a>) to make routing messages simple. They are very convenient!</p><p>However, before depending on a WebSocket library, do some research, and possibly some auditing.</p><p>Using a third-party WebSocket library can save time upfront, but it’s not without risk of introducing a vulnerability.</p><p>For example, according to Snyk, <a href="https://security.snyk.io/package/pip/websockets">websockets@9.1 introduces a DOS vulnerability before being patched in websockets@10</a>.</p><p>Here’s one more example of a <a href="https://security.snyk.io/vuln/SNYK-JS-WS-1296835">Regular Expression Denial of Service (ReDoS) vulnerability</a> introduced by the third-party ws package, which has since been solved.</p><p>Newer WebSocket libraries (or newer WebSocket library <em>versions</em>) may be more susceptible to vulnerabilities due to the fact they haven’t yet been battle-tested.</p><p>Additionally, watch out for older or unmaintained WebSocket libraries. Often, libraries with known vulnerabilities don’t get fixed due to a lack of maintainers.</p><h4>Impact of using vulnerable or outdated WebSocket libraries</h4><p>A vulnerable or outdated dependency may be susceptible to any of the common WebSocket vulnerabilities described in this post.</p><p>Malicious actors can exploit these vulnerabilities to gain access to sensitive data or take control of the application entirely.</p><h4>Prevention of using vulnerable or outdated WebSocket libraries</h4><ul><li>Use a commercial WebSocket-based API like <a href="https://hubs.la/Q02b9Z7s0">Ably</a>, which is actively maintained by a dedicated team, frequently undergoes penetration testing, and has a respectable <a href="https://hubs.la/Q02bb0qP0">vulnerability disclosure policy</a> (bug bounty).</li><li>Carefully inspect any open source dependency you add to your WebSocket server, as it may have an outstanding vulnerability.</li><li>Keep open source dependencies updated to ensure you have the latest security patches, reducing the risk of an exploit.</li><li>Optionally use an integration such as <a href="https://snyk.io/">Snyk</a> to continuously perform security scanning on your open source dependencies and detect potential vulnerabilities.</li></ul><h3>WebSocket security FAQ</h3><p>To wrap up this post, let’s cover some of the most commonly-asked questions about WebSocket security.</p><h3>Do WebSockets need SSL?</h3><p>Yes, it’s highly recommended to use SSL encryption with WebSockets (wss) to prevent eavesdropping and tampering by malicious actors. Using SSL also helps to maintain the integrity and confidentiality of the communication and prevents various security vulnerabilities that can arise when data is transmitted over an unencrypted connection.</p><h3>How secure are WebSockets?</h3><p>WebSockets are very secure when used over an encrypted SSL connection (wss) and you follow the WebSocket security best practices described in this post. Secure authentication, authorization, and input validation are crucial for preventing unauthorized access and attacks. Regular updates to libraries and ongoing testing contribute to overall security.</p><h3>How do you test WebSocket security?</h3><p>Comprehensive WebSocket security testing requires a deep understanding of the WebSocket protocol and practical experience in both manual and automated security testing techniques. Open tools like <a href="https://github.com/PalindromeLabs/STEWS">STEWS</a> can detect known WebSocket vulnerabilities while commercial security tools like <a href="https://portswigger.net/burp/documentation/desktop/tutorials/testing-websockets">Burp Suite</a> exist to intercept and manipulate WebSocket frames with ease, however they won’t catch everything. Perform manual testing and fuzzing to identify unexpected behavior or vulnerabilities that automated tools might miss.</p><p>If you lack experience in WebSocket security testing, consider consulting with security experts or penetration testers who specialize in this area, as the consequences of poor WebSockets security can be dire.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdb32027df85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ably-realtime/websocket-security-how-to-prevent-9-common-vulnerabilities-fdb32027df85">WebSocket security: How to prevent 9 common vulnerabilities</a> was originally published in <a href="https://medium.com/ably-realtime">Ably: Serious, serverless realtime infrastructure</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn to build your own desktop chat app with React and Electron, one step at a time]]></title>
            <link>https://medium.com/free-code-camp/build-a-desktop-chat-app-with-react-electron-and-chatkit-744d168e6f2f?source=rss-9f4bc2e3bf30------2</link>
            <guid isPermaLink="false">https://medium.com/p/744d168e6f2f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Alex Booker]]></dc:creator>
            <pubDate>Mon, 04 Jun 2018 16:51:35 GMT</pubDate>
            <atom:updated>2018-06-06T17:33:32.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-_ZbCJQtclP5tVK3" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=medium&amp;utm_medium=referral">Clément H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This tutorial was written in collaboration with the awesome Christian Nwamba.</em></p><p>When learning to code, you have a bunch of resources at your disposal — books, screencasts, tutorials, even exercises. But to become a great developer, you need to practice what you learn with a project.</p><p>Learning by doing is the motivation for this article. You’ll start from nothing and build a complete chat application, step by step.</p><p>You’ll build the project one step at a time and to test you understand it, we included some special bonus challenges at the end. Are you up to the test?</p><p>Here’s what we’ll build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*o0ILCOojCdCs4NB0.gif" /></figure><p>Pretty cool, right 😏?</p><p>When you follow along, you’ll learn how to build realtime chat, a “who’s online” list and along the way, how to structure a React app. To power our chat, we’ll be using a service I am helping to build called <a href="https://pusher.com/chatkit?utm_source=medium&amp;utm_term=desktop-chat-app-tut">Chatkit</a>.</p><p>Sound good? Tune in to <a href="https://youtu.be/twcOr043i4k">FreeCodeCamp radio</a> for some smooth, gentle background music to keep focused and let’s go!</p><h3>What you need to know</h3><p>Actually, one more thing 👀:</p><p>It would be nice if you knew some basic JavaScript, Node and React already. That being said, if you don’t feel comfortable with these technologies, have a go anyway!</p><p>We intentionally structured this tutorial to make it clear where to paste code so you can follow along. If you have questions, drop them here!</p><p>Alright, step one:</p><h3>Setup Electron</h3><p>To build a cross-platform desktop app with web technologies, we’ll use <a href="https://electronjs.org/">Electron</a>.</p><p>To get us off the ground, we made a minimal starter template. Download it:</p><pre>git clone https://github.com/pusher/electron-desktop-starter-template electron-desktop-chat</pre><pre>cd electron-desktop-chat</pre><p>And install those local dependencies:</p><pre>npm install</pre><h3>Create a Chatkit account</h3><p>We’re not too concerned with building a back-end in this tutorial so we’ll use <a href="http://pusher.com/chatkit">Chatkit</a>.</p><p>To follow along, <a href="http://pusher.com/chatkit">create a free account</a> and a new instance called “Electron desktop chat”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mIYRakmmplQuXiyI.gif" /></figure><p>In the settings window, turn on the test token provider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*bfFE2Zg1VWukbpkd.gif" /></figure><p>Note <strong>Your Test Token Provider Endpoint</strong>, <strong>Instance Locator</strong> and <strong>Secret Key</strong>. We’ll need them in the next step.</p><h3>Setup the Node server</h3><p>Chatkit has two fundamental concepts: <a href="https://docs.pusher.com/chatkit/core-concepts#users">Users</a> and <a href="https://docs.pusher.com/chatkit/core-concepts#rooms">rooms</a>.</p><p>Users can create rooms, join them, and chat in them. But before a user can interact with a room, we need to create one.</p><p>This has to happen on the server.</p><p>In electron-desktop-chat, run:</p><pre>npm install --save express cors body-parser pusher-chatkit-server</pre><p>And paste this in a new file called server.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f75cb2cf0a37871ca30587bdbad26656/href">https://medium.com/media/f75cb2cf0a37871ca30587bdbad26656/href</a></iframe><p>Remember to replace instanceLocator and key with your own the <strong>Instance Locator </strong>and <strong>Key</strong>.</p><p>Most of this code is boilerplate, importing dependencies, setting up Express, and so on.</p><p>The important part is the “/users” route which handles requests to create a new user.</p><p>Run the server with node server.js and you will see the server is “Running on port 3001”.</p><h3>Create the username form</h3><p>When someone loads our app, we’ll want to ask them for a username and then send it to “/users”.</p><p>Install some native-looking UI components with:</p><pre>npm install --save react-desktop</pre><p>And create a form component called UsernameForm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a23227b8b7fcea9c49cb41b1a8be1b43/href">https://medium.com/media/a23227b8b7fcea9c49cb41b1a8be1b43/href</a></iframe><p>You can read more about React form components <a href="https://reactjs.org/docs/forms.html">here</a>. By chance, the documentation uses a NameForm class similar to ours so it should all be familiar!</p><p>Next, replace all of App with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5c7b64133c087ce2d0747a7e257e947/href">https://medium.com/media/b5c7b64133c087ce2d0747a7e257e947/href</a></iframe><p>And to test it, run npm run dev. You will see the username form is rendered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yQY4Z9AKtmAV1rvD.png" /></figure><p>Make sure server is running (remember, the command is`node server.js), hit <strong>Submit</strong>, and you will see that a user is created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hjNlVMLHXd9VV2Qu.gif" /></figure><h3>Transitioning screens without a library</h3><p>Once we have a user, we can transition them from the UsernameForm to the actual chat screen. We should define that now.</p><p>Create a new component called Chat:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6275e96da9ed860f6aea61d00924a50/href">https://medium.com/media/e6275e96da9ed860f6aea61d00924a50/href</a></iframe><p>And update App:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36bf73bbd765483bf04bfb1a3b649c3b/href">https://medium.com/media/36bf73bbd765483bf04bfb1a3b649c3b/href</a></iframe><p>Run the app, enter a username, and you will transition to the chat screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*yz6R-9aO0mtQO8cD.gif" /></figure><h3>Add realtime chat with Chatkit</h3><p>Things are really coming along, wouldn’t you say?</p><p>To connect to Chatkit from the client, you need to install <a href="https://www.npmjs.com/package/@pusher/chatkit">@pusher/chatkit</a>:</p><pre>npm install --save add @pusher/chatkit</pre><p>And replace all of Chat with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cedea2e26f8a7f3d18e6f4376c8142b8/href">https://medium.com/media/cedea2e26f8a7f3d18e6f4376c8142b8/href</a></iframe><p>Remember to replace the tokenProviderUrl and instanceLocator values with <strong>Your Test Token Provider Endpoint</strong> and <strong>Instance Locator</strong>.</p><p>Run the app, hit ⌘+⌥+I (Control+Shift+I) and you will see that you connected to Chatkit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*awt3lX7P8-34CD9W.png" /></figure><h3>Create a Chatkit room</h3><p>We have a user but now we need a room!</p><p>To create one, use the Chatkit inspector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*bjy-pDVLlEf_TwC5.gif" /></figure><p>Remember to copy your room ID, we’ll need this in the next step.</p><h3>Create a chat room component</h3><p>Now we have a room, we can subscribe to new messages sent in that room.</p><p>To render them, create a MessageList component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae6be01a711882406aa6389d75c5fc90/href">https://medium.com/media/ae6be01a711882406aa6389d75c5fc90/href</a></iframe><p>And update Chat:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/425caa2ab539e76b4eb970a4ed08d54e/href">https://medium.com/media/425caa2ab539e76b4eb970a4ed08d54e/href</a></iframe><p>As ever, remember to update roomId with your actual room ID.</p><p>Now, when messages are sent in our room, onNewMessage will be called. From here, we can update our state and in turn, our UI.</p><p>In a second, we will let users send their own messages. For now, to test the subscription, use the inspector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MRLxCyFW8Mi3uydt.gif" /></figure><h3>Sending messages</h3><p>To let users send their own messages, create a SendMessageForm component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b896255bd9f4669e42665fe5fe5d75b8/href">https://medium.com/media/b896255bd9f4669e42665fe5fe5d75b8/href</a></iframe><p>And update Chat:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c0b102efecf0db862f50f953e17dee/href">https://medium.com/media/e2c0b102efecf0db862f50f953e17dee/href</a></iframe><p>Reload the app with ⌘+R (Control+Shift+R) and you will be able to send messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*iPUvhRR4bH0oeEql.gif" /></figure><p>In fact, why not open two applications side-by-side and have a conversation with yourself?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*IK1ZRrRPs61nvy0_.gif" /></figure><p>What a time to be alive…</p><h3>Style the UI</h3><p>Thanks to <a href="http://reactdesktop.js.org/">React Desktop</a>, our app already looks decent but we can do better.</p><p>Let’s make a few tweaks and define our layout for use in the next and final step.</p><p>Replace all of index.css with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ee4f68121d6956bd042d39ccbff3dca/href">https://medium.com/media/3ee4f68121d6956bd042d39ccbff3dca/href</a></iframe><h3>Show who’s online</h3><p>To finish our chat app, we will add a “who’s online” list to show, you guessed it, who’s online!</p><p>Create an OnlineList component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d8bebb132f56d8325ff8dc11f7748c4/href">https://medium.com/media/9d8bebb132f56d8325ff8dc11f7748c4/href</a></iframe><p>Then update Chat:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c4c4ed11cf1dd633f513cc7a2b5fa65/href">https://medium.com/media/4c4c4ed11cf1dd633f513cc7a2b5fa65/href</a></iframe><p>Were you expecting that to be more difficult? I definitely did the first time I tried!</p><p>Because Chatkit updates the users property dynamically, we don’t have to manage any of our own state. We simply need to tell React to re-render and, in turn, re-evaluate users each time someone comes online ( onUserCameOnline ), goes offline (onUserWentOffline) or joins the room (onUserJoined).</p><p>Go ahead, run the server and client and admire your magnificent new chat app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*oFR5EvkwrXoJmt1K.gif" /></figure><p>If you’ve come this far, you might as well keep going 💪! Have a stab at these bonus challenges…</p><h3>Challenge 1: Show who in the room is actively typing</h3><p>See if you can add typing indicators the app. For example, if am typing, you and everyone else in the room would see “Booker is typing…”.</p><p>If Chris and I were both typing, you would see “Booker and Chris are typing…” and so on.</p><p>Hints:</p><ul><li><a href="https://docs.pusher.com/chatkit/reference/javascript#typing-indicators">Chatkit typing indicator documentation</a></li><li><a href="https://github.com/pusher/build-a-slack-clone-with-react-and-pusher-chatkit">Slack clone tutorial</a></li></ul><h3>Challenge 2: Allow the user to create their own room</h3><p>In this tutorial, we used the inspector to create a room and then hard-coded the room ID. This isn’t a good practice.</p><p>In most applications, you would want to dynamically create rooms with the <a href="https://docs.pusher.com/chatkit/reference/server-node#creating-a-room">createRoom</a> function.</p><p>When someone loads the app, ask them for a room name as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*3pU3TxftH-vyDnGL.png" /></figure><p>If the room exists, join it; if not, create it then join it.</p><p>Hints:</p><ul><li><a href="https://docs.pusher.com/chatkit/reference/javascript#create-a-room">createRoom documentation</a></li></ul><h3>Conclusion</h3><p>That was fun! We built a pretty cool chat app in what, less than an hour?</p><p>One thing I noticed (and maybe you did too) is that once the foundation is in place (template, Chatkit connection, and so on), adding new chat features is pretty simple.</p><p>Aside from the challenges, we would be curious to see where else you could take the application. Some ideas:</p><ul><li>Send files</li><li>Unread message count</li><li>Notifications</li><li>Read cursors</li><li>Private one-to-one messaging</li></ul><p>Feel free to follow us on Twitter, <a href="http://twitter.com/bookercodes">@bookercodes</a> and <a href="http://twitter.com/codebeast">@codebeast</a>.</p><p>Until next time, ciao.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744d168e6f2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/build-a-desktop-chat-app-with-react-electron-and-chatkit-744d168e6f2f">Learn to build your own desktop chat app with React and Electron, one step at a time</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>