<?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 Viacheslav Luschinskiy on Medium]]></title>
        <description><![CDATA[Stories by Viacheslav Luschinskiy on Medium]]></description>
        <link>https://medium.com/@vialus?source=rss-bbeb4f18218d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_K_hY-l41dbW3EI50RhIZw.jpeg</url>
            <title>Stories by Viacheslav Luschinskiy on Medium</title>
            <link>https://medium.com/@vialus?source=rss-bbeb4f18218d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:22:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vialus/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[Using Enterprise React stack to build AI-Powered Applications in 2024/25]]></title>
            <link>https://javascript.plainenglish.io/using-enterprise-react-stack-to-build-ai-powered-applications-in-2024-25-b89d1de4b985?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89d1de4b985</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 05:16:47 GMT</pubDate>
            <atom:updated>2024-09-09T05:16:47.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*asXP4awkgweOycmx_rnXSg.png" /></figure><p>The area of React application development has gone through significant changes over the past two years. React has evolved from a tool to build a Single Page Applications (SPAs) to a comprehensive full-stack framework, thanks to the introduction of completely new concepts such as Server Components and Server Actions. Today it’s possible to create a professional, enterprise-class application without ever leaving the single window of your Integrated Development Environment (IDE). It adds to developers’ satisfaction and significantly speeds up the journey from idea to market, what startup community would definitely benefit from.</p><p>Another shift in apps development that took place recently is the ubiquitous usage of Artificial Intelligence tools. To showcase the current state of the React-based technology stack and how to use it to build AI-powered Apps I have created an AI-powered Todo app. This application not only allows users to perform standard actions expected from the typical Todo app, but also provides AI generated suggestions to help successfully complete them. The AI functionality is powered by the <a href="https://openai.com/">OpenAI</a> API, but it can easily be integrated with other well-known AI providers depending on your needs. The <a href="https://www.openaitodo.com/">Demo app</a> also offers the option to use <a href="https://gemini.google.com/app">Gemini </a>from Google. The source code for this boilerplate is available on my GitHub repository, enabling you to quickly develop your own AI-powered applications.</p><p><em>Demo App</em> — <a href="https://www.openaitodo.com/">https://www.openaitodo.com</a></p><p><em>GitHub Repo</em> — <a href="https://github.com/slava-lu/ai-powered-todo">https://github.com/slava-lu/ai-powered-todo</a></p><p>Nowadays developing AI-powered apps is essential for startups that want to stand out. Venture capital providers see these apps as significant opportunities for growth, as AI-driven solutions often offer scalability, improved efficiency and the potential to reshape industries. Investors are interested in supporting startups that use AI to innovate and streamline operations, expecting substantial returns. At the same time, users are increasingly attracted to AI-powered apps for their ability to provide personalised experiences, automate tasks, and deliver more intelligent solutions, making this technology a key factor in both user satisfaction and startup success.</p><p>In this article I will go deeper into the most significant changes that have occurred in the React ecosystem over the last two years, focusing on the new features and skills you’ll need to master in order to build modern, AI-powered applications. If you’re interested in understanding the technical evolution of the React technology stack over a longer period of time, I recommend reading <a href="https://medium.com/javascript-in-plain-english/enterprise-react-in-2022-3126ed43ba58">my previous article</a> from two years ago, which offers an additional overview.</p><h4>Modern React tech stack</h4><p>If you’re new to React, here’s what you need to learn to start building enterprise-class applications in 2024/25:</p><ul><li><strong>Basic React</strong> <a href="https://react.dev/learn">https://react.dev/learn</a></li><li><strong>Basic Next.js </strong><a href="https://nextjs.org/learn/dashboard-app">https://nextjs.org/learn/dashboard-app</a></li></ul><p>Additional modules to build AI-Powered Enterprise Apps:</p><ul><li><strong>Next-intl</strong> <a href="https://next-intl-docs.vercel.app/">https://next-intl-docs.vercel.app/</a></li><li><strong>Tailwind CSS</strong> <a href="https://tailwindcss.com/">https://tailwindcss.com/</a></li><li><strong>shadcn/ui</strong> <a href="https://ui.shadcn.com/docs">https://ui.shadcn.com/docs</a></li><li><strong>React Hook Form</strong> <a href="https://react-hook-form.com/">https://react-hook-form.com/</a></li><li><strong>Vercel AI SDK</strong> <a href="https://sdk.vercel.ai/">https://sdk.vercel.ai/</a></li></ul><p>Over the past two years the React ecosystem and Next.js framework have gone through significant transformations, marking a period of rapid evolution and innovation in web development. While some updates have been relatively minor, addressing performance optimisations or adding convenience features, others have fundamentally changed how developers build and think about React applications. Among these changes, the introduction of <a href="https://react.dev/reference/rsc/server-components">React Server Components</a> and <a href="https://react.dev/reference/rsc/server-actions">Actions</a>, advancements in concurrent rendering, and the new routing system stands out as particularly transformative. For React developers to stay up to date it is important to be in the loop of these changes and adapt accordingly.</p><p>Next.js offers a great <a href="https://nextjs.org/learn/dashboard-app">learning tutorial </a>therefore it does not make sense to provide any examples of the code here. It will only pollute the article where I want to outline the key changes and focus more on AI part.</p><p>One big impact on the React application landscape that I see is the significantly reduced need for centralised state management tools, like <a href="https://react-redux.js.org/">Redux </a>and third-party libraries, such as <a href="https://tanstack.com/query/latest">TanStack Query</a>. This is due to the robust built-in caching mechanisms and the ability to run much of the application logic directly on the server. React Server Components allow efficient data fetching and state handling on the server side, reducing the complexity and overhead traditionally associated with client-side state management. For tracking UI state it’s now recommended to use query strings, which also allow users to share deep links that represent the exact app state.</p><p>Among all the changes mentioned above React Server Components and Server Actions are the most significant. They provide an easier and more reliable approach to handling asynchronous operations compared to the traditional <a href="https://react.dev/reference/react/useEffect">useEffect </a>hook in client components. However, they also introduced some new challenges. Structuring the code with these new features can be complex, though manageable. There is also a lack of clear documentation tools for Server Actions, as something like <a href="https://swagger.io/">Swagger </a>does not currently exist for this purpose. The <a href="https://react.dev/reference/react/useActionState">useFormState </a>(recently renamed to useActionState) and <a href="https://react.dev/reference/react-dom/hooks/useFormStatus">useFormStatus </a>hooks, which come with Server Components and Actions, are not as intuitive as they could be. Their design could be improved, but with some initial research and practice they become usable and effective in practice.</p><p>Regardless of your perception of the new React ecosystem it is difficult not to accept Next.js absolutely fantastic ease of deployment to <a href="https://vercel.com/">Vercel</a>, which is especially important for startups looking to get their product in front of users quickly without messing up with hosting and deployment complexities. However, it’s worth noting that the free Vercel account only supports one database, so if you need more, you might need to consider paying $20 per month for a commercial account or exploring other hosting options.</p><p>In the area of CSS there is a new leader — <a href="https://tailwindcss.com/">Tailwind CSS</a> that has become de facto a standard for styling React based applications, with <a href="https://ui.shadcn.com/">shadcn/ui</a> being a high-level component library built on top of Tailwind. This combination provides a powerful and flexible solution for building modern user interfaces. And the cherry on this pie is the AI based design tool from Vercel that builds quite good UIs with shadcn/ui and Tailwind - <a href="https://v0.dev/">https://v0.dev/</a></p><p>All the big changes introduced in the last two ears brought additional challenge for React developers. If you’re working on a React project that is five years old or more, upgrading it to the latest version can be next to impossible. You can only keep the React version up to date as long as the old API is supported. Updating an older project to reflect modern development practices usually requires a complete rewrite. Unfortunately, there are currently no AI tools that can assist with this process in a reliable and meaningful way.</p><h4><strong>React meets AI</strong></h4><p>Whether it’s just a hype or something more, today users expect nearly any new app to have some level of AI integration. It might sound crazy, but my example shows that even such a simple app like Todo can be powered by AI and it still makes sense. With this in mind, let’s dive into the main topic of this article: building AI-powered apps with React.</p><p>I would point out three important questions you as a developer of AI-powered applications need to consider.</p><p><strong>Question 1: Which AI API should I use and how can I integrate it?</strong></p><p>Selecting the right AI API is important to achieve expected results. The quality of large language models (LLMs) often correlates with their cost. While premium LLMs offer powerful capabilities, they come at a higher price. On the other hand, more affordable options might not deliver the results you need. Therefore, it makes sense to experiment with different models and remain flexible so that you can switch to a better one if it becomes available. To facilitate this flexibility you can use an abstraction layer over the AI APIs, which Next.js provides through the <a href="https://sdk.vercel.ai/">Vercel AI SDK</a>. This SDK allows you to build your logic independently of the specific API although you’ll still need to create accounts and obtain API keys from each provider.</p><p><strong>Question 2: Do I need to fine-tune an LLM?</strong></p><p>The short answer is probably “No”. Large companies invest billions of dollars and vast amounts of computing power into improving LLMs. By the time you fine-tune a model, a better one may already be available on the market. Additionally, fine-tuning can be expensive, and there’s a risk that the investment might not pay off. If you have very specific data, consider using retrieval-augmented generation (RAG) first. RAG processes your data and presents it in a human-readable format similar to AI-generated outputs. This leads us to the next question.</p><p><strong>Question 3: Do I need to learn RAG and the tools to implement it?</strong></p><p>The answer is again “No”, at least for the pilot phase. Many services, such as OpenAI, offer RAG as a service (<a href="https://platform.openai.com/docs/assistants/overview">Assistants API)</a>, saving you from the need to learn and implement it yourself. While this might add to your costs (and probably quite a lot), it’s essential to remember that AI integration often involves unpredictability. RAG might not always deliver the results you need, in which case, you’ll better pay something to try it out and then cancel the subscription if you do not get what you want.</p><h4><strong>AI Skills for a software developer</strong></h4><p>It is worth mentioning that to build AI-powered tools you do not have to know anything about neural network, as you do not have to know C++ to use admin tools written in that language. However, integrating AI into your app brings new challenges and requirements that you may not have encountered before. I would group the necessary skills into three main categories:</p><h4><strong>General AI Skills:</strong></h4><ul><li><strong>Prompt Engineering:</strong> Although referred to as “engineering,” creating effective prompts is more of an art than a science. It’s like teaching a child — simple, direct instructions don’t always work, and you’ll need to experiment to find out what does. And like with children you need to pick up a different prompt for different AI models.</li><li><strong>Mitigating Hallucinations:</strong> AI models can sometimes generate incorrect but nice looking outputs, especially when asked complex or unusual questions. It’s very important to understand the limitations of the LLM you’re using. Do not ask them to find the answers to the new or rare problems.</li></ul><h4><strong>Technical AI Skills:</strong></h4><ul><li>While as mentioned above you don’t need in-depth knowledge of LLMs, transformers, or vector databases to use AI APIs, having a basic understanding of these concepts will help you to navigate through information and make informed decisions.</li><li>Learning how to implement Streaming APIs is essential. Users today expect real-time interactions, and while streaming is relatively simple on the backend, it poses some challenges on the frontend, as most frameworks aren’t designed to provide good streaming experience out of the box. You can start by exploring the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Streams_API">Streams API</a> documentation.</li></ul><h4><strong>AI-Related Business Skills:</strong></h4><ul><li>Business management might seem outside of the scope of a software developer’s role, but in the AI world it becomes quite relevant. You need to calculate the cost of each request to AI API, which is based on tokens (words) from the user’s question, your prompt, and the AI’s response. The number of input and output tokens can vary, so accurate estimation is key.</li><li>Making a decision when to charge users is another challenge. For example, if a user’s internet connection is slow and the response is canceled due to a timeout, charging a user at the end of AI response could be problematic and leading to money loss, especially if someone intentionally tries to hack you. Because you already paid for some tokens but have not charged the user due to connection loss. Charging a user before delivery of the full AI response, in case the response fails, may result in customer dissatisfaction. This is a delicate balance that requires careful planning.</li></ul><p>If you’re interested in exploring my <a href="https://github.com/slava-lu/ai-powered-todo">source code</a> of an AI-powered Todo list, here are a few things to keep in mind:</p><ul><li>The demo app is designed to showcase AI integration and does not include security features, neither for Server Actions nor for the AI API. It’s intended for local use only.</li><li>The demo also highlights the new React hooks related to Server Components and Actions. However, this isn’t necessarily the best way to achieve the business objectives. For example, I found the useFormStatus hook cumbersome and ultimately removed it in my demo version.</li><li>As mentioned earlier, frameworks like Next.js weren’t originally built for streaming. Finding the best way to integrate streaming into the existing logic can be challenging, so don’t hesitate to explore better solutions than mine.</li><li>I don’t share the exact prompts used in my production demo, so your local results may differ from what you see in the demo. This is because Prompt Engineering is an art. With each model release you may get different result and will need to perform that art again. If you’re unhappy with the results, don’t blame the LLM — spend more time refining your prompts.</li></ul><p>If you get stuck, feel free to reach out to me. My contact information is in the footer of the <a href="https://www.openaitodo.com/">demo app</a> or you can also message me privately here on Medium.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89d1de4b985" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-enterprise-react-stack-to-build-ai-powered-applications-in-2024-25-b89d1de4b985">Using Enterprise React stack to build AI-Powered Applications in 2024/25</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No-limit Auth using Express.js. Hardcore style.]]></title>
            <link>https://levelup.gitconnected.com/no-limit-auth-using-express-js-hardcore-style-fb58c4343897?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb58c4343897</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[user-management]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 23:23:41 GMT</pubDate>
            <atom:updated>2024-01-16T23:23:41.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uH1U4zh47SsU5rfdQT-P5Q.jpeg" /></figure><p>Every new software project starts with user authentication and management. This is a very boring but important part of any application. You most likely want to jump right into implementing business features but are not sure what would be the best and fastest way to tackle user management.</p><p>You can choose some ready-made solution like <a href="https://www.authkit.com/">Authkit </a>or <a href="https://www.keycloak.org/">Keycloak</a>, but they are black boxes and still require some time investment to learn, then to manage, and then to rely on their support.</p><p>What if you could have professional code that you can just cut and tune for your own needs? In this case, you could have your own user authentication solution ready within a week and be as professional as any ready-made system out there. Therefore, I am excited to introduce a JWT-based authentication solution using pure Node.js, encompassing all the features likely needed for most modern applications. This ‘pure’ approach means no ORM, no Passport.js, and no reliance on third-party libraries. This solution can serve as an adaptable boilerplate where you can tweak it to suit your specific requirements. It offers unrestricted freedom, free from third-party APIs and complex configurations.</p><p>This article is accompanied by a fully functional demo app, which showcases all the features along with the source code for both backend and frontend.</p><p><strong>Working demo</strong>: <a href="https://www.authdemoapp.com/">https://www.authdemoapp.com/</a></p><p><strong>Backend source code:</strong> <a href="https://github.com/slava-lu/auth-app-backend">https://github.com/slava-lu/auth-app-backend</a><br><strong>Swagger docs: </strong><a href="https://api.authdemoapp.com/api-docs/">https://api.authdemoapp.com/api-docs/</a><br><strong>Frontend source code</strong>: <a href="https://github.com/slava-lu/auth-app-frontend">https://github.com/slava-lu/auth-app-frontend</a></p><p>I have categorized the security features showcased in the Demo app into ‘<a href="https://www.authdemoapp.com/">Basic’ and ‘Advanced’</a>. This article focuses solely on the advanced features as basic feature are common across application and do not require extra explanation.</p><p>Before delving into each of the advanced features, it’s useful to outline the potential user management policy you may want to implement.</p><p><strong>Login Functionality:</strong> The application<strong> </strong>should allow users to authenticate via local passwords or social networks (OAuth), leading to a unified account. Locally created accounts require additional email verification. Users should have the option to enable two-factor authentication (2FA) for both local and OAuth account types. Prioritizing convenience, active users won’t need to re-enter their password on each app access. However, inactivity over three months necessitates re-authentication. Users can delete their accounts, which are then disabled but retained in the database, with an option for restoration. Users can also log out from their current device or all devices used previously.</p><p>As an optional feature, restricting login to only one device could be beneficial for certain applications, like streaming services.</p><p>In financial or other sensitive applications, having an auto-logout feature is a standard practice. It’s important that this feature is configurable to meet specific security needs.</p><p><strong>Password Management Functionality:</strong> Users must have the ability to change their password or recover a forgotten one. Admins should also be able to force a user to change the password. This will only affect users signing in locally without OAuth.</p><p><strong>Content Access functionality:</strong> Some content should be available for all users other should be protected.</p><p><strong>Administrative Control</strong>: Admins need the ability to instantly ban users. Additionally, support staff should have impersonation capabilities, allowing them to view the UI as another user, but with all actions logged under their actual account ID. Critical operations, such as changing passwords, must be restricted in impersonation mode.</p><p><strong>Enhanced Security for Admins:</strong> Certain users, like administrators, should be restricted from using social networks for login to enhance security. Additionally, it may be required for such users to have two-factor authentication (2FA) enabled.</p><p><strong>Critical Resource Access:</strong> Even for logged-in users, accessing the most sensitive resources should require password entry. This applies to users with local accounts. If a user initially logged in via a social network, they must set up a local password for accessing these protected resources.</p><p><strong>Public Network Sign-in</strong>: Users signing in from public networks may prefer not to store their authentication JWT persistently. Hence, the option to stay logged-in should be optional, including for social network sign-ins.</p><p>Now we go deep into some most interesting and exited features.</p><h4><strong>Deleting and Restoring Accounts</strong></h4><p>Typically, accounts are not completely removed from the database to avoid cascading deletion of all associated user data, which is undesirable both from a user interface and audit standpoint. This discussion will omit the varied legal perspectives on data privacy and protection, as they differ significantly across countries.</p><p>Some companies choose not to provide an account restoration feature, explicitly warning users that account deletion is permanent. Others, however, offer a grace period during which the account can be reinstated. In our Demo app, once an account is deleted, users receive a confirmation email containing a link to restore their account, should they reconsider their decision. From a marketing standpoint, I see no compelling reason to restrict the timeframe for account restoration. Nevertheless, if security and data privacy concerns necessitate it, we could implement a time limitation using a cron job. This job would systematically remove the account restoration code from the database after a set period, making the account irrecoverable. This method, leveraging a cron job, offers more dynamic control than embedding similar logic directly into the backend application code.</p><p>Another important consideration is the implication of completely deleting an account. If a user is permitted to register a new account using the same email address, this could potentially lead to a range of fraudulent activities. Therefore, even if legal requirements mandate the total removal of user data, it might still be prudent to prevent the reuse of the same email address in the future.</p><h4><strong>OAuth</strong></h4><p>Auth is a complex topic, not so much because it involves hard-to-understand concepts, but mainly due to its messiness in terms of different options, flows, and variations. Each article about OAuth tends to cover different aspects, further complicating the subject. Below, I will attempt to present the most straightforward explanation of OAuth. It will describe a classical use case involving both the REST API backend server and frontend client within your own domain. This scenario likely represents the majority of web applications out there. A clear understanding of the classical flow will also help to better grasp its different variations.</p><p>The classical OAuth flow is a three-step process. This design choice was made because the creators of OAuth wanted to encompass all possible use cases. However, they realized that many real-world applications do not need all three steps, or that some applications might not have a backend server. This realization led to a variety of OAuth flows and scenarios.</p><p>Let’s now explore the classical flow with some useful variations using Google as an example of an OAuth provider. The classical OAuth flow is officially called “Authorization Code Flow” should you want to ask ChatGPT for more details.</p><p><strong>Step 0 — App Setup:</strong> You need to visit Google’s web pages for developers and create your developer account. With this account, you can create a project where all your application data is stored. Since Google offers a range of services beyond OAuth, providing the exact URL for setting up OAuth in Google would be impractical as it may become outdated with subsequent updates. In most common scenarios, you need to set up the Client ID, Client Secret, and the Return URL for your application. You will also get some Google URLs to uses during the subsequent steps.</p><p><strong>Step 1 — Get the Authorization Code:</strong> A user clicks the “Sign in with Google” button. Clicking this button opens a special Google webpage (the URL of which you get in step 0) where a user can log into Google or, if already logged in, simply confirm that they are willing to share some personal information with you, the web app owner. The specific information requested is detailed on this webpage. As a developer, you specify the information you need about a user in the query string parameter of the URL that opens this Google page. The users confirm their willingness to share the requested information by clicking a button on that page. Google then generates a random string, referred to as a Code, and returns the user to the page using the return URL you specified in step 0, appending the code to the query string of that return URL.</p><p>As a result of step 1, you receive a Code from Google in your application. This code, by itself, is practically useless as it merely enables you to proceed to step 2.</p><p><strong>Step 2 — Get the Access Token:</strong> Unlike the code from Step 1, the access token you receive in this step can be used to obtain some personal user information. Therefore, the classical OAuth flow implies that you request the access token via a secure backend call to prevent interception. Specifically, upon receiving the code in the query string from Step 1, the frontend app should pass it to the backend. The backend server then uses this code in a call to another URL from Google, which you also obtain in Step 0. Along with the code from Step 1, this call requires the app secret ID, also provided in Step 0. This ensures Google that the request is genuinely from you and not from someone who simply possesses the code. If Google verifies the provided information, it responds with the access token, which looks like a random string but has the structure of a JWT token. Unfortunately, this access token does not contain any user information, so we have proceed to Step 3.</p><p><strong>Step 3 — Get the User Info:</strong> You pass the access token to the frontend (or continue calling Google from the backend, if preferred), add this access token in the header of a REST API call, and request the specific information you want about users, such as their email. If the access token is valid, you finally obtain the desired information.</p><p>Easy? Well, some people didn’t think so and suggested some “improvements”.</p><p><strong>Improvement 1:</strong> In most cases, we need the same basic information about a user: name, email, and profile picture URL. What if we simply include this info in the JWT access token and skip Step 3? This is what the creators of OAuth thought and called this improvement “<strong>OpenID Connect</strong>”. You can request OpenID Connect in Step 1 by adding the word “openid” to the “scope” query string parameter. Now in Step 2, you receive not only the basic access token, but another token called the id token, from which you can decode the basic user information. This exact improvement is implemented in the Demo app.</p><p><strong>Improvement 2:</strong> What if you don’t have a backend? Suppose you have a simple mobile app, or a so-called Single Page Application completely written in JavaScript that operates in the browser. The creators of OAuth addressed it with the “<strong>Implicit Flow</strong>” improvement. In this flow, instead of receiving the code in Step 1, you get the access token or id token right away, effectively reducing the process from three steps to just one! The Implicit Flow, unsurprisingly, is considered less secure but remains a viable option. To indicate to the OAuth provider that you want the Implicit Flow, you need to set the query string parameter response_type in Step 1 to “token” instead of “code”. Given the ever-increasing security threats, I wouldn’t be surprised if some OAuth providers eventually discontinue offering the Implicit Flow, so I would recommend using it only when necessary.</p><p>OAuth has a bunch of other variations, but the ones mentioned above are the most common.</p><p>In the Demo App, I’ve gone a bit further than just implementing standard OAuth with OpenID Connect. The additional features implemented in the app include:</p><p>1. Linking Accounts</p><p>2. Signing Out from the OAuth Provider (Removing App’s Permissions)</p><p>3. 2FA with OAuth</p><p>Linking local and OAuth user accounts based on email can be a very convenient feature. OAuth relies on trust in the third-party system, meaning that if a user has an account on LinkedIn or Google, that account should have a verified email. The most challenging part of automatically linking accounts is implementing it correctly, regardless of whether the first login method used is OAuth or Local with a password. If a user first signs in with OAuth, they can then request a password recovery link to set up a password for local authentication at a later time.</p><p>Another useful feature is the option for users to log out from their OAuth provider. For example, when a user first signs in with Google, they grant certain permissions to the app. With these permissions, you can access the user’s name, email, picture, etc. Subsequent logins via Google do not require asking for these permissions again. To revoke the granted permissions, a user would typically have to navigate to their Google account, find the appropriate setting, and remove the app from a list. However, Google also provides an API for this purpose. In the Demo app, I implemented this functionality on the profile page. If you are signed in via LinkedIn or Google, at the bottom of the Profile page, you will see a button to sign out from the respective OAuth provider, effectively removing the app from the list of allowed apps in the Google settings page.</p><p>The use of two-factor authentication (2FA) with OAuth will be described in one of the subsequent sections.</p><h4><strong>Preventing Certain Groups from Using Social Networks for Login</strong></h4><p>Using social networks (OAuth) for login is convenient and fast, but it might not be the best option if you require additional security for an account. Even though you can potentially ask a user to re-login with Google, you can’t force them to change their Google password. So, if a user’s Google account is compromised, there’s not much you can do apart from simply blocking the account. Therefore, you may not want certain sensitive user groups (like the admin group in the demo app) to be able to log in using social networks.</p><p>Local login allows for two extra security features:</p><p>· Forcing users to change their password.</p><p>· Requiring users to enter their password for some sensitive operations.</p><p>Alternatively, you could require Two-Factor Authentication (2FA) for OAuth accounts to access sensitive information, but it might be less convenient for users to set up 2FA compared to just using a local password.</p><p>Which groups are not allowed to log in via OAuth is controlled via a configuration table and the parameter “socialLoginNotAllowed”. This is not a trivial task, as the user’s identity is unknown before authentication. Therefore, you need to incorporate this check in the middle of the OAuth flow, after you have received the email from the OAuth provider but before you issue a JWT token. In the demo app, this check is placed in “oauthMiddleware.js” middleware.</p><h4><strong>Keeping Active Users Always Logged In</strong></h4><p>How long can a user stay logged in? This is an important question for both usability and security. If the period is too long, it poses a security risk; if too short, it will annoy users by requiring them to enter their password repeatedly. I suggest using a kind of sliding window approach. Each time a user opens the app with a still valid JWT, the expiration date is moved forward. So, as long as the user uses the app often enough, they always stay logged in. If the user is not active, then the JWT expires and a new sign-in is required. In my demo app, I have set the JWT lifetime to be 3 months. If a user uses the app at least once every 3 months, the JWT effectively never expires.</p><p>There is one more thing to consider regarding JWT lifetime: JWT is kept in a cookie, which also has a lifetime. It is useful when the cookie’s lifetime is a bit shorter than that of the JWT, so that the cookie expires first. In this case, we simply show the user as not being logged in. If the JWT expires first, then we will have an authentication error due to an invalid JWT.</p><p>There is also the option to deselect the ‘remember me’ checkbox. In this case, a user will be signed in only for the duration of the session. For most browsers, this means until the browser is closed.</p><h4><strong>Auto Sign-Out</strong></h4><p>Auto sign-out is designed to terminate a session after a period of inactivity. In the frontend app, we use an npm module to manage the timeout state and reset it when there is some activity. The timeout configuration is kept in the DB config, where it can be turned on and off. The two key parameters are the <strong>timeout </strong>time and the <strong>warning </strong>time.</p><p>The timeout time is the number of seconds a user is allowed to be idle. The warning time is the number of seconds before the expected logout when we start showing a warning widget in the browser with a countdown. Auto sign-out is recommended for financial applications or for applications that can be used in public places.</p><h4><strong>Role-Based Access Control</strong></h4><p>When a user makes a call to an endpoint, a few checks can take place. The first round of checks is done by the “checkUser” middleware. This middleware checks the JWT and some other parameters, like whether the email was validated, if the user has not been banned, etc. If more granular control is required, then the second middleware, “checkRoles”, can be added to the endpoint. This middleware checks if a user has a specific role before allowing the call to go through.</p><p>Apart from this roles control, which can be configured per endpoint or group of endpoints, there is one global control called <strong>role dependency</strong>.</p><p>Imagine you want all your admins to have 2FA. If a user has set up 2FA, we give him a specific role, let’s call it “2fa”. We can add a “2fa” group requirement to each of the admin routes. But the app offers a more elegant way. In the configuration table, you can specify that the admin role is dependent on the 2fa role. This means that the middleware will check if a user with the admin role also has the 2fa role. If not, access to the resource is denied.</p><p>In the config table, this configuration would look like this: <em>{“roleDependencies”: {“admin”: [“2fa”]}}.</em></p><h4><strong>Two-Factor Authentication (2FA)</strong></h4><p>Two-Factor Authentication is now expected from any system. There are two main ways it can be implemented: one is to send a code via SMS, and the other is to use some mobile apps that can generate one-time tokens. The SMS method is a bit less reliable since it requires mobile network coverage, but it’s simpler to set up. It also brings some extra infrastructure cost. For a not-very-critical app, using a free 2FA mobile app like Authy is a good option.</p><p>My Demo app implements a standard 2FA flow plus some advanced features described below:</p><p>1. 2FA can be used with social login (OAuth) as well. Surprisingly, some well-known apps out there do not implement 2FA for OAuth. This might be due to the fact that not all third-party auth modules have this feature out of the box. Setting up 2FA for OAuth requires extra effort. In the demo app, we use “postLogin” middleware to trigger the second step in authentication flow. This allows us to implement it where it’s needed, including OAuth routes.</p><p>2. Once users set up 2FA, they get a special role, called ‘2fa’. This allows for the use of standard role-based access control to limit access to users who have not set up 2FA. Additionally, the role dependency feature makes it easy to require all admins to have 2FA set up as well.</p><p>In some scenarios, the 2FA flow can become complex because login is now a two-step process of two stateless HTTP requests. The login is completed not when the user presents his credentials, but when he enters a valid code in the second step. This means that in the case of 2FA, you need to move some login activities to the code check endpoint, which in some cases, like with the “One login only” feature, becomes not very trivial.</p><p>Another aspect to keep in mind is the recovery procedure in case a user loses his device. For this, you may generate some recovery codes that a user can print and save somewhere. Technically, this task is easy, but practically, a user may be more likely to lose this recovery code paper than a phone. Thus, its practical usefulness can be questioned. In this sense, sending an SMS is more preferable for critical apps, as losing the phone does not mean losing the number. The number can be restored with the mobile network provider, which removes this extra management layer from you.</p><h4><strong>Sign Out from All Devices / One Login Only</strong></h4><p>Although these two features may seem very different from a business perspective, they are achieved using the same technical solution. Therefore, they are grouped here under one section.</p><p>To achieve this functionality, you need to add some randomly generated code in the JWT token, which I call “hashCheck”. This code should be matched against a value kept in the database upon every request. The purpose of this code is to add manual validation of the validity of the JWT. When a REST API call is made, the middleware checks, among other things, that the “hashCheck” in the JWT matches the “hashCheck” in the database. If this value does not match, the user is signed out (his cookie is deleted).</p><p>This is how it works in both scenarios:</p><p><strong>Sign out from all devices: </strong>When a user clicks this button, a new value of “hashCheck” is randomly generated and replaces the current value in the database. Consequently, all JWTs of that user stored anywhere become invalid.</p><p><strong>One login only:</strong> Each time a user signs in, a new “hashCheck” code is generated and put in both the database and the current JWT. As a result, all previous JWTs become invalid, and a user can’t access the system from other devices.</p><p>If you want to implement the feature to log out a user from a specific device instead of all devices, then you need to come up with a logic for generating the device ID based on location, OS, device type, and add a new table where you will keep the list of allowed devices. Instead of a random token, you would need to keep the device IDs in the JWT and check it against this table of allowed devices. Everything else remains the same. Personally, I do not see how this feature can be broadly useful, although I have seen some apps in the past where it was implemented. In most cases, signing a user out from all devices can be just enough.</p><h4><strong>Login as Another User (Impersonation)</strong></h4><p>Impersonation is a very powerful, yet potentially dangerous feature. It allows someone (like an admin or support personnel) to act as another user, while still logging actions under the real account ID. This feature might not be desirable in a banking app, but in apps with a very complex UI where users may struggle, it can significantly reduce support efforts. I’ve seen this feature be particularly useful in apps that help businesses manage their accounting online, where users can easily get lost and sending hundreds of screenshots to support staff might not be the best option.</p><p>Implementing the impersonation feature requires special consideration at the early stage of database design. To implement it properly and securely, you need two different tables: one for the account and one for the user. In this arrangement, an Account ID is not the same as a User ID. All UI elements and user rights are dependent on the User ID, but some security features and logging are based on the Account ID. During normal operations, the Account ID and User ID belong to the same person, but when a support person clicks on the “Impersonate” button, a JWT is created containing the Account ID of the support person and the User ID of the user being impersonated. This setup allows viewing the user interface as the impersonated user while tracking all actions under the Account ID of the support personnel. Additionally, some security features, like changing the password or deleting the account, are disabled in impersonation mode.</p><p>The step-by-step impersonation flow in the Demo app looks like this:</p><p>1. Login as a support user with the impersonation role enabled.</p><p>2. If the support user has the required role, the “login as” menu item becomes visible in the top right menu.</p><p>3. The support person enters the email of the user to be impersonated. As it is a sensitive operation, the password of the support user is requested. This means it will not work if the support user signs in using OAuth. In our security policy, users with the “impersonation” role are anyway not allowed to sign in using OAuth.</p><p>4. If the password is correct, a special JWT is created and assigned with the account ID of the original user and the user ID of the user being impersonated. A special flag is also added to the JWT indicating impersonation mode. Now, the UI appears as it would to the user, but since the real account ID is still present in the JWT, the actual user making changes can be identified.</p><p>5. Based on the special flag, the UI header indicates impersonation mode, so the support user does not forget it when they leave for lunch and return after an hour.</p><p>6. The Impersonation mode works only in the session mode. After the browser is closed, the user is signed out.</p><p>7. In Impersonation mode, functions for deleting accounts and changing passwords are disabled for security reasons.</p><p>To add an extra layer of security, you might consider allowing impersonation to work only with a one-time token that the end user generates and sends to the support person. This means that a support person can only impersonate with the user’s permission. However, this functionality is not implemented in the Demo app.</p><h4><strong>Require Entering the Password for Some Actions</strong></h4><p>If you are the admin of a sensitive system, you may prefer not to store your password in the browser. In this case, your sensitive operations may have additional protection by requiring the entering of a password, even if you are already signed in. In the Demo app, this is implemented for the “login as” feature that allows impersonating one user as another. From a development perspective, it is not a complex task. You need to add the “passwordCheck” middleware to the route endpoint and make some modifications to the frontend.</p><p>After the frontend is modified, you can turn this feature on and off by passing a false parameter to the middleware. If you pass “false”, the password check is skipped, allowing you to toggle it on and off without much code modification. You can see that the route /users/profile/update has the middleware with the false parameter. As soon as you remove “false, updating the profile will require a password check.</p><h4><strong>Cross-Tab Communication When Logging In and Out</strong></h4><p>This is a frontend feature, not directly related to the backend and REST API, but it’s still quite important to mention in a security context. Without tab synchronization, if you have multiple tabs open and sign in on one tab, you will still appear as signed out on the other tabs and would have to refresh the page to update the state. This is not very user-friendly.</p><p>There are a few ways to synchronize the status of browser tabs. The current common practice is to use the Broadcast Channel API. In the Demo app, if you sign in or out on one tab, you will see the UI change accordingly in all other open tabs using the aforementioned API.</p><h3><strong>Final Words</strong></h3><h4><strong>JWT Authentication</strong></h4><p>The key part of this solution is JWT based authentication. When implementing it a few key things should be considered.</p><p>1. How to send JWT in REST API calls.</p><p>2. Use of the refresh token.</p><p>There are two ways to send JWT to the backend server:</p><p><strong>HTTP Header</strong>. The good old approach is to use HTTP header of “Authorization: Bearer {jwt}” structure. The benefit of this approach is that it can be used for both mobile and web apps, but it is less secure therefore another approached used in this demo app.</p><p><strong>HttpOnly Cookies with JWT</strong>. As the name implies the token is passed via cookie. JavaScript code does not have access to this cookie that makes this approach more secure. As to the lack of cross platform feature in this case, I would say that today it is a very small disadvantage. In most cases the functionality of the web app and the native web is very different, so it makes little sense to unify just the authentication layer.</p><p><strong>Refresh Tokens.</strong> Originally, refresh tokens were not designed for simple scenarios where frontend and backend services under a single domain are managed by the same entity. While they are beneficial in complex, multi-domain configurations, their use in simpler setups tends to introduce unnecessary complexity without significant security benefits.</p><p>The approach of the short-life access token and the long-life refresh token can still be valid when aiming to avoid database queries with every network request, instead verifying authentication directly within the JWT. This approach offers performance advantages in high-load applications, though it does come with certain security considerations. For example, when you block the user you need to wait for the access token to expire before the user loses the access. For some applications it can be a big disadvantage. Therefore, in this demo app I check if a user is eligible to run a REST API call by making user checks against the database with every request. That eliminates the need of the refresh token.</p><h4><strong>Database</strong></h4><p>Since I do not use an ORM, I created a few helpers for INSERTs and UPDATEs, as they often follow a common pattern. I don’t have any wrappers for SELECT statements because they often involve joins and aggregations, which are easier to write with raw SQL statements than with any kind of wrapper. DELETE statements are quite rare and simple, so having a wrapper for them doesn’t seem justified. The INSERT and UPDATE wrappers also have transaction versions. Handling queries in a transaction is a bit different in the Postgres node module. A transaction requires special handling of the database client. We can’t just use the pool; rather, we create a client from the pool and use it throughout the transaction. More information on this can be found at <a href="https://node-postgres.com/features/transactions.">here</a>.</p><h4><strong>Config Table vs Config File vs ENV Variables</strong></h4><p>There are several places where an application can keep its configuration parameters. Parameters that are not expected to change often can be placed in a local config file. Sensitive parameters should go into the Environmental variables. Some parameters can be stored in the database to be adjusted from the admin interface without going through development or DevOps cycles. These parameters are read from the DB before Express.js starts and are set as global variables in Express.js using the app.set command. They can later be read via the app.get command. These parameters are stored in the database as JSON in a JSONB type of column, which is well-suited for storing configuration parameters but lacks data integrity controls. Extra care should be taken when storing these kinds of parameters. When changing parameters in the config table, a node service restart is necessary as the app reads the configuration table only at startup.</p><p>Thanks for reading. Should you want to contact me you can find the contact details at the <a href="https://www.authdemoapp.com/">footer of the demo app</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb58c4343897" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/no-limit-auth-using-express-js-hardcore-style-fb58c4343897">No-limit Auth using Express.js. Hardcore style.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise React in 2022]]></title>
            <link>https://javascript.plainenglish.io/enterprise-react-in-2022-3126ed43ba58?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3126ed43ba58</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 06:17:42 GMT</pubDate>
            <atom:updated>2022-04-23T16:02:07.268Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building enterprise-class React apps in 2022</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaMKpHvt-XL6XlD75vydIg.jpeg" /></figure><p>Learning React and being able to develop enterprise-class applications with React are two different things. There are two main reasons for that. First, there is a huge ecosystem of different modules you need to master. Second, this ecosystem changes every year. The last time I presented the enterprise React tech stack was <a href="https://medium.com/javascript-in-plain-english/enterprise-react-in-2020-78155bc99259">two years ago</a>. As you will see, there are not many modules from that tech stack that made it to this year. Since it might be challenging to navigate your way in React world I have written this article that can serve you as a map to the current state of the exciting React wonderland.</p><p>Along with this article comes the <a href="https://github.com/slava-lu/enterprise-react-2022">GitHub repo </a>and the <a href="http://enterprise-react-2022.vercel.app/">Demo app</a>, which brings together all the modules mentioned here (and some more). You can use this repo as the boilerplate of your next great React app.</p><p><strong>TL;DR</strong></p><p><strong>Main modules</strong></p><p><a href="https://nextjs.org/">Next.js </a>— React SSR framework</p><p><a href="https://redux.js.org/">Redux</a> — Central state management</p><p><a href="https://github.com/kirill-konshin/next-redux-wrapper">next-redux-wrapper</a> — Next and Redux connector</p><p><a href="https://redux-saga.js.org/">Redux-Saga</a> — Async middleware for Redux</p><p><a href="https://github.com/vinissimus/next-translate">next-translate</a> — Translation and i18n</p><p><a href="https://react-hook-form.com/">React Hook Form </a>— Form library</p><p><a href="https://chakra-ui.com/">Chakra UI</a> — Design system</p><p><em>Demo </em>— <a href="https://enterprise-react-2022.vercel.app/">https://enterprise-react-2022.vercel.app</a></p><p><em>Repo </em>— <a href="https://github.com/slava-lu/enterprise-react-2022">https://github.com/slava-lu/enterprise-react-2022</a></p><p>The first big change from the year 2020 is that Server-Side Rendering (SSR) is now a must. It is no longer just an SEO trick or performance optimization method. It is the industry standard, that can’t be avoided. Without SSR it is next to impossible to get any good score in the modern Google ranking system called <a href="https://web.dev/vitals/">Core Web Vitals.</a> Core Web Vitals became so much important these days that the learning portal of the main SSR framework has dedicated the <a href="https://nextjs.org/learn/seo/web-performance">whole section</a> to this topic. I would recommend mastering Core Web Vitals to a good level. With the ever-increasing amount of information, it can be really difficult to tell which site is better based on just its information. So checking how many efforts developers put into creating the website might become the key ranking factor for the Search Engines.</p><p>The key framework to build a React-based SSR app is <strong>Next.js</strong>. There are no real alternatives at the moment. Next.js is easy to start with and it has a good getting started guide and documentation. You can easily build a simple app with it but it becomes a bit tricky when it comes to Enterprise-class apps. The problem is the central state management like Redux that most big apps still need. There have been numerous attempts to get rid of Redux or replace it with something else but since Redux provides a really great developer experience, I am sure it will stay for some more years.</p><p>The challenge with Redux is that it is meant to be used client-side. Each time you render a page on the server you create a new Redux store which you then need to somehow merge with the existing client state (the process is called hydration). Hydration can be tricky and prone to errors. The best approach would be to make the first render as SSR, create a new clean Redux store, and then do only client-side renders. This was exactly the initial approach of Next.js when they introduced the <strong><em>getInitialProps</em></strong> data fetching method. For some reasons they later decided to shift away from this approach and introduced two new methods, <strong><em>getServerSideProps</em></strong> and <strong><em>getStaticProps</em></strong> as a potential replacement for the original one. The main claim from <a href="https://vercel.com/">Vercel</a>, the company behind Next.js, was that the two new methods can improve the app performance. They have not removed the original <em>getInitialProps</em> but they tried to avoid any mention of it in their communication and documentation. The purpose of <em>getStaticProps </em>is to render the static page during the build time and then just serve the static content. I doubt that many enterprise-level apps have lots of static content to make heavy use of this method. The main target of <em>getStaticProps</em> could be the competing <a href="https://www.gatsbyjs.com/">Gatsby </a>framework. The purpose of <em>getServerSideProps </em>is less clear even with the explanation from Vercel and there is an ongoing debate if Next.js should really push the developer community towards this method. What is clear though is that <em>getInitialProps</em> works much better with Redux and killing <em>getInitialProps </em>completely could dramatically decrease the use of Next.js. Since there are no alternatives in React world as mentioned above it may motivate developers to try out <a href="https://vuejs.org/">Vue.js</a> and <a href="https://nuxtjs.org/">Nuxt.js </a>and probably stay there.</p><p>Today it is still not obvious which direction Next.js will finally peruse. In the Demo app I used all three data fetching methods to show how they can be used with Redux. As you may see <em>getInitialProps</em> provides a much smoother developer experience than the other two methods.</p><p>For the Redux middleware that handles REST API (and WebSocket as well), I suggest using the good old <strong>Redux-Saga</strong> module. It provides a very good separation of UI from the business logic and makes managing the complex business logic very simple. It would be fair to mention that the initial learning of Redux-Saga can be time-consuming but then you will be building your async middlewares with a speed of light.</p><p>If you follow React trends you might have noticed that there are voices that suggest moving data fetching logic to the component level but I guess this could be just another attempt to finally kill Redux. I do not see any real benefits of it for the big apps. Separation of UI from the data fetching logic increases the app’s reliability and improves the developer experience. Developer experience becomes more and more important these days. Technology becomes complex, learning it becomes difficult and it is hard for a human to comprehend, let alone master all of the emerging techs. Therefore, making something simple can be a decisive point in choosing one technology over the other.</p><p>One of the additional benefits of Redux-Saga, when used with Next.js, is that you can easily choose your data fetching/navigation strategy. There are two main approaches:</p><ol><li>First navigate to a new page, then fetch data.</li><li>First fetch data, then navigate.</li></ol><p>The first approach looks like to be more popular but it is not easy to achieve with Next.js as data fetching methods, whatever they are, block the page navigation. Redux-Saga allows you to choose if you want to wait for data calls to be completed (promises resolved) before navigation or you don’t, therefore, making it possible to easily implement any of the options. How this is done can be seen in the demo app. Look for the <em>navigateAfterSaga</em> prop in the source code.</p><pre><em>Shop</em>.getInitialProps = async ({ store }) =&gt; {<br>  store.dispatch(<em>triggerProductList</em>(10))<br>  return {<br>    <strong>navigateAfterSaga</strong>: false,<br>    title: &#39;title#shop_page&#39;,<br>  }<br>}</pre><p>As to the low-level data fetching function, this time I use <a href="https://axios-http.com/"><strong>Axios</strong></a><strong> </strong>instead of classical fetch. Mostly due to timeout functionality that is very well managed by Axios both on the client and the server. To be honest, I don’t even have a clue how you could manage timeouts on the server with fetch and Next.js.</p><p>One nice new feature of Next.js is <a href="https://nextjs.org/docs/advanced-features/i18n-routing">Internationalized Routing</a> that comes out of the box. Unfortunately, it is only a small part of what developers need to build multi-language apps. You still need a translation module at least. You should choose one carefully as not all translation modules support all Next.js data fetching methods. I recommend using <strong>next-translate</strong> as it supports <em>getInitialProps</em>.</p><p>Another feature, that a good multi-language app might need, is to change the URL path based on the language. Not only the language prefix but the whole path so that e.g. ‘<em>en/page’</em> becomes ‘<em>de/seite’.</em> This is claimed to be achieved with the Next.js <a href="https://nextjs.org/docs/api-reference/next.config.js/rewrites">rewrites </a>feature. But it is definitely not the right place where it should belong to. I hope Next.js can address it at some point in the future.</p><p>One of the important choices you need to make in the tech stack selection process is the UI library. You can make your own but you need quite a lot of effort to do this. There are some ready-made solutions and the clear leader today in React world is <strong>Chakra UI</strong>. Previously Material UI was among the top choices but people became tired of it and the development of this design system was not very active. Chakra offers a good range of <a href="https://chakra-ui.com/docs/getting-started">basic free elements</a> as well as pre-built templates in the paid <a href="https://pro.chakra-ui.com/">Pro version</a>. With Pro templates, you can create the UI of your E-commerce web app really within a few days and without Figma or any other design tools. This is really cool.</p><p>The problem though like with any other UI library is that it forces you into its own API. If you have learned all the CSS properties, you have to re-learn them with Chakra UI. That is a bit annoying but you can always print the list of the most used ones and clip it somewhere in front of you. For very complex or unique UI elements, I would suggest using the <a href="https://styled-components.com/">styled-components</a> library as it offers great flexibility and it uses standard CSS. No abbreviations or Camelcase replacements.</p><p>As to the form management, there is a new young leader in React ecosystem. After the original <a href="https://redux-form.com/">Redux Form</a>, the popular option for a short time was <a href="https://formik.org/">Formik</a>. The problem with Formik was that it used the render props pattern. This pattern was once claimed to be trendy and therefore used by a number of modules. This pattern though did not stay for a long time. I find this pattern confusing and with complex apps, it becomes difficult to see what’s going on in your code.</p><p>To address the problems of Formik and the previous form libraries the new player appeared and is now actively gaining momentum — <strong>React Hook Form</strong>. It is easy to use and comprehend. The main challenge comes from the fact that it is based on the uncontrolled form pattern. Therefore it becomes complicated to submit the form outside the form component, but it is not impossible. The simplicity and good documentation are the killer features of this library.</p><p>This was the overview of the main modules you can use to start building the professional enterprise-class React apps.</p><p>A few words about <strong>deployments</strong>. If you built the app with Next.js you should consider deploying it to <a href="https://vercel.com/">Vercel hosting</a>. You can just connect your GitHub repo to Vercel cloud and click a couple of buttons to get it published. What is even more useful, you get the CI/CD out of the box. As soon as you create a Pull Request you can get the preview deployment and as soon as you merge the Pull Request to the master/main branch, your production deployment is updated. If you have ever tried to configure this kind of functionality in Jenkins or GitHub Actions you will love this feature.</p><p>There are a couple of other important topics that are not directly related to React but rather to the frontend domain in general so I will briefly touch on them.</p><p><strong>Testing</strong>. Testing is trickier than it might seem to be. On the one hand, everyone claims that testing is important but a few can dive deeper into which testing is important and why. Most of the unit testing hype comes from the backend world, where there is no immediate feedback to developers while they write their code. The only simple way for backend developers to see if their code actually works before it hits the production system is to test it with unit tests. But that is not the case in the modern frontend world. With the current high performant and reliable <a href="https://nextjs.org/docs/basic-features/fast-refresh">Fast Refresh</a> feature offered by Next.js and other frameworks, frontend developers can immediately see the result of every line of code they type in. Combining this with the Component-based approach that separates the code from affecting each other (especially if you separate UI from the data layer with Redux Saga) the value of unit testing becomes not that visible. I would bravely claim that unit tests add little value to the React app unless you have files with some complex data manipulation. But if you do so, I would highly recommend checking if this piece of code should belong to the backend.</p><p>What can be really useful in frontend testing is end-to-end UI tests. It is often difficult for frontend developers to see that a picture border-radius is 4 px rather than 2px or that spacing between elements has increased by an extra 4px. This type of UI tests can be automated with many good tools. Also randomly clicking links and buttons with some automation tools can be helpful. Developers usually check the logical paths that a reasonable human would choose. Clicking the buttons randomly may bring the site down or result in a non-consistent state. This is better to be avoided.</p><p>The last topic that I want also to touch on is third-party services. Nowadays no one wants to mess with mail servers and other infrastructure-related software. To save you some time for googling the available options I have listed my personal preferences below. I will not give any arguments to keep this article relatively short but feel free to use the comments if you want to talk about it.</p><p><a href="https://cloudinary.com/">Cloudinary </a>— storing and serving all media files</p><p><a href="https://sendgrid.com/">Sendgrid</a> — sending technical emails</p><p><a href="https://mailchimp.com/">Mailchimp</a> — sending marketing emails</p><p><a href="https://sendbird.com/">Sendbird</a> — chats and other messaging functionality</p><p>Many people may argue that they managed to build great apps using a different set of modules. Most likely it will be true. But what I can promise you is that you will not regret your choices, if you choose the tech stack presented here.</p><p>I hope you have found this overview useful. Feel free to follow me to stay up to date with the React trends or leave a comment if you have something to add or disagree with.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3126ed43ba58" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/enterprise-react-in-2022-3126ed43ba58">Enterprise React in 2022</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Technology Guide for Startup Leaders]]></title>
            <link>https://medium.com/swlh/modern-technology-guide-for-startup-leaders-9b5e804bf319?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b5e804bf319</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 08:01:01 GMT</pubDate>
            <atom:updated>2022-01-28T12:18:53.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UOkRxRPhPloYUuWix9KZWA.png" /></figure><p>From time to time, I meet people with a business background trying to lead a technology startup or participate in some way in a technical project. The typical case would be a company that wants to move online or expand to new markets by building an online platform. This sounds good, but there are some challenges.</p><p>The first thing a startup CEO usually does is to find someone with some technical background and ask him about the technical implementation of the solution.</p><p>This often ends up not as expected, due to:</p><ul><li>This guy may not necessarily be an expert, even if you think he is.</li><li>This guy may offer you the solution that is most interesting for him personally, but not for your business.</li></ul><p>The same applies if there is no tech guy nearby and the request is sent to a technology company that someone has recommended.</p><p>If you have little or no tech skills, you have to blindly trust every solution presented to you. Unfortunately, there is no such book as “Modern Software Development for Dummies” nor will it ever be written, as the modern tech stack is too dynamic for a standard book publishing cycle.</p><p>Therefore, this article is an attempt to give a high-level non-technical overview of some of the architectural concepts and development technologies in the modern world. You will unlikely become a tech guru after reading it, but you should be able to challenge the technical solutions presented to you.</p><p>This article will be most useful for commerce, marketplaces and other classical types of businesses. Innovative tech companies doing self-driving cars or drone delivery have a very specific tech stack that can hardly be shared with the other type of companies.</p><p>The diagram of what we will talk about is in the article header image. If you want to view a high-quality image or print it, you can <a href="https://drive.google.com/file/d/13uXBxpObrclLDVhcXmOwjp8ofPiYkt4W/view?usp=sharing"><strong>download it in PDF</strong></a><strong> </strong>format.</p><p>I will describe each part of the diagram below, namely the following key concepts:</p><ol><li>Frontend (Web)</li><li>Mobile app</li><li>Backend (REST API)</li><li>Databases</li><li>(Cloud) Hosting</li><li>DevOps</li><li>Microservices</li></ol><p><strong>Disclaimer</strong>: It is possible to build a solution with the different technologies as mentioned below. Just make sure you understand why you do it differently.</p><h3><strong>Frontend (Web)</strong></h3><p>Frontend is responsible for building a User Interface (<strong>UI</strong>) and making sure a User has a positive experience (<strong>UX</strong>) when using your web site. Some time ago, a typical developer was building both UI/UX and a server logic (backend). Now, as the user interface becomes more complex, it makes sense to have dedicated frontend developers to make sure your app still works as you continue to add new features and increase traffic.</p><p>JavaScript (JS) is the only language used today to create dynamic UI. The problem, however, is that no one is using just JS. It would be impossible to implement the complex UI without the help of some higher-level abstractions called <strong>frameworks</strong>.</p><p>There are three main JS frameworks for frontend development:</p><ul><li><a href="https://reactjs.org/">React</a></li><li><a href="https://angular.io/">Angular</a></li><li><a href="https://vuejs.org/">Vue</a></li></ul><p>Frameworks and the ecosystem around them are quite different from each other, making it unlikely that one person can be a guru in more than one framework. Don’t try to google which framework is better as you will get random results.</p><p>I would advise you to follow this logic when choosing a framework:</p><ul><li>If you are serious about the project and would like to build both the web app and the mobile app, pick up React.</li><li>If you want a quick web prototype, choose Vue.</li><li>If you want a strict structure rather than freedom of choice, use Angular</li><li>If you are not sure, pick up one for which it is easier to find the developers. In some regions, one framework may be more popular than others. React developers generally tend to be in higher demand and more expensive.</li></ul><h3><strong>Mobile app</strong></h3><p>There are two main approaches to building a mobile app. One is a good old native development where you build a separate app for each mobile platform using a specific language for that platform. Another is using a cross-platform language that somehow works with or compiles to the native code.</p><p>Although the first option has been around for quite some time, the languages ​​recommended by the platform vendors have recently changed. Google, the vendor of the Android-based operating system, now recommends using <a href="https://kotlinlang.org/"><strong>Kotlin</strong> </a>instead of the previous <a href="https://www.java.com/en/"><strong>Java </strong></a>option. Apple suggests using <a href="https://swift.org/"><strong>Swift </strong></a>instead of the former <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><strong>Objective C</strong></a><strong>.</strong> However, you can still build the app using the old languages, as it might be easier to find developers with that language skills.</p><p>As for the second approach of cross-platform development, it allows building mobile apps cheaper and faster. But it comes at the cost of reduced performance, sometimes a slower user interface, and a larger app size. Unless you plan to use some advanced hardware features or need your app to be super performing, I still recommend using the cross-platform approach.</p><p>The primary player in cross-platform mobile development is Facebook with its <a href="https://reactnative.dev/"><strong>React Native</strong> </a>solution. If you have built your web app with React and backend with Node.js you may ask the same developers to build the mobile app for both platforms as well. That’s pretty good if you lack resources. Alternatively, you can use Google’s recent solution — <a href="https://flutter.dev/"><strong>Flutter</strong></a>. It uses the <a href="https://dart.dev/"><strong>Dart </strong></a>language, which is rarely used anywhere else, so it might be difficult to find a Flutter developer at the moment. The Flutter may be a good option if you care about high performance but still want to save some money using cross-platform development.</p><h3><strong>Backend (REST API)</strong></h3><p>The backend is probably the most complex area to choose the right technology for. It has a long history with Java being the oldest language that survived until now. There are also relatively new players like Node.js, which attract developers with simpler language structures and shorter development times. Since backend development covers a wide range of products, not necessarily web applications, we focus only on what you need to build the REST API.</p><p>The <a href="https://restfulapi.net/"><strong>REST AP</strong></a>I, in plain English, is the server that gets the data from some sources, such as the database, and sends it to a web browser or a mobile app using some well-defined data formats. Contrary to the old approach when a server was responsible for the data and the UI, the REST API only cares about the data, while frontend developers and JS frameworks are responsible for UI.</p><p>The most popular languages to build the REST API currently are:</p><ul><li><a href="https://nodejs.org/en/">Node.js</a></li><li><a href="https://www.java.com/en/">Java</a></li><li><a href="https://www.python.org/">Python</a></li></ul><p>Node.js is the quickest but, nevertheless, the powerful option to build the REST API. Not only can you quickly build it, but you can also share backend development with the frontend developers because Node.js uses the same JavaScript language. If you have no preference over the language, this is the preferred option.</p><p>The next option is Java. Java is very different from JavaScript, regardless of the misleading common Java word. Java enforces a stricter architecture and presumably helps the developer to make fewer coding errors. But it comes at a cost. Java language is more complex and Java developers are more expensive.</p><p>Taking into account the complexity of the language, Java may be a bit overkill for the simple REST APIs. There is also some confusion about Java licensing, as some versions of Java are free, while others are not.</p><p>Python, the third option, is generally used for Data Analysis, Machine Learning, AI, etc. Not many people choose it as the language for the REST API, but still, some do. If you need to use Python in other parts of the solution, no one will blame you for using it for the REST APIs as well.</p><p>To be a bit more objective, I should also mention <a href="https://docs.microsoft.com/en-us/dotnet/csharp/"><strong>C#</strong></a> from Microsoft. Many big companies use it. This is not the best option for a startup, but there are a lot of C # developers who can build a good REST API. The problem is that the Windows-based infrastructure is largely more expensive than a Linux based one. Although you can try using C# with Linux, I still haven’t seen the success stories with that combination.</p><p>Unfortunately, the decision-making process does not stop with choosing the language, because, as with the frontend, you have to choose a framework.</p><p>Below is the list of the most popular frameworks split by languages. The most used is highlighted in bold:</p><ul><li>Node.js: <a href="https://expressjs.com/"><strong>Express</strong></a>/Koa</li><li>Java: <a href="https://spring.io/projects/spring-boot"><strong>Spring Boot</strong></a>/Vert.x</li><li>Python: <a href="https://www.djangoproject.com/"><strong>Django</strong></a>/Flask</li></ul><p>As with frontend, each backend developer has a preference for one framework over the other. There are also some frameworks that are not listed here, but these are safer to use.</p><h3><strong>Databases</strong></h3><p>Database is the heart of your app, so making a good choice here is important. Before picking up a database brand you need first to decide on the database type: <a href="https://aws.amazon.com/relational-database/"><strong>Relational</strong></a>(SQL) or <a href="https://aws.amazon.com/nosql/"><strong>NoSQL</strong></a>. There was much hype about NoSQL databases so don’t try to google which one is better. NoSQL databases are not intended to be generic data warehouses. They should be used for specific purposes or when your data has little or no structure.</p><p>Not all databases are free. Most of the well-known commercial relational databases are <a href="https://www.microsoft.com/en-us/sql-server/sql-server-2019"><strong>Microsoft SQL</strong></a> and <a href="https://www.oracle.com/database/"><strong>Oracle</strong></a>. They come with a set of good tools for database design and management, but today there are good tools for the free databases as well.</p><p>Two main options for the free relational databases are:</p><ul><li><a href="https://www.mysql.com/">MySQL</a></li><li><a href="https://www.postgresql.org/">PostgreSQL</a></li></ul><p>I would say they are more or less the same. Due to competition, each vendor tries to copy the good features of the other vendor. PostgreSQL is often chosen by many developers as it also has better features for working with the NoSQL data types. Personally, I prefer MySQL since it has better tools to manage the data and the database itself. You may also have heard about <a href="https://mariadb.org/"><strong>MariaDB</strong></a>. It is still far behind in usage compared to the other two, so I wouldn’t be using it right now.</p><p>After choosing a database, you need to decide how your backend will communicate with it. The basic option is just to use SQL itself. This works well, but some people think it is a bit complex and offer other approaches, <a href="https://en.wikipedia.org/wiki/Object-relational_mapping"><strong>ORM </strong></a>being the most popular one. ORM stands for Object-Relational Mapping and helps you avoid writing SQL queries. It can be a lot easier for simple things, but as soon as you have complex data selections and insertions, it can become a huge bottleneck. Professional developers generally do not recommend using ORM and prefer to stick with the native SQL.</p><p>A few words about NoSQL databases. If you want to store some unstructured data you can safely pick up <a href="https://www.mongodb.com/"><strong>MongoDB</strong></a>, the best known NoSQL database. If you need any caching solution, look at <a href="https://redis.io/"><strong>Redis</strong></a>. NoSQL databases are a complex topic, so I would not go into more detail. Just challenge your developers if they offer to store your primary data in these types of databases. You may be tempted to use a NoSQL database if you sell products of completely different types that have few overlapping features, but it is still better to try putting some core data into the SQL database so that you can use all the benefits of data consistency and reliability of classical relational databases.</p><h3><strong>(Cloud) Hosting</strong></h3><p>Choosing a hosting provider may seem like a simple thing, but today it is not, because, in addition to outsourcing a computer power and disk space, you must now think about outsourcing scalability, resiliency, and security concerns, as well as database management and infrastructure monitoring. Additional complexity also comes from the fact that hosting companies are now good enough at marketing new services that may seem great but which you probably won’t need.</p><p>The top 4 players in the global hosting market are:</p><ul><li><a href="https://aws.amazon.com/">Amazon (AWS)</a></li><li><a href="https://cloud.google.com/">Google (GCP)</a></li><li><a href="https://azure.microsoft.com/en-gb/">Microsoft (Azure)</a></li><li><a href="https://www.digitalocean.com/">Digital Ocean</a></li></ul><p>In addition to the above global companies, you can go with your local hosting providers, but they will most likely offer less convenient tools and a reduced set of services. Some companies still prefer to turn to local players because of the legal issues around keeping user data locally.</p><p>The first three companies in the list above offer a wide range of services with complex billing. Chances are, you don’t need 95% of what they offer. If you start completely new, I would advise you to start with the <strong>Digital Ocean</strong>. They have a clear interface, easy to use tools and offer practically everything a startup needs. If you want to try someone from the Big3, go to Amazon. It is a bit more expensive than Google, but it has better tools and UI. I can’t say much about Azure, as they still play more in Microsoft technology niche and apparently have no clear advantages over Amazon or Google.</p><p>To be efficient and competitive today, you not only have to outsource infrastructure but also some of the business services. Those services were internally managed about 5 to 10 years ago, but are now generally outsourced:</p><ul><li>Sending emails (<a href="https://sendgrid.com/">Sendgrid</a>)</li><li>Storing and managing images (<a href="https://cloudinary.com/">Cloudinary</a>)</li><li>Chats, video and audio communication (<a href="https://www.twilio.com/">Twilio</a>)</li></ul><p>There are many companies that offer these types of services, and the leaderboard changes every year. I just gave an example of the companies I would go with, but describing the benefits and making a comparison would probably require another article like this.</p><h3><strong>DevOps</strong></h3><p>DevOps is a generic term. Usually, it means, among other things, setting up a release pipeline which is often referred to as CI/CD (Continuous Integration/Continuous Delivery). Sometimes team structures and different agile practices are also considered part of the DevOps, but I will keep it out of scope.</p><p>The idea behind CI/CD is to move the code from the developer to the production server as fast as possible without much human intervention.</p><p>The typical development cycle looks like this:</p><ol><li>Product manager presents the new idea</li><li>Designer turns the idea into a visual prototype</li><li>Developers code the prototype</li><li>Developers push the code to the code repository (GitHub)</li><li>GitHub triggers tools that run automated tests</li><li>If automated tests are successful, the code is moved (deployed) to the test servers for manual testing</li><li>Quality Assurance team manually tests the code</li><li>If the tests are successful, the release manager pushes a button to deploy the code to the production servers.</li></ol><p>20 years ago, moving code to the server and between them was done through FTP, either manually or with some scripts. Now it is a little different and there are many tools to automate it. There is no absolute leader in this area, so it is quite difficult to name a go-to solution. A couple of brands you might want to check out are <a href="https://jenkins.io/"><strong>Jenkins</strong> </a>and <a href="https://about.gitlab.com/stages-devops-lifecycle/continuous-integration/"><strong>GitLab CI/CD</strong></a>. If you start small, I would advise trying a new tool called <a href="https://github.com/features/actions"><strong>GitHub Actions</strong></a>. It does not require any additional servers, as it is part of GitHub, where you store the code, but it can do almost everything you need at least in the early stages of the project.</p><p>Before pushing the code to the server, the current best practice is to wrap it in the <a href="https://www.docker.com/"><strong>Docker </strong></a>container. You can get away without it, but it would take a lot more effort later to build a scalable and resilient infrastructure. The Docker was created with the idea of ​​isolating the application environment from the hosting environment so that any code runs on any server. It’s still the good benefit of Docker, but probably the biggest one is the option to easily scale the entire solution by deploying Docker to the <a href="https://kubernetes.io/"><strong>Kubernetes </strong></a>cluster. Kubernetes is a container orchestration system. It’s a pretty complex technical topic, but it basically scales and replicates your Docker containers, so they work reliably and according to the load. If you choose the managed Kubernetes cluster from global cloud hosting providers, this complex topic can become quite easy but still a bit expensive.</p><p>There is one thing that does not just fit into one topic but encompasses areas of database, hosting and DevOp. That is the database hosting. You can host it as a classical Docker container like the other parts of the solution, or you can use a managed database hosting service from the hosting provider. The first option is cheaper, the second is easier and more scalable. If you decide to use the second option, check to see which databases are supported, as not all providers support all databases.</p><h3><strong>Microservices</strong></h3><p>Most people familiar with the modern world of software development have heard the word <a href="https://microservices.io/"><strong>Microservices</strong></a>. Microservice is not a piece of the diagram like the topics above, but rather the architectural approach to make your system more scalable and resilient. Scalability and resiliency are definitely the good things, but what is not always clearly mentioned is the cost you have to pay for it. And the cost is really high.</p><p>If you choose to use microservices, the first challenge will arise very soon when you decide to have an authentication service as one of the microservices. The problem is that authentication is used by all microservices and how to share authentication among them is a big and complex topic. The next challenge will appear when you have a transaction that spans different microservices. This easy thing with the single service, it immediately turns into a big headache with microservices. Therefore, unless you have a professional (and well paid) team of backend and frontend engineers, as well as a dedicated DevOps team, I would highly recommend starting monolith (without microservices). A good working monolith is much better than poorly functioning microservices. Also with Docker and Kubernetes, you can achieve scalability and resiliency with much less effort than using microservices.</p><p>Anyway, if you start monolith and one day hit the performance issues, you will be able to peel off some service to a microservice.</p><p>This was a brief introduction to the modern application development world. Each topic mentioned in this article is a large and complex technical area in itself with many books and other articles describing it, but I hope this article was a useful summary. The more you understand the technology, the greater the chances you have to succeed. As most investors say, the idea itself is worth nothing, proper implementation is what makes it successful.</p><p>As we now know, offline businesses can go away when a new virus arrives. Your online business will have a much better chance to survive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b5e804bf319" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/modern-technology-guide-for-startup-leaders-9b5e804bf319">Modern Technology Guide for Startup Leaders</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Objects and Arrays Manipulation for REST API]]></title>
            <link>https://medium.com/@vialus/javascript-objects-and-arrays-manipulation-for-rest-api-b3b59a73b618?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3b59a73b618</guid>
            <category><![CDATA[lodash]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 11:47:38 GMT</pubDate>
            <atom:updated>2020-01-20T07:42:44.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7lQ-N3hsSj_GsQC51KVBA.png" /></figure><p>JavaScript objects and arrays manipulation can be complex but it is the essential part of any frontend application that deals with REST API. It can become even more complex if you add immutability requirement imposed by the most modern JavaScript frameworks like React and Angular.</p><p>From the other hand when working with REST API you do mostly the same things like <strong>CRUD</strong> operations (<strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate, <strong>D</strong>elete) and some other transformations, so you don’t have to learn everything about objects and arrays before you start building the apps.</p><p>In this article I will show how to professionally manipulate objects and arrays with the modern JavaScript including <strong>ES2020,</strong> as well as with the most popular <a href="https://lodash.com/"><strong><em>Lodash </em></strong></a>library in the scope of the common REST API tasks. I’ll skip all the basics and focus on the more complex and interesting parts.</p><p>Do we still need Lodash or we can get away with just the modern JavaScript? That is the question that we will try to answer at the end of this article as well.</p><p>You can play with all the examples in this article by cloning the accompanying <a href="https://github.com/slava-lu/object-manipulation"><strong><em>git repo</em></strong>.</a></p><p>Let’s now see how we can read and send data to the backend REST API. We will first have a look at how to do all the CRUD operations and then move on to the more complex transformations. We will start with reading operation.</p><h3><strong>READ</strong></h3><p>Before we can read something we first need to check if there is something. The tricky part here is that even empty array and object will result to ‘true’ when doing something like this:</p><pre><strong>const </strong>emptyArray = []<br>!!emptyArray<br>// =&gt; <strong>true</strong></pre><p>Therefore, you need to check the length property instead:</p><pre><strong>myArray</strong>.length === 0 <br>Object.entries(<strong>myObject</strong>).length === 0</pre><p>The chances are that your backend guys instead of sending the empty array or object will send nothing, so you’d better do a bit more complex check:</p><pre><strong>myArray </strong>&amp;&amp; <strong>myArray</strong>.length === 0<br><strong>myObject </strong>&amp;&amp; Object.entries(<strong>myObject</strong>).length === 0</pre><p>If you are not a person that loves strict typing, you can do it a bit shorter:</p><pre>!!( <strong>myArray </strong>&amp;&amp; <strong>myArray</strong>.length)<br>!!( <strong>myObject </strong>&amp;&amp; Object.entries(<strong>myObject</strong>).length)</pre><p>Now let’s see how we can do this check with Lodash. Lodash is the library, which has many functions that simplify common array, object and functions manipulations. When you import Lodash from the external module you usually refer to it as <strong>_</strong> (underscore sign).</p><pre><strong>_isEmpty</strong>(myArrayOrObject)</pre><p>Quite simple, right? That is why (some) people love Lodash.</p><p>Now lets try to read some value from the (deeply) nested object. For example we have the object like this:</p><pre><strong>const </strong>nestedObject = {<br>  <strong>key1</strong>:<br>    {<br>      <strong>key2</strong>:<br>        {<br>          <strong>key3</strong>: <strong>&#39;</strong>value3<strong>&#39;</strong>,<br>          <strong>key4</strong>: <strong>&#39;</strong>value4<strong>&#39;<br>        </strong>}<br>    }<br>}</pre><p>You can’t just write <strong><em>nestedObject.key1.key2.key3</em></strong> since if there is no <strong>key2</strong>, then trying to read <strong>key3 </strong>may crash your app. Therefore you should do something like this:</p><p>a) Good old way, which would probably work with the first version of JavaScript:</p><pre>nestedObject &amp;&amp; nestedObject.<strong>key1 </strong>&amp;&amp; nestedObject.<strong>key1</strong>.<strong>key2 </strong>&amp;&amp; nestedObject.<strong>key1</strong>.<strong>key2</strong>.<strong>key3</strong></pre><p>b) A brand new <strong>ES2020 </strong>way that can be currently (January 2020) used only with the babel or node <strong>13+</strong> with the ‘<strong>harmony</strong>’ flag:</p><pre>nestedObject?.<strong>key1</strong>?.<strong>key2</strong>?.<strong>key3</strong></pre><p>c) With Lodash</p><pre><strong>_.get</strong>(nestedObject, <strong>&#39;key1.key2.key3&#39;</strong>)</pre><p>Sometimes, if the key you are looking for does not exist you want to have some default value. In this case you need to modify above mentioned examples a bit like this:</p><pre><strong>a)</strong> nestedObject &amp;&amp; nestedObject.<strong>key1 </strong>&amp;&amp; nestedObject.<strong>key1</strong>.<strong>key2 </strong>&amp;&amp; nestedObject.<strong>key1</strong>.<strong>key2</strong>.key5 || &#39;default value&#39;<strong><br><br>b)</strong> nestedObject?.<strong>key1</strong>?.<strong>key2</strong>?.key5 ?? <strong>&#39;</strong>default value&#39;<strong><br><br>c)</strong> <strong>_.get</strong>(nestedObject, <strong>&#39;key1.key2.key5&#39;</strong>, &#39;default value&#39;)</pre><p>Another thing you need to know about the objects is that if your key is variable rather than a string, than instead of <strong>.</strong> you need to use <strong>[]</strong> like this</p><pre>nestedObject[keyVar]</pre><p>That is all you really need to know to read the data that usually comes from the REST API. Lets move to create operation.</p><h3><strong>CREATE</strong></h3><p>Creating something is quite simple:</p><pre><strong>const </strong>myArray = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br><strong>const </strong>myObject = {<strong>key1</strong>: <strong>&#39;</strong>value1<strong>&#39;</strong>, <strong>key2</strong>: <strong>&#39;</strong>value2<strong>&#39;</strong>}</pre><p>What you need to keep in mind though is that if you need to create a new array/object based on the existing one don’t do like this:</p><pre><strong>const </strong>newObject = myObject (<strong>Wrong!</strong>)</pre><p>Remember, whatever you do, you should <strong>Not</strong> mutate (change) the existing object/array but rather create a new one. Use spread operator like this instead:</p><pre><strong>const </strong>newArray = [...myArray] (<strong>Right</strong>!)<br><strong>const </strong>newObject = {...myObject} (<strong>Right</strong>!)</pre><p>This will create a so called shallow copy, that is, the copy which is only one level deep independant of the old object. This should be enough for the purpose of creating a new object. If then you want to futher change some nested keys, read the <em>Update</em> section below.</p><h3><strong>UPDATE</strong></h3><p>To update the array you also use the spread operator:</p><pre><strong>const </strong>updatedArray = [...oldArray, <strong>&#39;d&#39;</strong>]</pre><p>To add a new key to the object, or to change the existing key use the same approach:</p><pre><strong>const </strong>updatedObject = {...oldObject, <strong>newOrExistingKey</strong>: <strong>&#39;</strong>newValue<strong>&#39;</strong>}</pre><p>But updating the key of a deeply nested object can be tricky. With our example above of the 3 level deep <strong>nestedObject</strong> it will look like this:</p><pre><strong>const </strong>updatedObject = {<br>  ...nestedObject,<br>  <strong>key1</strong>: {<br>    ...nestedObject.<strong>key1</strong>,<br>    <strong>key2</strong>: {<br>      ...nestedObject.<strong>key1</strong>.<strong>key2</strong>,<br>      <strong>key3</strong>: <strong>&#39;</strong>newValue<strong>&#39;<br>    </strong>}<br>  }<br>}</pre><p>Alternatively, you can use Lodash to Deep Copy the original object and then change the single property:</p><pre><strong>const </strong>clonedObject = <strong>_.cloneDeep</strong>(nestedObject)<br>clonedObject.<strong>key1</strong>.<strong>key2</strong>.<strong>key4 </strong>= <strong>&#39;</strong>newValue<strong>&#39;</strong></pre><h3>DELETE</h3><p>Delete<strong> </strong>operations are a bit more complex. To delete something from the array you should use the filter function. In the example below we remove value<strong> ‘a’ </strong>and the <strong>third element</strong> form the myArray</p><pre><strong>const </strong>myArray = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br>myArray.<strong>filter</strong>((element, index) <strong>=&gt;</strong> element !== <strong>&#39;</strong>a<strong>&#39; </strong>&amp;&amp; index !== 2 )<br>// =&gt; [ &#39;b&#39;, &#39;d&#39; ]</pre><p>Or the same with Lodash</p><pre><strong>_.filter</strong>(myArray, (element, index) =&gt; element !== <strong>&#39;a&#39; </strong>&amp;&amp; index !== 2)</pre><p>To delete some key(e.g. <strong>key1</strong>) from the object, spread operator comes to help us again:</p><pre><strong>const</strong>{key1, ...modifiedObject} = myObject</pre><p>Or the same with Lodash:</p><pre><strong>const </strong>modifiedObject = <strong>_.<em>omit</em></strong>(newObject, <strong>&#39;key2&#39;</strong>)<br></pre><p>Deleting the nested key with JavaScript can be tricky but as far as REST API is concerned, deleting the key is the same as assigning it the <strong><em>undefined </em></strong>value. So you can use the same tools as in the <em>Update </em>section or use the Lodash <em>omit</em> helper which can delete the nested keys as well.</p><h3><strong>Object &lt; — &gt; Array Transformations</strong></h3><p>Now let’s have some real fun. Backend guys are not always nice. They may send you the array of objects while you want the object with the element’s IDs as the keys or the other way round. You may try to negotiate with them but it may be easier to except the reality and transform what you received from backend to what you need in frontend.</p><p>Let’s say we received the nested object like this:</p><pre><strong>const </strong>objectToTransfer = {<br>  <strong>a</strong>: {<strong>name</strong>: <strong>&#39;</strong>Mary<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Poppins<strong>&#39;</strong>, <strong>age</strong>: 40},<br>  <strong>b</strong>: {<strong>name</strong>: <strong>&#39;</strong>John<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Smith<strong>&#39;</strong>, <strong>age</strong>: 35},<br>}</pre><p>But we want the array of objects like this:</p><pre><strong>const </strong>sortedArray = [<br>  { <strong>key</strong>: b, <strong>name</strong>: <strong>&#39;</strong>John<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Smith<strong>&#39;</strong>, <strong>age</strong>: 35 },<br>  { <strong>key</strong>: a, <strong>name</strong>: <strong>&#39;</strong>Mary<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Poppins<strong>&#39;</strong>, <strong>age</strong>: 40 }<br>]</pre><p>Why we may want this? Because we want to sort the objects by age. We can achieve it by this magic expression:</p><pre><strong>const </strong>sortedArray = <strong><em>Object</em></strong>.entries(objectToTransfer)<br>  .map(([ key, value ]) <strong>=&gt;</strong> ({key, ...value}))<br>  .sort((a,b) =&gt; <strong>a</strong>.age - <strong>b</strong>.age)</pre><p>If you do not need the <strong>keys </strong>to be part of the object, you can get away with the simpler expression:</p><pre><strong><em>Object</em></strong>.values(objectToTransfer).sort((a,b) =&gt; <strong>a</strong>.age - <strong>b</strong>.age)<br>// =&gt; [<br>  { name: &#39;John&#39;, surname: &#39;Smith&#39;, age: 35 },<br>  { name: &#39;Mary&#39;, surname: &#39;Poppins&#39;, age: 40 }<br>]</pre><p>This simpler result can be achieved by Lodash as well:</p><pre><strong>const </strong>TransferredArray = <strong>_.values</strong>(objectToTransfer)<br><strong>const </strong>sortedArray = <strong>_.<em>sortBy</em></strong>(TransferredArray, <strong>&#39;</strong>age<strong>&#39;</strong>)</pre><p>There is the option to chain the functions in Lodash but it requires extra effort that are probably not justified in this example. You may get more info in the <a href="https://lodash.com/docs/4.17.15#chain"><em>Lodash docs.</em></a></p><p>Now let’s see how to make the reverse transformation from an array to an object. To do this we first need to decide what our key will be. In the example below we obviously pick the value of ID as a key. So we have the array:</p><pre><strong>const </strong>arrayToTransfer = [<br>  {<strong>id</strong>: <strong>&#39;</strong>a<strong>&#39;</strong>, <strong>name</strong>: <strong>&#39;</strong>Mary<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Poppins<strong>&#39;</strong>, <strong>age</strong>: 40},<br>  {<strong>id</strong>: <strong>&#39;</strong>b<strong>&#39;</strong>, <strong>name</strong>: <strong>&#39;</strong>John<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Smith<strong>&#39;</strong>, <strong>age</strong>: 35}<br>]</pre><p>And we want the object:</p><pre><strong>const </strong>objectWeWant = {<br>  <strong>a</strong>: { <strong>name</strong>: <strong>&#39;</strong>Mary<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Poppins<strong>&#39;</strong>, <strong>age</strong>: 40 },<br>  <strong>b</strong>: { <strong>name</strong>: <strong>&#39;</strong>John<strong>&#39;</strong>, <strong>surname</strong>: <strong>&#39;</strong>Smith<strong>&#39;</strong>, <strong>age</strong>: 35 }<br>}</pre><p>And the magic transformation is done with the help of the <strong>reduce </strong>function:</p><pre><strong>const </strong>objectWeWant = arrayToTransfer.<strong>reduce</strong>((result, {id, ...rest}) <strong>=&gt;</strong> ({...result, [id]: rest}), {} )</pre><p>Don’t worry if it does not make sense to you right away. Reduce function is considered to be one of the most complex one in Array operations. I will leave it to you to figure out how it works. If you do — congratulations. You are now a JavaScript Ninja:)</p><p>If you don’t really feel comfortable with it, there is a help coming from Lodash again:</p><pre><strong>const </strong>objectWeWant = <strong>_.<em>keyBy</em></strong>(arrayToTransfer, &#39;id<strong>&#39;</strong>)</pre><p>Why do you need to transfer an array to an object? The main use case is to easily refer to the nested object by ID. If you don’t want to bother with this transformation you can still use the <strong>find </strong>function for the same purpose like this:</p><pre><strong>const </strong>objectByID = arrayToTransfer.<strong>find</strong>(obj <strong>=&gt;</strong> obj.<strong>id </strong>=== <strong>&#39;</strong>a<strong>&#39;</strong>)</pre><p>Or with Lodash helper:</p><pre>const objectByID = <strong>_.<em>find</em></strong>(arrayToTransfer, {<strong>id</strong>: &#39;a&#39;})</pre><p>Now you have the tools you need to effectively read, process or send data to/from REST API. If you think I missed some essential piece of information, please feel free to comment.</p><p>Now to the question I mentioned in the beginning. To lodash or not to lodash?</p><p>That should depend on your level of JS skills. The less dependencies your app has, the faster it works and downloads, which also means the better SEO rating. But Lodash takes care of all the edge cases for you and makes it much safer to play with arrays and objects. After all, the properly working app is still better than the fast but buggy app. So assess your JS skills and make the decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3b59a73b618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise React in 2020]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/enterprise-react-in-2020-78155bc99259?source=rss-bbeb4f18218d------2"><img src="https://cdn-images-1.medium.com/max/2600/1*RDC8V8hAvYT2PEudgTAtaA.png" width="2799"></a></p><p class="medium-feed-snippet">In my previous article published about a year ago I presented the React tech stack which I called Enterprise React. It is the opinionated</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/enterprise-react-in-2020-78155bc99259?source=rss-bbeb4f18218d------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/enterprise-react-in-2020-78155bc99259?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/78155bc99259</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Fri, 13 Dec 2019 08:50:14 GMT</pubDate>
            <atom:updated>2019-12-15T20:56:58.620Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Enterprise React in 2018–2019]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@vialus/enterprise-react-in-2018-2019-ae6c80c03f1?source=rss-bbeb4f18218d------2"><img src="https://cdn-images-1.medium.com/max/2600/1*WZ_AgKx58_nnbApsurTKkA.jpeg" width="2799"></a></p><p class="medium-feed-snippet">Note: The updated version of Enterprase React 2020 is now published</p><p class="medium-feed-link"><a href="https://medium.com/@vialus/enterprise-react-in-2018-2019-ae6c80c03f1?source=rss-bbeb4f18218d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vialus/enterprise-react-in-2018-2019-ae6c80c03f1?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae6c80c03f1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 09:55:40 GMT</pubDate>
            <atom:updated>2019-12-13T08:52:56.574Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Breaking out of the Matrix with React Portals and Mutation Observer]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@vialus/breaking-out-of-the-matrix-with-react-portals-and-mutation-observer-b35b8d977235?source=rss-bbeb4f18218d------2"><img src="https://cdn-images-1.medium.com/max/1600/1*RQRXzC4umJ6tNvPdIH66yQ.jpeg" width="1600"></a></p><p class="medium-feed-snippet">The primary role of React is to build a self-contained application or so-called SPA (Single Page Application) that manages its own state&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@vialus/breaking-out-of-the-matrix-with-react-portals-and-mutation-observer-b35b8d977235?source=rss-bbeb4f18218d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@vialus/breaking-out-of-the-matrix-with-react-portals-and-mutation-observer-b35b8d977235?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35b8d977235</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[portal]]></category>
            <category><![CDATA[mutationobserver]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Wed, 30 May 2018 13:59:07 GMT</pubDate>
            <atom:updated>2018-05-30T13:59:07.808Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Real-time data with redux-saga event channels and socket.IO]]></title>
            <link>https://javascript.plainenglish.io/real-time-data-with-redux-saga-event-channels-and-socket-io-ad6e64dbefd9?source=rss-bbeb4f18218d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6e64dbefd9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Viacheslav Luschinskiy]]></dc:creator>
            <pubDate>Thu, 23 Nov 2017 20:32:28 GMT</pubDate>
            <atom:updated>2019-12-18T20:28:09.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SK-wb5zDu0yFioWXqzb7dg.jpeg" /></figure><h3>Intro</h3><p>There is a bunch of tutorials about dealing with real-time data in react/redux applications. They usually show how to make a simple chat app and lack production ready features for real-time data management required in the business apps.</p><p>Majority of the business apps use socket to receive the real-time data while upstream requests go via standard REST API therefore there is no send option in the code you will see below. But once you understand how it works you can easily add this functionality.</p><p>Today there are two main options for real-time data apps:</p><p>1. Ready-made Google firebase database</p><p>2. Custom backend based on socket.io library</p><p>You can start pretty fast with the firebase but your customization options will be limited. With the second option you can do much more.</p><p>If you apt more to the second option keep reading on.</p><h3>Basics</h3><p>Your main challenges with the real-time data will most likely be like these:</p><p>1. Your React/Redux application may look architecturally perfect but as soon as you try to incorporate the real-time data, it may start falling apart</p><p>2. In classical REST API if a server is down you get a 500 error and can show a friendly message to your user. With real-time API you may not receive anything either due to a server being down or because you just do not have any new data. So, the connection monitoring becomes more complicated and important.</p><p>Luckily, we have the redux-saga and its cool feature known as eventChannels along with forks, delays, race and other functions that altogether help us to build the robust real-time data app.</p><p>If you want just to see a working example fell free to jump right into the source code <a href="https://github.com/slava-lu/saga-socket-example">https://github.com/slava-lu/saga-socket-example</a></p><p>Otherwise read below some explanation what the example app does. You have to know the redux and redux-saga basics.</p><p>There is a take function in redux-saga which is usually used to listen to the redux actions and do some stuff based on the action type. But this take function can also be used to listen to the so-called channels.</p><p><strong>const </strong>payload = <strong>yield </strong>take(channel);</p><p>The channel is constructed with another function with the standard signature that you need just to take from the redux-saga doc (or my example). That signature uses the eventChannel redux-saga function that does the trick.</p><pre><strong>const </strong>createSocketChannel = socket =&gt; eventChannel((emit) =&gt; {<br> <strong>const </strong>handler = (data) =&gt; {<br> emit(data);<br> };<br> socket.on(<strong>‘newTask’</strong>, handler);<br> <strong>return </strong>() =&gt; {<br> socket.off(<strong>‘newTask’</strong>, handler);<br> };<br> });<br> </pre><p>Since you want your socket channel to be created only when the connection to the server is successful you need to wrap you socket.on event listener into the Promise since the redux-saga works with Promises rather than with callbacks.</p><p>Taking it all together your code may look like this.</p><pre><strong> const </strong>socketServerURL = <strong>‘http://localhost:3000&#39;</strong>;<br> <strong>let </strong>socket;<br> <br> <em>// wrapping function for socket.on<br> </em><strong>const </strong>connect = () =&gt; {<br> socket = io(socketServerURL);<br> <strong>return new </strong>Promise((resolve) =&gt; {<br> socket.on(<strong>‘connect’</strong>, () =&gt; {<br> resolve(socket);<br> });<br> });<br> };<br> <br> <em>// This is how a channel is created<br> </em><strong>const </strong>createSocketChannel = socket =&gt; eventChannel((emit) =&gt; {<br> <strong>const </strong>handler = (data) =&gt; {<br> emit(data);<br> };<br> socket.on(<strong>‘newTask’</strong>, handler);<br> <strong>return </strong>() =&gt; {<br> socket.off(<strong>‘newTask’</strong>, handler);<br> };<br> });<br> <br> <em>// saga that listens to the socket and puts the new data into the reducer<br> </em><strong>const </strong>listenServerSaga = <strong>function</strong>* () {<br> <br> <em>// connect to the server<br> </em><strong>const </strong>socket = <strong>yield </strong>call(connect);<br> <br> <em>// then create a socket channel<br> </em><strong>const </strong>socketChannel = <strong>yield </strong>call(createSocketChannel, socket);<br> <br> <em>// then put the new data into the reducer<br> </em><strong>while </strong>(<strong>true</strong>) {<br> <strong>const </strong>payload = <strong>yield </strong>take(socketChannel);<br> <strong>yield </strong>put({type: ADD_TASK, payload});<br> }<br> };</pre><p>We could have stopped here as this is all you need apart from the basic react/redux/saga setup to get the real-time data from your socket server.</p><p>But…</p><h3>Going to Production</h3><p>But there is much more you need to do to put it into production:</p><p>1. Listen to the disconnect and reconnect events</p><p>2. Open and close the channel by the button click or in the component lifecycle functions</p><p>3. Wait for the connection timeout to know if a server is up or down (there is no 500 error)</p><p>4. Make sure your saga will automatically receive the data when the server goes up again</p><p>5. Put all this connection info into the reducer for further processing</p><p>To wire all this up you need to understand the redux-saga good enough. At least you have to know the difference between call and fork, all and race, take and takeEvery, as well as to understand how to cancel tasks.</p><p>So, if you want to master the redux-saga and real-time data management open the redux-saga docs and my example app and become a redux-saga ninja :)</p><p>You may find the full code here <a href="https://github.com/slava-lu/saga-socket-example">https://github.com/slava-lu/saga-socket-example</a></p><p>To play with this example app you need to:</p><p>1. Run yarn in both Client and Server folders to install node_modules</p><p>2. Turn on socket server by running node ./index.js in the Server folder</p><p>3. Launch the client app by running yarn start in the Client folder and point your browser at <a href="http://localhost:8080/">http://localhost:8080</a></p><p>If you’ve done everything right you should see this screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*OPHwxbf4Q29m1tRtsbUGyA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6e64dbefd9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/real-time-data-with-redux-saga-event-channels-and-socket-io-ad6e64dbefd9">Real-time data with redux-saga event channels and socket.IO</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>