<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Joshua Medina</title>
    <description>The latest articles on DEV Community by Joshua Medina (@jnmedinadev).</description>
    <link>https://dev.to/jnmedinadev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1065703%2Fbfbe7e96-8714-410d-bd5f-eea8bf1dd7ce.jpeg</url>
      <title>DEV Community: Joshua Medina</title>
      <link>https://dev.to/jnmedinadev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jnmedinadev"/>
    <language>en</language>
    <item>
      <title>A Guide to Setting Up Passport.js Google Strategy with PostgreSQL, Express, React, and Node.js</title>
      <dc:creator>Joshua Medina</dc:creator>
      <pubDate>Mon, 28 Aug 2023 23:34:17 +0000</pubDate>
      <link>https://dev.to/jnmedinadev/a-guide-to-setting-up-passportjs-google-strategy-with-postgresql-express-react-and-nodejs-2e7d</link>
      <guid>https://dev.to/jnmedinadev/a-guide-to-setting-up-passportjs-google-strategy-with-postgresql-express-react-and-nodejs-2e7d</guid>
      <description>&lt;p&gt;The purpose of this article is to provide the reader with a quick guide to setting up &lt;a href="https://www.passportjs.org/"&gt;Passport.JS&lt;/a&gt; Google Strategy (OAuth2) with their React frontend and PostgreSQL backend to maintain a user session and authentication. While recently working on my latest web application, I noticed there are very few articles or videos that guides a developer on how to implement Passport specifically with React and PostgreSQL. We will use &lt;a href="https://www.npmjs.com/package/pg-pool"&gt;pg-pool&lt;/a&gt; to manage the connection between our express backend and our database. This article assumes the reader has a basic understanding of React and Express, and has already setup their credentials with &lt;a href="https://console.developers.google.com/"&gt;Google Developers Console&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;Once you have created your &lt;em&gt;react&lt;/em&gt; app, and established your &lt;em&gt;express&lt;/em&gt; server, &lt;code&gt;cd&lt;/code&gt; to your root folder for your server (I named mine 'server') open your terminal and run this command to install the required packages:&lt;br&gt;
&lt;code&gt;npm install passport, passport-google-oauth20, pg, express-session&lt;/code&gt;&lt;br&gt;
Additionally, you may want to install 'cors' to assist with any cors-error messages you might get, and 'dotenv' to establish your environment variables you don't want accessible to the public: &lt;br&gt;
&lt;code&gt;npm install cors, dotenv&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Backend
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Setup &amp;amp; Initialization
&lt;/h3&gt;
&lt;h4&gt;
  
  
  DOTENV
&lt;/h4&gt;

&lt;p&gt;After installing the required packages, let's setup our 'dotenv' file. At the top-level of our server, create a dotenv file and name it like so: &lt;code&gt;.env&lt;/code&gt;. Make sure to include this file in your &lt;code&gt;.gitignore&lt;/code&gt; file. This is where we will store our sensitive information. Inside this file should be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;.env

CLIENT_ID="FROM YOUR GOOGLE DEVELOPERS CONSOLE"
CLIENT_SECRET="FROM GOOGLE DEVELOPERS CONSOLE"
CLIENT_CALLBACK_URL="FROM GOOGLE DEVELOPERS CONSOLE"
CLIENT_URL="URL of your frontend. i.e. localhost:3000"
COOKIE_SECRET="ANY STRING YOU WANT. USED TO VERIFY COOKIE CREDENTIALS"
NODE_ENV="production"
DB_USER="name of user in your PostgreSQL database: normally defaults to 'postgres'"
DB_PASSWORD="The password you established for your database. You might not have set one up"
DB_HOST="The name of the host domain: i.e., localhost"
DB_PORT="The port your database uses: normally defaults to '5432'" **This is NOT the port your server 'listens' on**
DB_NAME="The name you have given your database"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whenever we need to use a variable from this file, we will require it in like so: &lt;code&gt;require("dotenv").config();&lt;/code&gt; &lt;/p&gt;

&lt;h4&gt;
  
  
  PG-POOL
&lt;/h4&gt;

&lt;p&gt;Next we will setup our connection to our database using the variables in our dotenv file. I created a folder called 'db' then a file within called 'index.js', but you may use whatever you like. Establish your pool connection like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;db&amp;gt;index.js

require("dotenv").config();
const { Pool } = require("pg");

const pool = new Pool({
  database: process.env.DB_NAME,
  port: process.env.DB_PORT,
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
 });

module.exports = pool;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Passport Google Strategy Setup
&lt;/h4&gt;

&lt;p&gt;Next, create a file to hold our setup for Passport (I named mine 'auth.js'). This file will get fairly large fairly quick depending on the information you would like passport to maintain regarding your user. For the purposes of this article, I will keep it as simple as possible. Keep in mind you may need to adjust some variables to better suit your needs. At the top of the file, require in the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;auth.js

const passport = require("passport");
const { Strategy: GoogleStrategy } = require("passport-google-oauth20");
require("dotenv").config();
const pool = require("./db/index.js");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You may want to 'require' in any helper functions you'd like to use to further authenticate a user to your database, such as checking if the user google email is already registered with your app. Next, still inside 'auth.js', we will create a new instance of 'passport' and 'GoogleStrategy':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;auth.js
//---required in variables---//

