<?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 Robert Rutenge on Medium]]></title>
        <description><![CDATA[Stories by Robert Rutenge on Medium]]></description>
        <link>https://medium.com/@robertrutenge?source=rss-1de49f475cd8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*r4oCTrWdejhmJxb2.</url>
            <title>Stories by Robert Rutenge on Medium</title>
            <link>https://medium.com/@robertrutenge?source=rss-1de49f475cd8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 05:26:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robertrutenge/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[Building Authentication API using Node , express and JWT .]]></title>
            <link>https://robertrutenge.medium.com/building-authentication-api-using-node-express-and-jwt-e0c05496b501?source=rss-1de49f475cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0c05496b501</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Robert Rutenge]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 04:01:01 GMT</pubDate>
            <atom:updated>2020-09-10T05:16:13.213Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Authentication API using Node , express and JWT .</h3><p>In this tutorial , we will create a REST API from scratch using Nodejs and express , validate the data submitted and secure the endpoints via JSON Web Token (JWT) . We will also use MongoDB / Mongo Atlas to store our data .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*wR5MK3CJZW3xma-hAo0BtA.jpeg" /></figure><p>The code for this tutorial can be found on github , see below ;-</p><p><a href="https://github.com/robertrutenge/express-auth-api.git">https://github.com/robertrutenge/express-auth-api.git</a></p><p>Without further due , let’s get started as we have a lot of code to write . First thing first , you need to have node installed on your machine , create a project folder and open terminal then inside your project folder let’s fire up our app by initializing our node project .</p><pre>npm init -y</pre><p>Note : We have use -y to accept all default options</p><p>Let’s install expressjs</p><pre>npm install express </pre><p>Now , let’s create index.js file on a root of our project as its our main entry point . Inside index.js file we will create a basic express app as below; —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48f53c4b6b0d9c24d9afbd400641b457/href">https://medium.com/media/48f53c4b6b0d9c24d9afbd400641b457/href</a></iframe><p>Now let’s proceed , and run our app</p><pre>node index.js</pre><p>You should see a message <strong><em>Auth APIs listening on port 3000 </em></strong>on your console log . If you try to access the url , localhost:3000 now you should get <strong><em>Cannot GET / </em></strong>as no route has been created yet .</p><p>Let’s add start script inside package.json file so as we don’t have to launch our app every time by typing node index.js . remove the test script and add start script as below ;-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e1b110425004968a44d964f105c4737/href">https://medium.com/media/3e1b110425004968a44d964f105c4737/href</a></iframe><p>To avoid restarting our app everytime we make changes to it , we are going to use nodemon so as the refresh happens automatically . go on install nodemon as a dev dependency .</p><pre>npm i -D nodemon</pre><p>Modify the start script to use nodemon</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46d76d864694d9d3b3b01d47d19c962a/href">https://medium.com/media/46d76d864694d9d3b3b01d47d19c962a/href</a></iframe><p>Now let’s start our app , we should be good to go .</p><pre>npm start</pre><p>Now let’s start building by creating an endpoint for registration . Let’s start with the basic implementation ;-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8ff49be87b507a8ebadd2f2b0633c5/href">https://medium.com/media/3d8ff49be87b507a8ebadd2f2b0633c5/href</a></iframe><p>As you can see on line 6 above , we have implemented a simple route for registration . Go on open postman and test going to localhost:3000/register and you should see Register returned as a response . That means so far so good .</p><p>Now for simplicity , we will collect 3 fields during regisrtation , namely person’s full name , email and password .</p><p>On the register route , lets change it to return our data by changing line 7 to</p><pre>res.send(req.body)</pre><p>Now , Let’s make that call on postman like below ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzzeUCxJtgLsA_yYMkA4iw.png" /></figure><p>If we make a call we can see it does not return anything , if you try to console.log req.body you will find that it’s undefined . This is because we need to add body parser middleware to have access to our req.body , let’s go ahead and do that .</p><p>Above our register route function add below code;</p><pre>app.use(express.json());</pre><p>The above basically tells express to recognize the incoming request object as JSON Object . Now if we run again our register endpoint , we should be able to get response .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsme0vSklIiKdFMiyV9K0w.png" /></figure><p>Now that we can get our response , let’s take some time to add some validation on the data submitted . As of now if you send empty data or remove one of the fields , it should work fine .</p><p>We are going to use a package called joi for validation . Go on and install it .</p><pre>npm install @hapi/joi</pre><p>Then we will import in our main file and add validation as below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b07d9e17088b154511c018f779d676ee/href">https://medium.com/media/b07d9e17088b154511c018f779d676ee/href</a></iframe><p>As seen above , from line 8 , we have created a schema and add validation rules for our fields . If you now try for example to submit password less than 6 characters you should get an error or submit invalid email .</p><p>Since when we get an error , we are sending the whole object as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ec0d376edbbdf325a64ff350f041946/href">https://medium.com/media/0ec0d376edbbdf325a64ff350f041946/href</a></iframe><p>We will use object destructuring to get the error object , and then return 400 with the appropriate message which is under details . change the register route to below ; —</p><pre>app.post(“/register”, (req, res) =&gt; {</pre><pre>const { error } = registrationSchema.validate(req.body);</pre><pre>if (error) return res.status(400).send(error.details[0].message);</pre><pre>res.send(“Registered!”);</pre><pre>});</pre><p>If you run again , you will see 400 error with just a message , and if all validations have passed you will see “Registered!” message .</p><p>Now that we are done with validations , let’s go on and persist our data to the Database . As mentioned before , we are going to use MongoDB as our database , so go on to MongoDB Atlast , register or login .</p><p>Once login , click Build a new cluster on top right , choose a free tier with MO Sandbox which is free forever . Once everything is setup , go under the newly created cluster , and click connect , where you will have options on how to connect to your cluster as below ;-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEErrJgl9g-sknh1rA7frw.png" /></figure><p>Choose Connect Your Application , in which you will presented with connection string . Keep that connection string as we will use it in our application . And that’s it for Mongo Atlas .</p><p>Now to connect to MongoDB in our application , we will need to install a package called mongoose .</p><pre>npm install mongoose</pre><p>Now import mongoose and establish a connection</p><pre>const mongoose = require(“mongoose”);</pre><pre>mongoose.connect(“mongodb+srv://your_connection_string”,<br>{useNewUrlParser: true, useUnifiedTopology: true });</pre><p>Once connected , let’s go and create our schema as below :-</p><pre>const UserSchema = new mongoose.Schema({</pre><pre>fullname: { type: String, required: true },</pre><pre>email: { type: String, required: true },</pre><pre>password: { type: String, required: true }</pre><pre>});</pre><pre>const User = mongoose.model(“user”, UserSchema);</pre><p>Once our schema is set , we use mongoose.model() function to create our model as shown above .</p><p>Once our model is ready , the last step is to persist the data sent via post , see the update register route below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db5198fe3febf7776e24c4e33f5742f4/href">https://medium.com/media/db5198fe3febf7776e24c4e33f5742f4/href</a></iframe><p>On the above , we have created an instance of our User model and then use the save method to persist the data . Note we have changed our function to async as we need to wait for some DB operations to end like persisting the date .</p><p>If you go on . and run the register endpoint on postman , you should be able to get a response with our newly persisted user object with an extra _id field . Also if you go to your cluster , then collections , you should see a newly created users collection with one document that has the data submitted .</p><p>Another thing before we start to login , we can see that the password is saved as plain text , we can change this by using a package called bcryptjs which will allow us to encrypt our password . go on and install it .</p><pre>npm i bcryptjs</pre><p>Let’s change the register function , and encrypt our password .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44d3357eed75c91fd3d4df8adbaf8f9e/href">https://medium.com/media/44d3357eed75c91fd3d4df8adbaf8f9e/href</a></iframe><p>On line 4 , we are using salting to create a secure password . Now if you call the register endpoint again , the password should be encrypted .</p><p>One last thing , to ensure best practice , we will also check if email exists on registering as well as try and catch the model.save() just incase anything went goes wrong .</p><pre>const emailExists = await User.findOne({ email: req.body.email });</pre><pre>if (emailExists) return res.status(400).send(“Email already exists”);</pre><p>Also</p><pre>try {</pre><pre>const savedUser = await user.save();</pre><pre>res.send(savedUser);</pre><pre>} catch (error) {</pre><pre>res.status(400).send(error);</pre><pre>}</pre><p>Our final register route should be as below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea00a4e7cfc808b3aa4898ed2c1e23f5/href">https://medium.com/media/ea00a4e7cfc808b3aa4898ed2c1e23f5/href</a></iframe><p>Now , let’s go and continue with login . To avoid this tutorial being too long as it’s already is , go ahead and validate the login credentials as its the same process we did with register .</p><p>I went along and added the login code as below , it should be straight forward :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b862b07d035b38c99ea86aaff215040a/href">https://medium.com/media/b862b07d035b38c99ea86aaff215040a/href</a></iframe><p>Now if email and password is correct , you are going to see “Logged In” message . Note that for the purpose of this tutorial , the email and password not correct messages are different but ideally and for security purpose they should be the same like “Email or password incorrect” .</p><p>Great ! now let’s finalize the last part for securing our endpoints . for this we are going to use a package called jsonwebtoken , let’s install it .</p><pre>npm i jsonwebtoken</pre><p>As usual , we will import it .</p><pre>const jwt = require(“jsonwebtoken”);</pre><p>From here , we are going to create a token when a user logs in using jwt.sign() method which accepts a payload as a first parameter and a secret key which ideally you will store it in your environment variables .</p><pre>const token = jwt.sign(</pre><pre>{ _id: user._id, email: user.email },</pre><pre>“YOUR_SECRET_KEY”</pre><pre>);</pre><pre>res.header(“auth_token”, token).send(token);</pre><p>Now once logged in , we will add auth_token on response header so as it can be used to check authorization of various resources . Our Final login should look like below : —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adff0c2ee7eabd0b44edb76b8b4d0e26/href">https://medium.com/media/adff0c2ee7eabd0b44edb76b8b4d0e26/href</a></iframe><p>One last thing before we call it off . Now that we have generate a token we need to learn how to secure our private routes .</p><p>We will secure our routes by creating a middleware which will first check if auth_token is present in our request and if not will throw 401 , unauthorized error . It will then use jwt.verify() method to verify the token and serve our request if passed . see below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633e7cfd36c63edc4420e4be765a8186/href">https://medium.com/media/633e7cfd36c63edc4420e4be765a8186/href</a></iframe><p>Note . jwt.verify() will decrypt our token and give us a payload that we passed during the process of generating the token using jwt.sign() . If you have the token you can also decrypt it manually by going to <a href="https://jwt.io/">https://jwt.io/</a> and paste your encoded token as below for my scenario .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWQuI7BoFQEtJHzNCaZbbw.png" /></figure><p>Now , let’s use our middleware . We will create a simple get endpoint , let’s call it dashboard and it will contain very secure data that a user needs to be authenticated to access it .</p><pre>app.get(“/dashboard”, (req, res) =&gt; {</pre><pre>res.send(“VERY CONFIDENTIAL DATA”);</pre><pre>});</pre><p>If you run this on postman now , you should get “VERY CONFIDENTIAL DATA” . Now let’s go on and secure it . Its as simple as adding our middleware function on our get route .</p><pre>app.get(“/dashboard”, tokenVerifier, (req, res) =&gt; {</pre><pre>res.send(“VERY CONFIDENTIAL DATA”);</pre><pre>});</pre><p>Now if you run it on postman , you should get access denied message !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKihDhHjOsnBTSUUr3vQLw.png" /></figure><p>Go on postman and call login endpoint again , get the returned auth_token . Return back to dashboard endpoint , create auth_token header on postman with the generated token during login as its value and then call it again .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zAHbB8zoBJl15zNpjIYKw.png" /></figure><p>You can now see “VERY CONFIDENTIAL DATA” .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FpcLjAwQeLt4vIhRyiA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ftv4-haha-hurra-pcLjAwQeLt4vIhRyiA&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FpcLjAwQeLt4vIhRyiA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/36530b3db833a74f98b750fe77c1110f/href">https://medium.com/media/36530b3db833a74f98b750fe77c1110f/href</a></iframe><p>That’s it folks . Hope this helps you in one way or the other , don’t hesitate to reach out incase of any comments .</p><figure><a href="https://www.buymeacoffee.com/waJApDX"><img alt="" src="https://cdn-images-1.medium.com/max/214/1*wAFIUHAMV3RcENcPh4lTMA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0c05496b501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Progressive Web App (PWA) with React]]></title>
            <link>https://robertrutenge.medium.com/building-progressive-web-app-pwa-with-react-53a03c54009c?source=rss-1de49f475cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a03c54009c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Robert Rutenge]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 10:25:16 GMT</pubDate>
            <atom:updated>2020-09-10T05:13:33.214Z</atom:updated>
            <content:encoded><![CDATA[<p>According to comScore Mobile Metrix on time spend on Mobile app vs Web App , 13 % were spent on mobile web and 87% on mobile apps.</p><p>Progressive Web Apps (PWAs) is the technology that was designed to bridge this gap by giving web apps ability to behave like mobile apps , ability such as making them installable .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*idOBa09Y1TPVSI28Pjx7hg.jpeg" /></figure><p>In this tutorial , we will use New York Times API to create a PWA app that will display a list of most popular stories from New York Times . Below is what we will be creating ;-</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FW3UEUXiMZN0RWvHMyX%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FW3UEUXiMZN0RWvHMyX%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FW3UEUXiMZN0RWvHMyX%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="228" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d789d3f4b95a4c5252d170588e2212/href">https://medium.com/media/b5d789d3f4b95a4c5252d170588e2212/href</a></iframe><p><strong>Github Link for final project</strong> : <a href="https://github.com/robertrutenge/nytimes-pwa">https://github.com/robertrutenge/nytimes-pwa</a></p><p>Go on and register for an account via <a href="https://developer.nytimes.com/">https://developer.nytimes.com/</a> , don’t worry it should take about 2 minutes to set everything up .</p><p>Once registered and logged in , click on the dropdown that has your email on the top right and selects apps then new app . Go on fill in the App Name and other fields . Once Created , you will see a section that has an API Key , go on copy that key somewhere as we will use it later to call our APIs .</p><p>One Done , let’s get started . Make sure you have Nodejs and create-react-app installed , from there create a new react application called nytimes-pwa by running the below command :</p><pre>create-react-app nytimes-pwa</pre><p>Let’s start building . go on to App.js file , remove logo import and on the header delete everything and add a title “New York Times “ . Go to App.css and modify .App-header class min-height to 10vh;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e461cf6964cf7a1ba1f2f4bd7dd05ef/href">https://medium.com/media/2e461cf6964cf7a1ba1f2f4bd7dd05ef/href</a></iframe><p>Now , let’s go on displaying our popular stories from New York Times . Go on and install axios as we will use it as our HTTP Client to call our APIs .</p><pre>npm install axios</pre><p>Under Src directory , let’s create a services folder and under it new file nytimesApi.js with below code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/091e331adda072cc5f6bb3c63f3eaa14/href">https://medium.com/media/091e331adda072cc5f6bb3c63f3eaa14/href</a></iframe><p>The code above should be straightforward , we use axios to call an API that will give us popular posts . Let’s go ahead and use getMostPopularStories() function in our App.js file and for now just display the titles as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f0b2042ca95989fed39ea9f0be64a5b/href">https://medium.com/media/3f0b2042ca95989fed39ea9f0be64a5b/href</a></iframe><p>From the above code , we used useState hook to declare our state called stories in which its default value is set to an empty array as shown on line 6 . we will use the useEffect hook to call our API and modify stories state to the response we get and finally display our fetched posts .</p><p>In case , you run in to this error</p><pre>Uncaught Error: Cannot find module ‘/Users/my-user/my/project-path/nytimes-pwa/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/slicedToArray’</pre><p>Just go ahead and install babel runtime</p><pre>npm add <a href="http://twitter.com/babel/runtime">@babel/runtime</a></pre><p>After this , let’s finalize displaying the stories by creating a story component that will display each story together with adding some styles .</p><p>To speed things up , i have gone ahead and add a Story Component together with the styling on app.css , go ahead and copy below code .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/640e1bfdbcc85261d9c53af3421b7d70/href">https://medium.com/media/640e1bfdbcc85261d9c53af3421b7d70/href</a></iframe><p>And then our &lt;Story&gt; component is as below :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e1ebc24c0fcee7203667d0ed57c7ae/href">https://medium.com/media/26e1ebc24c0fcee7203667d0ed57c7ae/href</a></iframe><p>Note from the above that we are using bootstrap and font-awesome to spice up our UI . so go on , and install them</p><pre>npm install bootstrap @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome</pre><p>And at last , our added styling on app.css file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2fc0140bc24e3fafdc101e60e278699/href">https://medium.com/media/c2fc0140bc24e3fafdc101e60e278699/href</a></iframe><p>If everything went OK , you should have similar screen as below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VW5xLUEnu1xrC_PzvxP8SA.png" /></figure><p>Now , let’s start what were here for , Progressive Web App (PWA) .</p><p>From the official PWA page on google developer page , The 3 factors that makes an APP PWA are :</p><ul><li><a href="https://developers.google.com/web/progressive-web-apps#reliable"><strong>Reliable</strong></a> — Load instantly and never show the downasaur (The game you enjoy playing on chrome while offline) , even in uncertain network conditions.</li><li><a href="https://developers.google.com/web/progressive-web-apps#fast"><strong>Fast</strong></a> — Respond quickly to user interactions with silky smooth animations and no janky scrolling.</li><li><a href="https://developers.google.com/web/progressive-web-apps#engaging"><strong>Engaging</strong></a> — Feel like a natural app on the device, with an immersive user experience.</li></ul><p>Before we start with pwa , go on and build our app</p><pre>npm run build</pre><p>We will use serve for launching our app , if its not installed , go ahead and install it .</p><pre>npm i serve</pre><p>Now go ahead and launch our web app using serve .</p><pre>serve -s build</pre><p>By default our web app will be served on port 5000 .</p><p>We will also be using google lighthouse under chrome dev tools to inspect how progressive our app is , go on and inspect our served web app , click the audit tab and click Run Audit at the bottom of the page .</p><ol><li><strong>Reliable</strong></li></ol><p>Let’s make our react app reliable and to do that , create-react-app already comes with a service worker that we need to register .</p><p>A service worker is a script that runs in the background to perform various tasks such as caching resources , handling network resources and storing content for offline use .</p><p>At the moment no service worker is registered as seen when you use chrome dev tools to inspect under application then service workers , you will see nothing at the moment .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkL-7zSte-Pu_7JZRr3vGw.png" /></figure><p>Also if you go to network tab , then offline , and refresh the page , you will see downasaur , go on and play the game a little bit as we are about to register our service worker to resolve that .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNimNnphePGMjHMdIFnPwQ.png" /></figure><p>Let’s register a service worker , go to index.js file in the src directory of our file and change serviceWorker.unregister() to serviceWorker.register() . Note that the serviceWorker is imported from serviceWorker.js that comes when we created our app .</p><p>Go on and build and serve the app again .</p><p>Now if you refresh the browser and inspect again you will see our newly registered service worker . At this moment our web app is cached by service worker as stated on the console with the below message ;</p><blockquote>This web app is being served cache-first by a service worker. To learn more, visit <a href="https://bit.ly/CRA-PWA">https://bit.ly/CRA-PWA</a></blockquote><p>Also , if you go to network and turn on offline , you can see that downasaur did not appear , and the page is served with the header and no content as network request to fetch the content failed but all static files has been cached and rendered in the browser .</p><p>It’s up to you to play with this offline capability and see to what extent you want to cache the static files like images for offline capability .</p><p><strong>2. Engaging</strong></p><p>create-react-app comes with a web manifest file called manifest.json file residing in the public directory .</p><p>From MDN</p><blockquote>The web app manifest provides information about an application (such as name, author, icon, and description) in a JSON text file. The purpose of the manifest is to install web applications to the homescreen of a device, providing users with quicker access and a richer experience.</blockquote><p>Go on and change the short_name and name to reflect our app .</p><p>short_name is intended to be about 12 characters and is typically displayed in App launcher and new tab page . It is an optional field and if not supplied , the name will be used .</p><p>name is the primary identifier of the app and is a required field. It will typically displayed on Install dialog , Extension management UI and chrome web store .</p><p>Now Build and serve our web app again</p><p>How about our app being installable ? No worries , if your using chrome version 70 and above , open our app and then chrome options settings , the three dots on the top right then next to find , you will see an option to install our app to chrome apps as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBJGXreIFLeannZ-nYqgpA.png" /></figure><p>Once done , your app will be launched , or you can open it via chrome or via</p><pre>chrome://apps/</pre><p><strong>3 . Fast</strong></p><p>According to google study , 53% of web users will abandon the site if it takes more than 3 seconds to load . Let’s test how fast our app is performed generally after building and serving it . Doing a final audit on my end i get below results ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsik-irkJj_2VFQ_AS0_5A.png" /></figure><p>I hope , this gave you some insight on how to take advantage of PWA when creating a new react app or optimizing your existing react apps .</p><figure><a href="https://www.buymeacoffee.com/waJApDX"><img alt="" src="https://cdn-images-1.medium.com/max/214/1*7cbokaiyPfGVtq_6bM6cbw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a03c54009c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using React Hooks in Redux Application]]></title>
            <link>https://robertrutenge.medium.com/using-react-hooks-in-redux-application-a5f0ce78a798?source=rss-1de49f475cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f0ce78a798</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Robert Rutenge]]></dc:creator>
            <pubDate>Tue, 08 Oct 2019 09:57:09 GMT</pubDate>
            <atom:updated>2020-09-10T05:12:37.383Z</atom:updated>
            <content:encoded><![CDATA[<p>Most developers don’t like redux for so many reasons , but the introduction of react hooks in react 16.8 will some how reduce the pain of using redux .</p><p>Among the biggest pain is the wiring that needs to happen when you want to connect a component to the redux store , all these Higher-Order Component usage , the connect , mapStateToProps and mapDispatchToProps make it quite cumbersome .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*4khgguJQPxUwKSZH3URgQQ.png" /></figure><p>Let’s begin , we are going to create a ToDo Application in which you can add a todo , toggle the state of a task as well as delete a todo .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXf0jzKdNPRft11iHKp%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FXf0jzKdNPRft11iHKp&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXf0jzKdNPRft11iHKp%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="251" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8e405237d7950818fee9a5fcf124bea/href">https://medium.com/media/a8e405237d7950818fee9a5fcf124bea/href</a></iframe><p>The Final code for this tutorial can be found here <a href="https://github.com/robertrutenge/todo-redux-hooks">https://github.com/robertrutenge/todo-redux-hooks</a></p><p>Let’s Start . We are going to use create-react-app to bootstrap our new application , let’s call it todos</p><pre>create-react-app todos</pre><p>Let’s cd to our application and start it by running</p><pre>npm start</pre><p>We are going to use bootstrap to give some styling to our components , so let’s install it first ;-</p><pre>npm install bootstrap</pre><p>Let’s start with the easy stuffs first , creating our components , on our todo application we are going to have 2 components , one for inputing new todo item and another one to display the list of todos together with an option of marking wether a task is complete or not and another option to delete a todo .</p><p>Delete everything on App.js file and add the two components . Don’t forget to add bootstrap.css file in the index.js file or app.js file .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32119a49231cf9e87b1c49c98500a036/href">https://medium.com/media/32119a49231cf9e87b1c49c98500a036/href</a></iframe><p>Let’s go ahead and create the two components . Under the scr folder , create a new components folder with two files ToDoInput.js and ToDoList.js .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aadde58c269e5e294c586855f24c55fb/href">https://medium.com/media/aadde58c269e5e294c586855f24c55fb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b43790247a56a1cc5917c13af432426/href">https://medium.com/media/5b43790247a56a1cc5917c13af432426/href</a></iframe><p>The code above , should be straightforward , and it should give something like below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*FljxCIth4zfdXzSlW0GFhA.png" /></figure><p>Since , we will be using redux as our state management library , lets go ahead and install redux and react-redux .</p><pre>npm install redux react-redux</pre><p>Once Installed , Let’s create our redux store , go on and create store folder inside it , index.js file with the code below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b1a3fe910ea8a2373685afb81c6aad5/href">https://medium.com/media/8b1a3fe910ea8a2373685afb81c6aad5/href</a></iframe><p>The createStore() function from redux will need a reducer , so let’s go on and create a reducers folder inside store folder and inside it , index.js file with the below code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a75c1dd18ecd6d8881a9ddcaa9ccf1f/href">https://medium.com/media/6a75c1dd18ecd6d8881a9ddcaa9ccf1f/href</a></iframe><p>As we all know in redux , the only way to communicate with our store is through action , so let’s go on and add our action creators . Inside store folder create actions folder and inside it , index.js file .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9829894ef5d30382c187c0e08dd58cd6/href">https://medium.com/media/9829894ef5d30382c187c0e08dd58cd6/href</a></iframe><p>Now we should be good to go with the redux part , the only missing part is connection the store to our application . We will do that by using a Provider from react-redux . Let’s change our App.js file by wrapping it with our provider and supplying the store we just created .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/976656a8b33480bd779b0eafa1602024/href">https://medium.com/media/976656a8b33480bd779b0eafa1602024/href</a></iframe><p>Finally , we manage to connect the store and everything should work as expected . If you have Redux Dev Tools installed , and inspect our application , you should be able to see our store with a todos empty array as below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXFVd_MhxPOdIPt-2lCREQ.png" /></figure><p>Now , on to the final part . Using React Hooks to our redux application . Hooks allow access of state and lifecycle methods in stateless / functional components . Since react-redux v7.1.0 , some hooks APIs have been introduced as an alternative to HOC connect() function that’s normally used when you want to connect to the store .</p><p>The most used react redux hooks APIs are <strong>useSelector()</strong> that allows the access of our redux store data and <strong>useDispatch() </strong>that returns a reference to the dispatch function .</p><p>We will use the two APIs for adding , toggling and deleting our todos .</p><p>Let’s start with adding todos , let’s change our &lt;ToDoInput /&gt; . Before that make sure you install uuid which we will use to generate a random id .</p><pre>npm install uuid</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/547e8040787bb2c802d628eb35f04d9a/href">https://medium.com/media/547e8040787bb2c802d628eb35f04d9a/href</a></iframe><p>So , explaining what happened above . We first use useState hook from react for storing our state which is todo . setToDo is the same as this.setState() method in stateful component and it does just That .</p><p>Note that , useState() passed a parameter that defines initial state , and in this new hook implementation the state does not necessarily needs to be an object compared to the stateful component implementation . In our case its an empty string .</p><p>So , on the input we have added the value property that will hold the current state , and the onChange method that will use setTodo() to change the value of our state .</p><p>The onSubmit method calls the submit function that will in turn calls addToDo method that will use UseDispatch() hook from react-redux to dispatch an action in our case addToDoAction() .</p><p>If all goes well , you should be able to add your todo with no error and when inspect in our redux store you should see the newly added todos .</p><p><strong>Displaying the todos</strong></p><p>Now let’s finalize our application , by displaying the todos and adding functionality to toggle the state of the todo task as well as delete the todo .</p><p>Modify &lt;ToDoList/&gt; component as below :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31ca0ad88b90c5312c929e265bf7e441/href">https://medium.com/media/31ca0ad88b90c5312c929e265bf7e441/href</a></iframe><p>From the above implementation , useSelector hook was used to get the current state in our store for our todos . The useSelector is equivalent to mapStateToProps argument in the connect function .</p><p>The toggle and delete actions should be as the addToDo we saw earlier .</p><p>Once you start to use the hooks , you will start to realize how efficient and effective they are . Remember the hooks did not come to replace anything , so no need to rewrite your projects to use them , you can just introduce them in new development as they don’t have any breaking changes .</p><figure><a href="https://www.buymeacoffee.com/waJApDX"><img alt="" src="https://cdn-images-1.medium.com/max/214/1*7cbokaiyPfGVtq_6bM6cbw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f0ce78a798" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Start a react project without create-react-app]]></title>
            <link>https://robertrutenge.medium.com/start-a-react-project-without-create-react-app-9af418e44277?source=rss-1de49f475cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9af418e44277</guid>
            <category><![CDATA[webpack4]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[babel-7]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Robert Rutenge]]></dc:creator>
            <pubDate>Tue, 24 Sep 2019 10:46:15 GMT</pubDate>
            <atom:updated>2021-02-11T18:35:54.651Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s be honest , boilerplates are great and create-react-app was one of the most awaited command as it allows you to start coding straight away without having to worry about all configurations that goes on .</p><p>But sometimes it’s good to understand how all the pieces connect , so as you can have a better understanding of how react works .</p><p>Let’s get started , go to the folder where you want to run your project and create a new directory called created-react-app .</p><p>Make sure you have nodejs and npm installed . run below command to make sure node and npm are installed</p><pre>node -v<br>npm -v</pre><p>Let’s start our project but initializing a node project with the below command :</p><pre><em>npm init -y </em></pre><p><em>*The -y allows us to start a node project with the default configurations .</em></p><p><strong>1 . Install babel</strong></p><p>React uses JSX as its markup language . babel is the javascript compiler that will translate JSX to ordinary javascript .</p><p>Babel also allows us to use future versions of ECMA Script (ES2015 and beyond) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*dLv3viuecOZR-87dRry9XQ.jpeg" /></figure><p>Okay , we get it . Let’s start using babel by adding babel core to our project</p><pre><em>npm i @babel/core</em></pre><p>For it to be useful , babel would require some configurations to be added for supporting various libraries and functionalities . We will add the following plugins :-</p><p><strong><em>The react preset</em></strong></p><ul><li>This allows conversion of jsx to plain javascript .</li></ul><pre>npm i --save-dev @babel/preset-react</pre><p><strong><em>The env preset</em></strong></p><ul><li>This allows support for ES2015 (ES6) features .</li></ul><pre><em>npm i --save-dev @babel/preset-env</em></pre><p>For our newly added presets to work in our project , we need to create a babel configuration file (.babelrc) on the root of our project and add the presets inside that file .</p><p><em>.babelrc</em></p><pre>{</pre><pre>&quot;presets&quot;: [&quot;@babel/preset-react&quot;, &quot;@babel/preset-env&quot;]</pre><pre>}</pre><p>Let’s us test if our new babel presets were applied , create app.js file , and add a simple function that uses ES6 Arrow function to test if our babel configurations works as expected !</p><pre>const app = () =&gt; {<br>    console.log(“Hello World from created react app “);<br>};</pre><p>To run this file with babel , we will need to install babel-cli .</p><pre>npm install --save-dev @babel/cli</pre><p>@babel/cli includes an executable called babel that you can run with npx.</p><pre>npx babel app.js</pre><p>Running the command the output becomes</p><pre>var App = function App() {<br> console.log(“Hello World from JSX”);<br>};</pre><p>You can see some changes , our arrow function has been replaced with function .and const keyword which was new in ES6 was replaced by var .</p><p>Let’s now test if our react-preset works as expected , change app.js file as below</p><pre>const App = () =&gt; {</pre><pre>&lt;h1 className=”Hello”&gt;Hello World&lt;/h1&gt;;</pre><pre>};</pre><p>Run</p><pre>npx babel app.js</pre><p>The output will be as below</p><pre>var App = function App() {<br> React.createElement(“h1”, {<br> className: “Hello”<br> }, “Hello World”);<br>};</pre><p>As we can see , preset-react converted our h1 tag to a call to React.createElement() .</p><p><strong>2 . Install react</strong></p><p>Now that we already configured babel , its time to jump in to the good stuffs .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*OMwUSmVixo0F8gJfSh2ONA.jpeg" /></figure><p>Go on an install react and react-dom so as we can create our first react component :-)</p><pre>npm install react react-dom</pre><p>ReactDOM connect react and the DOM where in most cases it will be used only once during mounting with ReactDOM.render() function .</p><p>To make this tutorial as relevant as possible , let us copy the folder structure of create react app</p><pre>created-react-app/<br>   README.md <br>   node_modules/  <br>   package.json   <br>   public/     <br>      index.html     <br>      favicon.ico  <br>   src/     <br>      App.css    <br>      App.js     <br>      App.test.js    <br>      index.css     <br>      index.js     <br>      logo.svg</pre><p>We won’t have all the files as create-react-app but only the ones necessary to run a react project .</p><p>Let’s start with the index.html file , create a public folder and inside it add index.html file with the following content :-</p><pre>&lt;!DOCTYPE html&gt;</pre><pre>&lt;html lang=&quot;en&quot;&gt;</pre><pre>&lt;head&gt;</pre><pre>    &lt;meta charset=&quot;utf-8&quot; /&gt;</pre><pre>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;</pre><pre>    &lt;title&gt;Created React App&lt;/title&gt;</pre><pre>&lt;/head&gt;</pre><pre>&lt;body&gt;</pre><pre>    &lt;noscript&gt;You need to enable JavaScript to run this app.   &lt;/noscript&gt;</pre><pre>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><pre>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><p>All of our source files will reside inside a src directory . Create a src directory and inside it let’s create our first file , index.js .</p><p>we will use ReactDOM.render() to mount react inside a parent container with id of root as below ;</p><pre>import React from “react”;<br>import ReactDOM from “react-dom”;<br>import App from “./app”;</pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(“root”));</pre><p>Let us end with our last file , app.js which will only display a message “Hello World from created react app “ from the screen .</p><pre>const App = () =&gt; {<br>    &lt;h1&gt;Hello World from created react app&lt;/h1&gt;;<br>};<br>export default App;</pre><p>Now everything should be fine , the last thing is to launch our app . For that we will use Webpack .</p><p><strong>3 . Webpack</strong></p><p>Here comes another headache to most newbies even experienced developers .</p><p>Webpack is a build tool that allows us to take to take all of our project assets and turns them in to a production ready bundle .</p><p>The files that our project uses are called modules and we tell webpack to load the modules when we configure our project .</p><p>The famous “Convention over Configuration” should apply here as this process can be very tedious .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ovd4jGTL1Uz296WBDbRodw.png" /></figure><p>But hey , wait a minute , going through webpack documentation for the latest version (Version 4) , here is what you can find</p><blockquote>Since version 4.0.0, webpack does not require a configuration file to bundle your project. Nevertheless, it is <a href="https://webpack.js.org/configuration">incredibly configurable</a> to better fit your needs.</blockquote><p>Okay! , fingers crossed . let us proceed . We need to install the following npm packages before we proceed .</p><p><strong>Webpack</strong></p><p>This is module bundler for our application . As the application gets bigger , webpack will intelligently bundle our files in to a single file .</p><pre>npm install -D webpack</pre><p><strong>Webpack-cli</strong></p><p>As its name , its a cli tool that will allows us to run webpack commands .</p><pre>npm install -D webpack-cli</pre><p><strong>Let’s build our project</strong></p><p>Now that we have webpack and webpack-cli installed , its time to build our project to production . Note below if we choose to proceed without creating a webpack config file .</p><blockquote>Out of the box, webpack won’t require you to use a configuration file. However, it will assume the entry point of your project is src/index and will output the result in dist/main.js minified and optimized for production.</blockquote><p>Open package.json file under script add a build script for webpack</p><pre>{<br>   &quot;scripts&quot;:{<br>       &quot;build&quot; : &quot;webpack&quot;<br>   }<br>}</pre><p>Run the build command</p><pre>npm run build</pre><p>If you run the command , you will see this error</p><pre>Module parse failed: Unexpected token (5:16)<br>You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See <a href="https://webpack.js.org/concepts#loaders">https://webpack.js.org/concepts#loaders</a><br>| import App from &quot;./app&quot;;<br>| <br>&gt; ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));<br></pre><p>This happens because a loader is missing in our webpack config . Webpack loaders helps with tasks such as perform transformations on files and loading of files and images . For example React uses JSX which a browser does not understand , so it needs to be transformed to plain javascript for it to run on a browser .</p><p>Go on and install babel-loader which is a webpack helper package that allows transpiling of JavaScript files using <a href="https://github.com/babel/babel">Babel</a> and <a href="https://github.com/webpack/webpack">webpack</a>.</p><pre>npm install -save-dev babel-loader</pre><p>Once installed , create webpack configuration file inside our project directory and save it as webpack.config.js . Inside our config file let’s add babel-loader with below configurations :</p><pre>module.exports = {<br>    module: {<br>        rules: [<br>            test: /\.js$/,<br>            exclude: /(node_modules)/,<br>            use: {<br>            loader: &quot;babel-loader&quot;,<br>            options: {<br>                presets: [<br>                    &quot;@babel/preset-react&quot;, <br>                    &quot;@babel/preset-env&quot;<br>                ]}<br>              }<br>         }]<br>      }<br>};</pre><p>Now run npm run build , and it should compile succesfully . Go on and open a dist folder and you will see only one file , main.js which is our bundle file .</p><p>For our application to run we need index.html file , so the next thing to do is to tell webpack to include index.html file on our build as well as including our bundled file (main.js) inside the script tag of index.html .</p><p>There are two ways of doing this , the first one is manually by adding index.html file inside a dist folder as below</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot; /&gt;     &lt;title&gt;Created React App&lt;/title&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>If you go on and click the index.html file , you should be able to open the page as below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEiiO4JvEQCR8BNS3ZqOig.png" /><figcaption>Screen showing our index.html file</figcaption></figure><p>Another option , which is the ideal one is to use a plugin . go on and install html-webpack-plugin . This plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags.</p><pre>npm i --save-dev html-webpack-plugin</pre><p>After installing , just add the plugin to your webpack config as follows:</p><pre>const HtmlWebpackPlugin = require(&quot;html-webpack-plugin&quot;);<br>module.exports = {<br>    module: {<br>        rules: [<br>           {<br>               test: /\.js$/,<br>               exclude: /(node_modules)/,<br>               use: {<br>                    loader: &quot;babel-loader&quot;,<br>                    options: {<br>                    presets: [<br>                        &quot;@babel/preset-react&quot;, <br>                        &quot;@babel/preset-env&quot;<br>                     ]}<br>                   }<br>             }]},<br>    plugins: [<br>        new HtmlWebpackPlugin(<br>            {<br>                template: &quot;./public/index.html&quot;<br>             })<br>          ]};</pre><p>Now , if you build again , you should see the same result as the first screen .</p><p><strong>Running the Dev Server</strong></p><p>Another awesome feature of webpack is that it allows you to set up a development server that will automatically reload your project when things change .</p><p>To achieve that , we are going to install another plugin , called webpack-dev-server .</p><pre>npm install --save-dev webpack-dev-server</pre><p>Add the dev server config to our webpack.config.js file</p><pre>var path = require(&#39;path&#39;);<br><br>module.exports = {<br>  //...<br>  devServer: {<br>    contentBase: path.join(__dirname, &#39;dist&#39;),<br>    compress: true,<br>    port: 9000<br>  }<br>};</pre><p>After that , in our package.json file , and a start script that uses our dev server .</p><pre>&quot;scripts&quot;: { <br>   &quot;build&quot;: &quot;webpack-dev-server&quot;<br> }</pre><p>Note : If your running webpack version 5 replace webpack-dev-server with webpack serve as below</p><pre>&quot;scripts&quot;: { <br>   &quot;build&quot;: &quot;webpack serve&quot;<br> }</pre><p>After that , go ahead and run</p><pre>npm start</pre><p>If everything goes well , you will see something like below on your command window , go ahead and navigate to <a href="http://localhost:9000/">http://localhost:9000/</a> , and you should be able to see the screen with “Hello World from created react app” message .</p><pre>ℹ ｢wds｣: Project is running at <a href="http://localhost:9000/">http://localhost:9000/</a><br>ℹ ｢wds｣: webpack output is served from /<br>ℹ ｢wds｣: Content not from webpack is served from /Users/my-path/created-react-app/dist<br>ℹ ｢wdm｣: Hash: d74d0e81a0e2c1beb23e</pre><p>Last thing is to test if our automatic reload feature works , go ahead and edit app.js file and change the message to”Hello World from react ” and the page should automatically reload .</p><p>Let’s end here as its already long content to digest , what you should explore after this is how to use webpack to also load css and images and also do code splitting , subject which i will cover in coming articles .</p><p>That’s it folks . Hope you have learned something and don’t hesitate to give feedback on this article.</p><figure><a href="https://www.buymeacoffee.com/waJApDX"><img alt="" src="https://cdn-images-1.medium.com/max/214/1*7cbokaiyPfGVtq_6bM6cbw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9af418e44277" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>