passport.use(
  new GoogleStrategy(
    {
     clientID: process.env.CLIENT_ID,
     clientSecret: process.env.CLIENT_SECRET,
     callbackURL: process.env.GOOGLE_CALLBACK_URL,
    },
    async(accessToken, refreshToken, profile, done) =&amp;gt;{
     const userData = profile._json;
     let user = {};
     try {
      const currentUserQuery = await pool.query("SELECT * FROM users WHERE google_id = $1", [userData.sub]);
      if(currentUserQuery.rows.length &amp;gt; 0){
      user = {
       user_id: currentUserQuery.rows[0].user_id,
       username: currentUserQuery.rows[0].username,
       };
      } else {
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Quick explanation of what's happening in this first portion of the strategy. We initialized a new GoogleStrategy, passed in our credentials, then began our async function, which takes 4 parameters: accessToken, refreshToken, profile, done. We then grabbed the information from the google response and stored it in a variable called userData. We created a variable called user and set it equal to an empty object. We did this so we could determine what information to store in session. We then queried our database to determine if the user is already registered and, if so, store in our 'user' object the information we want kept in session: user_id, username. Let's continue where we left off, our &lt;code&gt;else&lt;/code&gt; logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//---Continuing logic---//
} else {
  const newUser = await pool.query("INSERT INTO users (username, email, firstName, lastName, img, googleID)
VALUES ($1, $2, 3$, $4, $5, $6) RETURNING user_id, username", [userData.name, userData.email, userData.given_name, userData.family_name, userData.picture, userData.sub]);
  user = {
   user_id: newUser.rows[0].user_id,
   username: newUser.rows[0].username
  }
}
done(null, user);
} catch (error) {
  done(error, false, error.message)
  }
 }
));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this portion of our logic, we're stating that if the user is not already in our database, to insert their information and return only the information we want stored in session, again: user_id, username. &lt;code&gt;done(null, user)&lt;/code&gt; is a callback function passport uses to determine when a block of logic is complete, whether from error or otherwise. The first parameter is used if there is an error, the second parameter is used to store the session information. Next, we have to serialize and deserialize. Still inside the same file, under &lt;code&gt;passport.use&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//---Continuing from previous code block---//
passport.serializeUser((user, done) =&amp;gt; {
  done(null, user);
});

passport.deserializeUser((user, done) =&amp;gt; {
  done(null, user)
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a simplified call for serialization and deserialization of user. &lt;strong&gt;NOTE: Passport stores in session whatever is contained in the deserializeUser done() callback function as req.user. So if you want to update your session object, here is where it must be done.&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Server.js
&lt;/h4&gt;

&lt;p&gt;Now that we have setup pool, dotenv, and passport, we can move onto our server's main file (I named mine server.js). First, we will &lt;code&gt;require&lt;/code&gt; in the needed modules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;server.js

const express = require("express");
const session = require("express-session");
const cors = require("cors");
const passports = require("passport");
require("dotenv").config();
require("./auth.js")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we'll initialize, then utilize a router. &lt;strong&gt;NOTE: The order in which we initialize our packages (express, session, passport, etc.) is important.&lt;/strong&gt; Still within server.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;server.js

//---required modules---//

const app = express();

app.use(
 cors({
  credentials: true,
  origin: process.env.CLIENT_URL,
 })
);

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static("public"));

app.use(
 session({
  secret: [process.env.COOKIE_SECRET],
  cookie: {
   secure: process.env.NODE_ENV === "production" ? "true" : "auto",
   sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
   maxAge: 30 * 24 * 60 * 60 * 1000,
  },
  resave: false,
  saveUninitialized: false,
 })
);

app.use(passport.session());
app.use(passport.authenticate("session"));

const authRouter = require("./routes/authRouter.js);
app.use("/auth", authRouter);

app.listen(8080, () =&amp;gt; {
 console.log("Listening on port: 8080")
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Setting up Authentication Route
&lt;/h4&gt;

&lt;p&gt;In the previous section, at the end of the code block, we setup a route to handle &lt;code&gt;"/auth"&lt;/code&gt;. Now we will setup the actual router. We could have done everything inside our server.js file, but best practices dictate we maintain a separation of concerns. I created a folder called routes, then created a file named 'authRouter.js'. You may call it whatever you like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server&amp;gt;routes&amp;gt;authRouter.js

const express = require("express");
const router = express.Router();
const passport = require("passport");
require("dotenv").config();

router.get("/google",
 passport.authenticate("google", { scope: "profile", })
);

router.get("/google/callback", 
 passport.authenticate("google", { session: true }), 
 (req, res) =&amp;gt; {
  res.redirect(`${process.env.CLIENT_URL}`);
});

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Frontend
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Login Component
&lt;/h3&gt;

&lt;p&gt;For simplicities sake, I will just use a very basic login component that returns a &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; with a &lt;code&gt;&amp;lt;button&amp;gt;&lt;/code&gt;. You will need to provide your own styles, and imports as your app requires. Your environment variables may be different as well. I created a folder in my 'src' folder named 'pages' and a react file named 'Login.js'. The &lt;code&gt;baseApiURL&lt;/code&gt; will be where your server is 'listening'. In this article, the server is listening on localhost:8080.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;client&amp;gt;src&amp;gt;pages&amp;gt;Login.js

import { baseApiURL } "../App.js";

export default function Login(){

const handleOAuth = () =&amp;gt; {
 window.open(`${baseApiURL}/auth/google`, "_self");
};

return (
 &amp;lt;div&amp;gt;
  &amp;lt;button onClick={handleOAuth}&amp;gt;
   Login with Google
  &amp;lt;/button&amp;gt;
 &amp;lt;/div&amp;gt;
 )
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the user clicks the button, a new window will appear (the reason for "_self"), asking the user to login with their google credentials. If they accept, they will be redirected according to the redirect we setup in our authRouter.&lt;/p&gt;

&lt;h3&gt;
  
  
  Managing Authentication
&lt;/h3&gt;

&lt;p&gt;You now have everything setup for Google Authentication using Passport! Last thing to remember: whenever your frontend React app needs to verify the authentication of the user, whether in a &lt;code&gt;GET&lt;/code&gt; or &lt;code&gt;POST&lt;/code&gt; request, you must include &lt;code&gt;credentials: "inlcude",&lt;/code&gt; like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//---POST Route---//

fetch(`${baseApiURL}${routeNeedingAuth}`, {
 credentials: "include",
 method: "POST",
 headers: {
  "Content-Type": "application/json",
 }, 
 body: JSON.stringify("DATA BEING SENT"),
})

//---GET Route---//

fetch(`${baseApiURL}${routeNeedingAuth}`, {
 credentials: "include",
})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Remember: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Your web application's needs and variables may vary. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The order in which you initialize the modules in your server matters.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Routes needing authentication after the user has logged in requires &lt;code&gt;credentials: "include",&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you would like a visual guide, checkout this &lt;a href="https://www.youtube.com/playlist?list=PLBieMfwfePY8wOyuGlANlcmmyPgQ4HLVe"&gt;YouTube Playlist&lt;/a&gt; by Lester Fernandez. He does a phenomenal job explaining the steps. Happy Coding! &lt;/p&gt;

</description>
      <category>react</category>
      <category>postgres</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Express Middleware as the Nightclub Bouncer: Ensuring VIP Access to Your App</title>
      <dc:creator>Joshua Medina</dc:creator>
      <pubDate>Sat, 05 Aug 2023 09:26:57 +0000</pubDate>
      <link>https://dev.to/jnmedinadev/express-middleware-as-the-nightclub-bouncer-ensuring-vip-access-to-your-app-25j7</link>
      <guid>https://dev.to/jnmedinadev/express-middleware-as-the-nightclub-bouncer-ensuring-vip-access-to-your-app-25j7</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. &lt;br&gt;
 -&lt;a href="https://expressjs.com/en/guide/writing-middleware.html"&gt;Expressjs.com&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Welcome to the blog post where we're going to unravel the intriguing world of middleware and how it transforms into the "bouncer" of your web application! Imagine your web app is like a bustling nightclub, and you, as the app owner, want to ensure that only VIP guests (authenticated users) get access to the exclusive party. That's where middleware steps in, just like a vigilant bouncer stationed at the club's entrance. In this post, we'll explore how middleware can serve as a security guard, managing who gets in (authenticated users) and who gets turned away (unauthorized visitors).&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Middleware?
&lt;/h2&gt;

&lt;p&gt;In the context of web development using frameworks like ExpressJS, middleware is a special type of function that sits between the incoming request from the client and the response sent back by the server. It has the power to intercept and process the request before it reaches the main route handler. This clever functionality allows developers to add extra features, security measures, or custom logic to their applications without cluttering the main code. This will also help developers maintain DRY code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Authentication Middleware
&lt;/h2&gt;

&lt;p&gt;Authentication middleware is used to check whether a user is authenticated (logged in) before granting access to certain routes or resources. When a user makes a request to a protected route, the authentication middleware is executed before the route handler. The middleware examines the request to determine whether the user is authenticated. If the user is authenticated, the middleware allows the request to proceed to the route handler. If the user is not authenticated, the middleware may redirect the user to a login page, return an error response, or take other appropriate actions.  Before we look at actually creating the &lt;code&gt;authMiddleware&lt;/code&gt;, we need to briefly discuss the different authentication strategies.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authentication Strategies
&lt;/h3&gt;

&lt;p&gt;Although there are several strategies to use when authenticating, such as &lt;a href="https://www.oauth.com/oauth2-servers/differences-between-oauth-1-2/"&gt;OAuth2&lt;/a&gt;, or &lt;a href="https://www.passportjs.org/"&gt;Passport&lt;/a&gt;, for simplicity we will use the &lt;a href="http://expressjs.com/en/resources/middleware/session.html"&gt;express-session&lt;/a&gt; (session). Please refer to the link on how to properly setup session in your environment.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create Authentication Middleware
&lt;/h2&gt;

&lt;p&gt;First, we need to create a middleware function that will handle the authentication logic. The middleware function typically checks for the presence of authentication data, in our case: session. As I quoted from &lt;a href="https://expressjs.com/en/guide/writing-middleware.html"&gt;expressjs.com&lt;/a&gt; earlier, middleware functions have access to the &lt;code&gt;req&lt;/code&gt;, &lt;code&gt;res&lt;/code&gt; objects as well as the &lt;code&gt;next&lt;/code&gt; function. The &lt;code&gt;next&lt;/code&gt; function (called 'next' by convention)(&lt;a href="https://expressjs.com/en/guide/writing-middleware.html"&gt;expressjs.com&lt;/a&gt;) is a callback provided by Express that allows a middleware function to pass control to the &lt;em&gt;next&lt;/em&gt; middleware or route handler in the chain. When called, it passes the request to the &lt;em&gt;next&lt;/em&gt; function and continues the execution flow through the middleware stack. If &lt;code&gt;next&lt;/code&gt; is not called within a middleware, the request might hang, and subsequent middleware or route handlers won't be executed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in a separate location: ../middlewares/authentication.js

const authMiddleware = (req, res, next) =&amp;gt; {
 // Check if the user has an active session
 if (req.session &amp;amp;&amp;amp; req.session.user) {
  next();
 } else { 
  //User does not have an active session, redirect to login page
  res.redirect('/login');
 }
};

module.exports = authMiddleware;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This middleware checks if the user has an active session (indicating that they are authenticated) before allowing access to protected routes. If the user doesn't have an active session, they are redirected to a login page. In this example, we assume that the &lt;code&gt;req.session.user&lt;/code&gt; object contains user information after a successful login. When the user logs in with the correct credentials, we would set &lt;code&gt;req.session.user&lt;/code&gt; with the necessary user data (e.g. username, user_id) during the login process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementing the Middleware
&lt;/h2&gt;

&lt;p&gt;Now that we have our bouncer created, we next need to include it in any and all routes that require a VIP badge. First, let's take a look at the syntax for a standard &lt;code&gt;GET&lt;/code&gt; request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const router = express.Router();

router.get('/VIPdata', (req, res) =&amp;gt; {
 res.render('vipData');
});
module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code sets up an ExpressJS server that listens for &lt;code&gt;GET&lt;/code&gt; requests on the URL route &lt;code&gt;'/VIPdata'.&lt;/code&gt; When a request is made, the server responds by rendering the 'vipData' page. Anyone will be able to walk into the VIP section and view your data!&lt;/p&gt;

&lt;p&gt;Now, let's look at the syntax for adding our middleware. Although we could have used a nameless function inside the &lt;code&gt;GET&lt;/code&gt; request, best practices for DRY code would be to establish a named function, then &lt;code&gt;require&lt;/code&gt; it in any routes that will need it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const router = express.Router();
const authMiddleware = require('../middlewares/authentication');

// Our middleware sits between the route, and the route logic
router.get('/VIPdata', authMiddleware, (req, res) =&amp;gt; {
 res.render('vipData');
});

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The route is now protected with our authentication middleware (imported as &lt;code&gt;authMiddleware&lt;/code&gt;) to ensure only authenticated users can access it. When a request is made to '/VIPdata', the server renders the 'vipData' view, allowing authenticated users to access the protected VIP data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion:
&lt;/h2&gt;

&lt;p&gt;In conclusion, we've journeyed into the fascinating realm of authentication middleware in ExpressJS, where we discovered the power of these "bouncers" guarding our web applications. Just like vigilant sentinels, authentication middleware ensures that only trusted users gain access to the exclusive parts of our application.  Armed with these valuable insights, we're now equipped to protect our web applications with confidence, allowing users to revel in the unique and personalized experiences they deserve. So go forth, embrace the power of authentication middleware, and let your Express applications shine with a heightened sense of security and user satisfaction!&lt;br&gt;
-Josh&lt;/p&gt;

</description>
      <category>database</category>
      <category>api</category>
      <category>backend</category>
      <category>express</category>
    </item>
    <item>
      <title>Conditional Rendering in React &amp;&amp; Build Dynamic User Interfaces</title>
      <dc:creator>Joshua Medina</dc:creator>
      <pubDate>Sat, 17 Jun 2023 08:54:43 +0000</pubDate>
      <link>https://dev.to/jnmedinadev/conditional-rendering-in-react-build-dynamic-user-interfaces-5a20</link>
      <guid>https://dev.to/jnmedinadev/conditional-rendering-in-react-build-dynamic-user-interfaces-5a20</guid>
      <description>&lt;p&gt;Conditional rendering plays a crucial role in building modern and interactive user interfaces in React. With the ability to selectively render components and content based on specific conditions, you can create dynamic UIs that adapt and respond to user interactions. In this blog post, we will explore various techniques and best practices to utilizing conditional rendering in React and unlock its full potential.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Conditional Rendering Basics
&lt;/h2&gt;

&lt;p&gt;In React, conditional rendering can be achieved using JavaScript expressions within JSX. Let's start with a simple example using &lt;code&gt;if/else&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Greeting({ isLoggedIn }) {
  if(isLoggedIn){
    return &amp;lt;h1&amp;gt;Welcome back!&amp;lt;/h1&amp;gt;;
  }else {
    return &amp;lt;h1&amp;gt;Please log in or sign up.&amp;lt;/h1&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the 'Greeting' component conditionally renders a different greeting to the users based on whether the prop 'isLoggedIn' is &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. Ternary Operator for Concise Rendering
&lt;/h2&gt;

&lt;p&gt;As with vanilla JavaScript, we can utilize a ternary operator to handle some of our conditional rendering in React, while being a bit more concise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Greeting({ isLoggedIn }) {
  return (
    &amp;lt;div&amp;gt;
      {isLoggedIn ? &amp;lt;h1&amp;gt;Welcome back!&amp;lt;/h1&amp;gt; : &amp;lt;h1&amp;gt;Please sign up or log in.&amp;lt;/h1&amp;gt;}
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the ternary operator eliminates the &lt;code&gt;if/else&lt;/code&gt; statements and makes the code more succinct and readable. &lt;/p&gt;

&lt;h2&gt;
  
  
  3. Logical &amp;amp;&amp;amp; Operator for Conditional Rendering
&lt;/h2&gt;

&lt;p&gt;Another approach to conditional rendering is using the logical &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator. The &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; allows you to conditionally render&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;...its(&lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;) right side if the left side (condition) is &lt;code&gt;true&lt;/code&gt;, or render nothing otherwise. -&lt;a href="https://react.dev/learn/conditional-rendering"&gt;React.dev&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Banner(){

const [isCartHovered, setIsCartHovered] = useState(false);

const toggleCart = () =&amp;gt; {
  setIsCartHovered(!isCartHovered);
};

return (
  &amp;lt;div&amp;gt;
    &amp;lt;button className="cartButton" 
      onMouseEnter={toggleCart}
      onMouseLeave={toggleCart}
    &amp;gt;
    Shopping Cart
    &amp;lt;/button&amp;gt;
    {isCartHovered &amp;amp;&amp;amp; &amp;lt;HoverCart /&amp;gt;}
  &amp;lt;/div&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example of the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator was taken directly from my &lt;a href="https://jnmedina32.github.io/E-Commerce-Store/"&gt;E-Commerce-Store&lt;/a&gt; application. The code allows users to preview the items in their cart by conditionally rendering the &lt;code&gt;&amp;lt;HoverCart /&amp;gt;&lt;/code&gt; component &lt;em&gt;only&lt;/em&gt; when &lt;code&gt;isCartHovered&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt;. The &lt;code&gt;isCartHovered&lt;/code&gt; is only &lt;code&gt;true&lt;/code&gt; when the user hovers over the cart button.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Switch Statements for Complex Conditions
&lt;/h2&gt;

&lt;p&gt;In certain scenarios where you have multiple conditions and need to render different components based on specific cases, using switch statements can provide a more organized approach. Let's take a look at an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function UserProfile({ userRole }) {
  switch (userRole) {
    case 'admin':
      return &amp;lt;AdminProfile /&amp;gt;;
    case 'manager':
      return &amp;lt;ManagerProfile /&amp;gt;;
    case 'employee':
      return &amp;lt;EmployeeProfile /&amp;gt;;
    default:
      return &amp;lt;GuestProfile /&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, the &lt;code&gt;UserProfile&lt;/code&gt; component renders different profiles based on the &lt;code&gt;userRole&lt;/code&gt; prop. By using switch statements, it becomes easier to handle various cases and maintain readable code.&lt;/p&gt;

&lt;p&gt;Switch statements are particularly useful when you have multiple conditions with different possible outcomes. They provide a clean and structured way to handle complex conditional rendering in your React components.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Conditional rendering is a powerful feature in React that enables the creation of dynamic and responsive user interfaces. By mastering techniques such as JavaScript expressions, the ternary operator, logical &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator, and switch statements, developers can build UIs that adapt and respond to specific conditions. Whether it's simple rendering, concise logic, handling conditional elements, or managing complex scenarios, understanding and applying these conditional rendering techniques will empower React developers to create engaging and interactive user interfaces with ease."&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>frontend</category>
      <category>react</category>
      <category>coding</category>
    </item>
    <item>
      <title>A Beginner's Guide to Regular Expressions Methods: Simplifying Syntax and Usage</title>
      <dc:creator>Joshua Medina</dc:creator>
      <pubDate>Fri, 05 May 2023 22:38:53 +0000</pubDate>
      <link>https://dev.to/jnmedinadev/a-beginners-guide-to-regular-expressions-methods-simplifying-syntax-and-usage-1jhl</link>
      <guid>https://dev.to/jnmedinadev/a-beginners-guide-to-regular-expressions-methods-simplifying-syntax-and-usage-1jhl</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text replace operations. A regular expression can be a single character, or a more complicated pattern." &lt;a href="https://www.w3schools.com/js/js_regexp.asp"&gt;-w3schools&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Regular expression (&lt;strong&gt;regex&lt;/strong&gt;) methods can be a powerful tool for developers, but they can also be daunting to understand and use. In this technical blog post, we will simplify the topic of regex methods used in JavaScript (&lt;strong&gt;JS&lt;/strong&gt;) by collating all the necessary information in one place. We will cover the basics of regular expression methods, including syntax, and some common use cases. This blog post is organized for quick reference about the &lt;em&gt;&lt;strong&gt;methods&lt;/strong&gt;&lt;/em&gt; usable with regex and sometimes utilizes regex syntax like &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags"&gt;flags&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags"&gt;character classes&lt;/a&gt;, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"&gt;assertions&lt;/a&gt;, and &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions"&gt;quantifiers&lt;/a&gt; to showcase the different ways the methods could be used. By the end of this post, you will have a comprehensive understanding of regular expression methods and be better equipped to use them in your own development projects.&lt;/p&gt;

&lt;h2&gt;
  
  
  -Methods-
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Regular expressions are used with the &lt;strong&gt;RegExp Object methods&lt;/strong&gt; &lt;code&gt;test()&lt;/code&gt; and &lt;code&gt;exec()&lt;/code&gt; and the &lt;strong&gt;String Object methods&lt;/strong&gt; &lt;code&gt;match()&lt;/code&gt;, &lt;code&gt;matchAll()&lt;/code&gt;, &lt;code&gt;replace()&lt;/code&gt;, &lt;code&gt;replaceAll()&lt;/code&gt;, &lt;code&gt;search()&lt;/code&gt;, and &lt;code&gt;split()&lt;/code&gt;. -&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#using_regular_expressions_in_javascript"&gt;MDN Web Docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  -Regular Expression Object Methods-
&lt;/h3&gt;

&lt;p&gt;The two methods we use on the regex object are &lt;code&gt;test()&lt;/code&gt; and &lt;code&gt;exec()&lt;/code&gt;. Regex methods are called on our RegExp Object and the parameter is the string we would like to search through: &lt;code&gt;regex.method(string)&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  -test() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;test()&lt;/code&gt; method returns a Boolean value: &lt;code&gt;true&lt;/code&gt; if the pattern is found or &lt;code&gt;false&lt;/code&gt; if the pattern is not found.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const regex = /pattern/;
const string1 = "This sentence contains the pattern";
const string2 = "This sentence does not contain it";

//When the pattern will be found
console.log(regex.test(string1)); //Expect: true


//When the pattern will not be found
console.log(regex.test(string2)); //Expect: false

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  -Common Use Case for test() Method-
&lt;/h5&gt;

&lt;p&gt;Two common use cases for the test() method are when you want to ensure that a user inputs a valid phone number(i.e. correct amount of digits) or a valid email address (i.e. contains an '@' or a '.com'). Let's examine checking the validity of a US phone number. The code to test for a valid United States phone number could look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const validUSNumberRegex = 
/^(\+?1[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$/;

//If the number is valid

let userInputNumber =  +1 333-333-4444;

console.log(validNumberRegex.test(userInputNumber));
//Expect: true

//If the number is NOT a valid US Number

let userInputNumber = +974 4444 4444;

console.log(validUSNumberRegex.test(userInputNumber));
//Expect: false

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a &lt;code&gt;true&lt;/code&gt; return, we could continue with the provided information as planned. With a &lt;code&gt;false&lt;/code&gt; return, we could instruct the user to please provide a correct US number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(validUSNumberRegex.test(userInputNumber) == true){
  //Save number for later use
  validPhoneNumbersArray.push(userInputNumber);
} else {
  //Request User to resubmit a correct US number
  alert("Please enter a valid US phone number.")
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  -exec() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;exec()&lt;/code&gt; method returns an array of information if the pattern is found: &lt;code&gt;['pattern', index: 'index found at', input: 'the string the pattern was found', groups: 'if the pattern belongs in a group']&lt;/code&gt;. The &lt;code&gt;exec()&lt;/code&gt; method returns &lt;code&gt;null&lt;/code&gt; if the pattern is &lt;em&gt;not&lt;/em&gt; found. The &lt;code&gt;exec()&lt;/code&gt; method is useful when you need to find the next match of a pattern within a string and you want to work with the individual match and its capturing groups before moving on to the next match. This method stores the index of the previous match, so when called again, will return the &lt;em&gt;next&lt;/em&gt; match in the string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const regex = /pattern/;
const string1 = "This sentence contains the pattern";
const string2 = "This sentence does not contain it";

// When the pattern will be found
console.log(regex.exec(string1)); 
/* Expect: [
'pattern', 
index: 27, 
input: 'This sentence contains the pattern', 
groups: undefined] 
*/

// When the pattern will NOT be found
console.log(regex.exec(string2)); //Expect: null

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  -Common Use Case for exec() Method-
&lt;/h5&gt;

&lt;p&gt;Let's say we have been tasked to compile all the email addresses that were submitted from a multitude of users. For example, hundreds of thousands of users have submitted messages that look something like: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hello, software developer. My name is John Wick. My email address is &lt;a href="mailto:JohnWick@Unbeatable.com"&gt;JohnWick@Unbeatable.com&lt;/a&gt;, my wife's email is &lt;a href="mailto:JohnWicksWife@beatable.com"&gt;JohnWicksWife@beatable.com&lt;/a&gt;, and my dog's email is &lt;a href="mailto:JohnWicksDog@theRealLoveInterest.com"&gt;JohnWicksDog@theRealLoveInterest.com&lt;/a&gt;. I am interested in joining your company because....&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;While you could read every single message and manually input the names and emails and any other pertinent information, it would be exponentially faster to use the &lt;code&gt;exec()&lt;/code&gt; method. Using capture groups in your regex would further allow you to breakdown the information you are retrieving. Here is a while loop that will grab all the emails, then further dissect the email using the 'groups' property from the &lt;code&gt;exec()&lt;/code&gt; method (let's assume the quote above has already been saved to the variable &lt;code&gt;userLetters&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const emailRegex = 
/(?&amp;lt;user&amp;gt;\w+[!#$%&amp;amp;'*+\-/=?^_`{|]{0,1}\w+)@(?&amp;lt;domain&amp;gt;[a-zA-Z]+[-.]?[a-zA-Z0-9]+)\.(?&amp;lt;top&amp;gt;[a-zA-Z]{2,3})/g;

let submittedEmails = [];
let match;

while((match = emailRegex.exec(userLetters)) !== null) {
  submittedEmails.push({
    'userEmail': match[0],
    'userName': match.groups.user,
    'domainName': match.groups.domain,
    'topDomain': match.groups.top
  })
}
console.log(submittedEmails);
/* Expect: [
  {
    userEmail: 'JohnWick@Unbeatable.com',
    userName: 'JohnWick',
    domainName: 'Unbeatable',
    topDomain: 'com'
  },
  {
    userEmail: 'JohnWicksWife@beatable.com',
    userName: 'JohnWicksWife',
    domainName: 'beatable',
    topDomain: 'com'
  },
  {
    userEmail: 'JohnWicksDog@theRealLoveInterest.com',
    userName: 'JohnWicksDog',
    domainName: 'theRealLoveInterest',
    topDomain: 'com'
  }
]
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Not only are we now able to email all users who submitted valid emails, we could filter it to only email users utilizing the 'Unbeatable' domain name!&lt;/p&gt;

&lt;h3&gt;
  
  
  -String Object Methods-
&lt;/h3&gt;

&lt;p&gt;These methods are &lt;code&gt;match()&lt;/code&gt;, &lt;code&gt;matchAll()&lt;/code&gt;, &lt;code&gt;replace()&lt;/code&gt;, &lt;code&gt;replaceAll()&lt;/code&gt;, &lt;code&gt;search()&lt;/code&gt;, and &lt;code&gt;split()&lt;/code&gt;.&lt;br&gt;
As mentioned earlier, we can use regex with methods used on String Objects: &lt;code&gt;string.method(regex)&lt;/code&gt;  &lt;/p&gt;
&lt;h4&gt;
  
  
  -match() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;match()&lt;/code&gt; method in conjunction with the global flag will return an array of strings if matches are found: &lt;code&gt;['match1', match2, match3]&lt;/code&gt; or &lt;code&gt;null&lt;/code&gt; if no matches are found. If the global flag is not used, the method will return the first match in the same format as the &lt;code&gt;exec()&lt;/code&gt; method.&lt;/p&gt;
&lt;h5&gt;
  
  
  -Common Use Case for the match() Method-
&lt;/h5&gt;

&lt;p&gt;Let's again say we have been tasked to compile certain information, but this time we need to only grab birthdates from the data. We don't have need to also grab additional information like how the &lt;code&gt;exec()&lt;/code&gt; method provides, just an array of the birthdates. The user submitted info could look like this:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hello again, Software Developer. My name is John Wick. I realized in my last message I forgot to include our birthdates. My birthday is 09/02/1964. My wife's birthday is 11/16/1966. My dog was born on 03/22/2020.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's assume we have already stored information above to a variable &lt;code&gt;userInfo&lt;/code&gt;. Our code to grab the birthdays using the &lt;code&gt;match()&lt;/code&gt; method could look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const birthdayRegex = /\d{2}\/\d{2}\/\d{4}/g;

const birthdays = userInfo.match(birthdayRegex);
console.log(birthdays);
//Expect: [ '09/02/1964', '11/16/1966', '03/22/2020' ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code regex only returns matches in the format 'xx/xx/xxxx'. You would need to alter the regex to match other formats. Once we have the data, we could use it to determine age demographics, how many adults, how many minors, etc...&lt;/p&gt;

&lt;h4&gt;
  
  
  -matchAll() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;matchAll()&lt;/code&gt; method is similar to the &lt;code&gt;exec()&lt;/code&gt; method in that it returns an array of information about the match.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll"&gt;MDM Web Docs&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Simply put, the &lt;code&gt;matchAll()&lt;/code&gt; method does what &lt;code&gt;exec()&lt;/code&gt; method can do when working with all matches at once, but the &lt;code&gt;matchAll()&lt;/code&gt; method can do it a bit more concisely, making it easier to read.&lt;/p&gt;

&lt;h5&gt;
  
  
  -Common Use Case for the matchAll() Method-
&lt;/h5&gt;

&lt;p&gt;To showcase how the &lt;code&gt;matchAll()&lt;/code&gt; method is more concise than the &lt;code&gt;exec()&lt;/code&gt; method, we will use the same scenario as before. Compare the two codes and see the differences. Again we have this user info: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Hello, software developer. My name is John Wick. My email address is &lt;a href="mailto:JohnWick@Unbeatable.com"&gt;JohnWick@Unbeatable.com&lt;/a&gt;, my wife's email is &lt;a href="mailto:JohnWicksWife@beatable.com"&gt;JohnWicksWife@beatable.com&lt;/a&gt;, and my dog's email is &lt;a href="mailto:JohnWicksDog@theRealLoveInterest.com"&gt;JohnWicksDog@theRealLoveInterest.com&lt;/a&gt;. I am interested in joining your company because....&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Assume again the above quote has been saved to the variable &lt;code&gt;userLetters&lt;/code&gt;. Using the &lt;code&gt;matchAll()&lt;/code&gt; method, the code might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const emailRegex = 
/(?&amp;lt;user&amp;gt;\w+[!#$%&amp;amp;'*+\-/=?^_`{|]{0,1}\w+)@(?&amp;lt;domain&amp;gt;[a-zA-Z]+[-.]?[a-zA-Z0-9]+)\.(?&amp;lt;top&amp;gt;[a-zA-Z]{2,3})/g;

const matches = [...userLetters.matchAll(emailRegex)].map(match =&amp;gt; ({
  user: match.groups.user,
  domain: match.groups.domain,
  top: match.groups.top
}));

console.log(matches);
/* Expect: 
[
  { user: 'JohnWick', domain: 'Unbeatable', top: 'com' },
  { user: 'JohnWicksWife', domain: 'beatable', top: 'com' },
  { user: 'JohnWicksDog', domain: 'theRealLoveInterest', top: 'com' }
] */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  -replace() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;replace()&lt;/code&gt; method is used to replace a specified value or pattern in a string with a new value or string. The method returns a new string with the replaced value or pattern. It can be used with a regular expression or a string value to replace all occurrences (if the 'g' flag is used) of the specified value or pattern, or a specified number of occurrences. The &lt;code&gt;replace()&lt;/code&gt; method does not modify the original string but returns a new string with the replaced values. The method takes two parameters: (regex, replacement) &lt;code&gt;string.replace(regex, replacement)&lt;/code&gt;. The replacement can be a string value, or a function. The function's result (return value) will be used as the replacement string. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace"&gt;MDM Web Docs&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalStr = "Regular Expressions are FUN, FUN, FUN!";
const regex = /fun/i;
const newWord = "AMAZING";

const newStr = originalStr.replace(regex, newWord);
console.log(originalStr); 
//Expect: "Regular Expressions are FUN, FUN, FUN!"
console.log(newStr);
//Expect: "Regular Expressions are AMAZING, FUN, FUN!"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What if we wanted to replace the first two 'FUN' with 'AMAZING'? With the help of a count variable, the code could look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalStr = "Regular Expressions are FUN, FUN, FUN!";
const regex = /fun/ig;
const newWord = "AMAZING";

let count = 0;
const newStr = originalStr.replace(regex, (match) =&amp;gt; {
  count++;
  return count &amp;lt; 3 ? newWord : match;
});

console.log(newStr);
//Expect: "Regular Expressions are AMAZING, AMAZING, FUN!"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  -Common Use Case for the replace() Method-
&lt;/h5&gt;

&lt;p&gt;I actually just recently used the &lt;code&gt;replace()&lt;/code&gt; method in a &lt;a href="//JNMedina32.github.io/Recipe_App"&gt;Recipe App&lt;/a&gt; I created. My app fetches information from an API, then dynamically renders the content to the user. I had an issue with some of the results from the API containing single quotes in the label property, which caused errors when working with the localStorage. If a user searched only for "Central Europe" in the cuisine dropdown box, the first recipe displayed used to be "Brined Ramps from 'Bar Tartine'". I fixed this within the Recipe Class using the &lt;code&gt;replace()&lt;/code&gt; method. The code is essentially this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Original label: Brined Ramps from 'Bar Tartine'

this._label = recipe.recipe.label.replace(/'/g, '');

//New label: Brined Ramps from Bar Tartine

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  -replaceAll() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;replaceAll()&lt;/code&gt; method does exactly as you'd expect, replaces all occurrences of a given substring in a string. Unlike &lt;code&gt;replace()&lt;/code&gt;, which only replaces the first occurrence of the pattern unless the global flag is set, &lt;code&gt;replaceAll()&lt;/code&gt; replaces all occurrences by default. The &lt;code&gt;replaceAll()&lt;/code&gt; method, like &lt;code&gt;replace()&lt;/code&gt;, takes two arguments: the pattern to be replaced and the replacement string. The pattern can be either a string or a regular expression, and the replacement string can be either a string or a function that returns a string. One important thing to note is that replaceAll requires a global regular expression pattern, meaning that the g flag must be specified in the regular expression pattern. If the g flag is not specified, a TypeError will be thrown. &lt;br&gt;
This &lt;code&gt;replaceAll()&lt;/code&gt; does NOT need a global flag:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalStr = "Regular Expressions are FUN, FUN, FUN!";
const newStr = originalStr.replaceAll("FUN", "AMAZING");

console.log(newStr);
//Expect: "Regular Expressions are AMAZING, AMAZING, AMAZING!";

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This &lt;code&gt;replaceAll()&lt;/code&gt; DOES need a global flag:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalStr = "Regular Expressions are FUN, FUN, FUN!";
const newStr = originalStr.replaceAll(/FUN/g, "AMAZING");

console.log(newStr);
//Expect: "Regular Expressions are AMAZING, AMAZING, AMAZING!";

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  -Common Use Case for the replaceAll() Method-
&lt;/h5&gt;

&lt;p&gt;Exactly the same as &lt;code&gt;replace()&lt;/code&gt;, when you need to replace ALL substrings.&lt;/p&gt;

&lt;h4&gt;
  
  
  -search() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;search()&lt;/code&gt; method returns the index of the first match. If no match is found, it returns -1. The syntax for &lt;code&gt;search()&lt;/code&gt; is: &lt;code&gt;string.search(regex)&lt;/code&gt;. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When you want to know whether a pattern is found, and also know its index within a string, use &lt;code&gt;search()&lt;/code&gt;-&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search"&gt;MDM Web Docs&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const string = "Regular Expressions are FUN, FUN, FUN!";
const indexOfRegex = string.search(/[A-Z]{2,}/);

console.log(indexOfRegex);
//Expect: 24
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you might be thinking: "When would I need to know the index of a substring?" Great question! Knowing the index of a particular substring in a larger string can be useful in a variety of ways. For example, if you want to extract a specific piece of information from a string, you can use the &lt;code&gt;indexOf&lt;/code&gt; method to find the starting index of that information and then use string manipulation techniques to extract it. Additionally, you can use the index to replace or modify specific parts of a string. The index can also be useful for performing more advanced operations such as parsing or tokenizing a string.&lt;/p&gt;

&lt;h4&gt;
  
  
  -split() Method-
&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;split()&lt;/code&gt; method splits a string into an array of substrings based on the regex. &lt;code&gt;split()&lt;/code&gt; does not change the original string. This method can take two parameters: &lt;code&gt;string.split(regex, limit)&lt;/code&gt;.&lt;br&gt;
The second parameter, 'limit', is optional. When used, the method will continue splitting the string until it has split &lt;code&gt;limit&lt;/code&gt; number of times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//No limit set
const stringToSplit = "Regular Expressions are FUN, FUN, FUN!";
let arrayOfSplitStr = stringToSplit.split(/\s/);

console.log(arrayOfSplitStr);
/* Expect: 
[ 'Regular', 'Expressions', 'are', 'FUN,', 'FUN,', 'FUN!' ]
*/

//Limit set
let arrayOfSplitStr = stringToSplit.split(/\s/, 4);
console.log(arrayOfSplitStr);
// Expect: [ 'Regular', 'Expressions', 'are', 'FUN,' ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  -Common Use Case for the split() Method-
&lt;/h5&gt;

&lt;p&gt;We are now tasked with listing all the sentences in a 10,000 word document. No idea why we're tasked to do this, but it doesn't matter. We can write a simple regex to handle the different ways a sentence can end and use it in a &lt;code&gt;split()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiSentenceDoc = "I LOVE CODING! Isn't problem solving great? I'm excited being a software developer.";

const splitRegex = /(?&amp;lt;=[.?!])\s+(?=[A-Z])/;

const splitArray = multiSentenceDoc.split(splitRegex);

console.log(splitArray);
/* Expect: [
  'I LOVE CODING!',
  "Isn't problem solving great?",
  "I'm excited being a software developer."
]


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  -Conclusion-
&lt;/h2&gt;

&lt;p&gt;In conclusion, regular expressions are a powerful tool in any developer's toolkit, and the various string methods built upon them can provide significant benefits in terms of string manipulation and data processing. By mastering these methods, developers can improve their efficiency and productivity, and unlock new possibilities for their applications. Whether you're a beginner or an experienced developer, taking the time to learn and understand regular expressions and their associated methods can open up a world of possibilities and help you take your coding skills to the next level.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>learning</category>
      <category>coding</category>
    </item>
  </channel>
</rss>
