<?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 Anthony Sebastin J on Medium]]></title>
        <description><![CDATA[Stories by Anthony Sebastin J on Medium]]></description>
        <link>https://medium.com/@anthonysebastinj?source=rss-3280bb18e92e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uWvBiYIUsrxq05wDF5ZaWQ@2x.jpeg</url>
            <title>Stories by Anthony Sebastin J on Medium</title>
            <link>https://medium.com/@anthonysebastinj?source=rss-3280bb18e92e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:13:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anthonysebastinj/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[When the Runtime Becomes the Risk: Two Critical PHP Vulnerabilities]]></title>
            <link>https://medium.com/@anthonysebastinj/when-the-runtime-becomes-the-risk-two-critical-php-vulnerabilities-c5bf94eb6265?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5bf94eb6265</guid>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[php-development]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 15:43:14 GMT</pubDate>
            <atom:updated>2026-10-22T15:43:14.837Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two critical PHP vulnerabilities disclosed on October 21 – 22, 2026, expose potential risks of remote code execution.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*YGBjxamSPRvsp1Aql-qiEw@2x.jpeg" /></figure><p>As developers, we usually focus on securing our application code, APIs, and databases. But what if the vulnerability isn’t in our code, but in the runtime itself?</p><p>Recently, two critical PHP vulnerabilities caught my attention: CVE-2026–109618 and CVE-2026–109619. Here’s my understanding of how they work.</p><blockquote><strong>Out-of-Memory Vulnerability :</strong></blockquote><p>When PHP processes a request, it needs memory. If memory allocation fails, PHP should handle the situation safely.</p><p>However, a flaw in how PHP handles this failure can leave its internal state inconsistent. An attacker may exploit this to cause memory corruption and potentially execute code on the server.</p><p>In simple words, the problem isn’t running out of memory; it’s what happens when PHP handles that failure incorrectly.</p><blockquote><strong>Use-After-Free Vulnerability :</strong></blockquote><p>PHP allocates and releases memory while processing requests. A use-after-free occurs when PHP tries to access memory that has already been released.</p><p>The dangerous part is that an internal reference to that memory may still exist. If PHP uses that outdated reference, it can cause memory corruption and potentially allow an attacker to execute code.</p><h4>How Can This Lead to a Data Breach?</h4><p>An attacker can send a specially crafted HTTP request to trigger a vulnerable code path. If exploitation succeeds, they may execute code with the PHP process’s permissions and potentially access application files, credentials, or sensitive data.</p><blockquote>Key Takeaway</blockquote><p>Securing our application is important, but keeping the technology it runs on secure is equally important.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5bf94eb6265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Overusing Redux: A Pub-Sub Approach for Event-Driven React Apps]]></title>
            <link>https://medium.com/@anthonysebastinj/stop-overusing-redux-a-pub-sub-approach-for-event-driven-react-apps-0deea3fbe225?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0deea3fbe225</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[publish-subscribe-pattern]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 07:43:26 GMT</pubDate>
            <atom:updated>2025-12-29T07:45:46.336Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to decouple React components using a lightweight publish–subscribe pattern</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7gIJ_7wSeQThCsf-6PmGw.png" /><figcaption>Publish-Subscribe pattern in React.</figcaption></figure><p>Modern React applications often struggle with component communication as they grow in complexity. Passing props down multiple levels or having global state for every interaction can quickly become messy.</p><p>In this article, we’ll explore a lightweight publish–subscribe (pub-sub) event system in React that enables loosely coupled, event-driven communication without relying on Redux or React Context.</p><blockquote><strong>What is Pub-Sub in React?</strong></blockquote><p>In the context of a React application, Pub-Sub is a pattern where components communicate through events rather than direct parent–child props or callbacks.</p><p>In simple terms: A component does something → an event is fired → any interested component reacts to it.</p><blockquote><strong>Let’s try to understand the publish–subscribe pattern with a simple React example.</strong></blockquote><p>To get started, we first need a central event bus that handles publishing and subscribing to events. In React, let’s do this with a simple TypeScript class.</p><pre>// pubsub.ts<br><br>export type EventPayload = unknown;<br>export type EventCallback&lt;T = EventPayload&gt; = (payload: T) =&gt; void;<br><br>class PubSub {<br>  private events: Map&lt;string, Set&lt;EventCallback&gt;&gt; = new Map();<br><br>  subscribe&lt;T = EventPayload&gt;(<br>    eventName: string,<br>    callback: EventCallback&lt;T&gt;<br>  ): () =&gt; void {<br>    if (!this.events.has(eventName)) {<br>      this.events.set(eventName, new Set());<br>    }<br><br>    const callbacks = this.events.get(eventName)!;<br>    callbacks.add(callback as EventCallback);<br><br>    // unsubscribe function<br>    return () =&gt; {<br>      callbacks.delete(callback as EventCallback);<br>      if (callbacks.size === 0) {<br>        this.events.delete(eventName);<br>      }<br>    };<br>  }<br><br>  publish&lt;T = EventPayload&gt;(eventName: string, payload: T): void {<br>    const callbacks = this.events.get(eventName);<br>    if (!callbacks) return;<br><br>    callbacks.forEach((callback) =&gt; {<br>      callback(payload);<br>    });<br>  }<br>}<br><br>// singleton instance<br>export const pubSub = new PubSub();</pre><p>Here’s how it works, piece by piece</p><pre>private events: Map&lt;string, Set&lt;EventCallback&gt;&gt; = new Map();</pre><p>This line creates a central registry that keeps track of all the events in your application and their subscribers. Think of it like a table of events, where:</p><ul><li>Key (string) → the name of the event, like &quot;USER_ACTION&quot; or &quot;ITEM_ADDED&quot;.</li><li>Value (Set&lt;EventCallback&gt;) → all the functions (callbacks) that should notify the subscribed components when this event occurs.</li></ul><blockquote><strong>How Components Subscribe to Events?</strong></blockquote><pre> subscribe&lt;T = EventPayload&gt;(<br>    eventName: string,<br>    callback: EventCallback&lt;T&gt;<br>  ): () =&gt; void {<br>    if (!this.events.has(eventName)) {<br>      this.events.set(eventName, new Set());<br>    }<br><br>    const callbacks = this.events.get(eventName)!;<br>    callbacks.add(callback as EventCallback);<br><br>    // unsubscribe function<br>    return () =&gt; {<br>      callbacks.delete(callback as EventCallback);<br>      if (callbacks.size === 0) {<br>        this.events.delete(eventName);<br>      }<br>    };<br>  }</pre><p>The subscribe method allows a component to listen to an event by providing the event name and a callback function. Here’s what happens under the hood:</p><ul><li>If the event name doesn’t exist in the registry yet, the event bus creates a new entry with a fresh Set. This is necessary because without it, subscribing to a new event would fail.</li></ul><pre>const callbacks = this.events.get(eventName)!;<br>     callbacks.add(callback as EventCallback);</pre><ul><li>The component’s callback is then added to the list of subscribers for that event so that it will be notified whenever the event is published.</li><li>The method returns an unsubscribe function, which the component can call when it unmounts to prevent memory leaks.</li></ul><blockquote><strong>How Publishing an Event Works?</strong></blockquote><pre>publish&lt;T = EventPayload&gt;(eventName: string, payload: T): void {<br>    const callbacks = this.events.get(eventName);<br>    if (!callbacks) return;<br><br>    callbacks.forEach((callback) =&gt; {<br>      callback(payload);<br>    });<br>  }</pre><p>We have a publish method that lets a component emit an event along with some payload. Here’s what happens:</p><ul><li>The component calls publish, providing the event name (like &quot;USER_ACTION&quot;) and a payload (data to share).</li><li>The event bus looks up all subscribers that registered callbacks for this event name.</li><li>It then iterates over each callback and calls it, passing the payload.</li><li>Each subscriber reacts independently updating state, showing a message, or performing any action it needs.</li><li>If no component has subscribed to this event, the method simply does nothing, so publishing an event is always safe.</li></ul><pre>export const pubSub = new PubSub();</pre><p>And finally exporting a single instance, all components in the app share the same event bus.</p><p>And that’s it! With this pubSub utility, we’ve set up a central event bus that allows React components to interact through events without being directly connected.</p><blockquote><strong>Publishing Events from a Component</strong></blockquote><p>Here’s a simple Publisher component that emits an event using our pubSub utility whenever the user clicks a button.</p><pre>// Publisher.tsx<br><br>import React from &#39;react&#39;;<br>import { pubSub } from &#39;./pubsub&#39;;<br><br>const Publisher: React.FC = () =&gt; {<br>  const handleClick = () =&gt; {<br>    pubSub.publish(&#39;USER_ACTION&#39;, {<br>      message: &#39;Button clicked from Publisher&#39;,<br>      timestamp: Date.now(),<br>    });<br>  };<br><br>  return (<br>    &lt;div style={{ border: &#39;1px solid #ccc&#39;, padding: 16 }}&gt;<br>      &lt;h3&gt;Publisher&lt;/h3&gt;<br>      &lt;button onClick={handleClick}&gt;Publish Event&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Publisher;</pre><p>To publish an event from a React component, we simply import the<strong> </strong>singleton pubSub instance and call its publish method whenever something happens like a button click.</p><pre>pubSub.publish(&#39;USER_ACTION&#39;, {<br>  message: &#39;Button clicked from Publisher&#39;,<br>  timestamp: Date.now(),<br>});</pre><ul><li>&#39;USER_ACTION&#39; is the component/event name.</li><li>payload is the data we are sending to the subscribers.</li><li>When this line runs, the pubSub instance iterates over all callbacks subscribed to &#39;USER_ACTION&#39; and calls them immediately with the payload.</li></ul><blockquote><strong>Subscribing to Events from Various Components</strong></blockquote><p>Here are a couple of Subscriber components that listen for the same event using our pubSub utility and react whenever the Publisher emits it.</p><pre>// SubscriberA.tsx<br><br>import React, { useEffect, useState } from &#39;react&#39;;<br>import { pubSub } from &#39;./pubsub&#39;;<br><br>interface UserActionEvent {<br>  message: string;<br>  timestamp: number;<br>}<br><br>const SubscriberA: React.FC = () =&gt; {<br>  const [eventData, setEventData] = useState&lt;UserActionEvent | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    const unsubscribe = pubSub.subscribe&lt;UserActionEvent&gt;(<br>      &#39;USER_ACTION&#39;,<br>      (data) =&gt; {<br>        console.log(&#39;Subscriber A received:&#39;, data);<br>        setEventData(data);<br>      }<br>    );<br><br>    return unsubscribe;<br>  }, []);<br><br>  return (<br>    &lt;div style={{ border: &#39;1px solid #4caf50&#39;, padding: 16 }}&gt;<br>      &lt;h3&gt;Subscriber A&lt;/h3&gt;<br>      {eventData ? (<br>        &lt;pre&gt;{JSON.stringify(eventData, null, 2)}&lt;/pre&gt;<br>      ) : (<br>        &lt;p&gt;No events received yet&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default SubscriberA;</pre><pre>// SubscriberB.tsx<br><br>import React, { useEffect } from &#39;react&#39;;<br>import { pubSub } from &#39;./pubsub&#39;;<br><br>const SubscriberB: React.FC = () =&gt; {<br>  useEffect(() =&gt; {<br>    const unsubscribe = pubSub.subscribe(<br>      &#39;USER_ACTION&#39;,<br>      (data) =&gt; {<br>        console.log(&#39;Subscriber B received:&#39;, data);<br>      }<br>    );<br><br>    return unsubscribe;<br>  }, []);<br><br>  return (<br>    &lt;div style={{ border: &#39;1px solid #2196f3&#39;, padding: 16 }}&gt;<br>      &lt;h3&gt;Subscriber B&lt;/h3&gt;<br>      &lt;p&gt;Listening to USER_ACTION events (check console)&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default SubscriberB;</pre><p>Once we have a Publisher emitting events, components can subscribe to those events using the same pubSub singleton instance.</p><pre>const unsubscribe = pubSub.subscribe(&#39;USER_ACTION&#39;, (data) =&gt; {<br>  console.log(&#39;Subscriber B received:&#39;, data);<br>});</pre><ul><li>&#39;USER_ACTION&#39; is the event name/component name the Subscriber wants to listen to.</li><li>The second argument is a callback function that runs whenever the event is published. Here, data is the payload sent by the Publisher.</li></ul><p>So, this is how we can subscribe to published events from any component using the shared pubSub instance.</p><blockquote>And that’s a done deal!🚀</blockquote><p>With this pubSub setup, Publishers can emit events and Subscribers can react in real-time, all without prop drilling or extra global state.</p><p>This pattern is especially handy for apps with lots of event-driven UI updates, like proctoring tools or assessment platforms, where multiple components need to respond to user actions or system events. It keeps your React app clean, flexible, and easy to maintain.</p><p><em>See you in the next blog, where we’ll explore more patterns to make your React apps even more interactive and maintainable!👋</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0deea3fbe225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Session vs JWT: Exploring and Implementing Authentication Strategies for Your Web App]]></title>
            <link>https://medium.com/@anthonysebastinj/session-vs-jwt-exploring-and-implementing-authentication-strategies-for-your-web-app-b09f32b9047b?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b09f32b9047b</guid>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[stateless]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Thu, 01 May 2025 16:18:37 GMT</pubDate>
            <atom:updated>2025-05-01T16:26:27.307Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building and Comparing Session and Token-Based Authentication for Secure and Scalable Apps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*Q1APukdGf5dMYBWY5cTNYQ.png" /></figure><p>Hello Devs👨‍💻!</p><p>It’s been a while since I last shared a post, but I’m excited to be back with something new. Glad to have you back on the blog! In my last post, we explored full-stack authentication in detail if you missed it, you can catch up 🔗 <a href="https://medium.com/@anthonysebastinj/full-stack-authentication-firebase-in-a-vite-react-app-with-node-js-and-mongodb-ee832e3b529b">here</a>.</p><p>Today, we’re switching things up to cover a crucial topic for any web application: authentication. We’ll build both Session-Based Authentication and Token-Based (JWT) Authentication, comparing them side by side to determine which method works best for your web app.</p><blockquote><em>So without any delay, Let’s get started!🚀</em></blockquote><h4>Why Are Sessions and Tokens Important?</h4><p>When a user logs into a website, the site needs a way to remember them as they move from page to page. But since the web doesn’t remember anything by itself, we need a method to keep the user logged in.</p><p>To solve this, developers rely on two main strategies:<br><strong> </strong>Session-Based Authentication and Token-Based Authentication.</p><p>Both methods help maintain the logged-in state, but they do it in very different ways. Understanding how each works and when to use which can help you build more secure, scalable, and user-friendly applications.</p><h4>1. Session-Based Authentication</h4><p>A <strong>session</strong> is a way for a web application to remember a user after they log in. Instead of asking for your login details on every page, the server creates a session and stores your info like your user ID on the server. Then it gives the browser a <strong>session ID</strong> like a receipt which is saved in a cookie.</p><p>Sessions are stateful, meaning they rely on server memory or external storage solutions like a database or a CDN (such as AWS) to store session data. This makes them suitable for scenarios where maintaining user state on the server is necessary.</p><p>In this blog, we’ll be using <strong>Express-session </strong>a popular middleware in Node.js to manage sessions.</p><blockquote><strong>Packages Required for Session-Based Authentication</strong></blockquote><p>Before we start setting up the session-based authentication, we need to install a few packages that will help us manage sessions and connect to MongoDB:</p><pre>npm install express-session cors mongoose dotenv</pre><blockquote><strong>Setting Up the Express Server with Sessions</strong></blockquote><p>Now that we’ve installed the necessary packages, let’s set up the Express server and configure session-based authentication. This configuration will allow the backend to handle login, logout, and store session information in cookies.</p><p>Here’s how you can set up the server:</p><pre>import express from &#39;express&#39;;<br>import cors from &#39;cors&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import sessionRoutes from &#39;./routes/sessionRouter.js&#39;;<br>import jwtRoutes from &#39;./routes/tokenRouter.js&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>import session from &#39;express-session&#39;;<br>dotenv.config();<br><br>const app = express();<br>const PORT = 5000;<br><br>app.use(cors({<br>  origin: &#39;http://localhost:5173&#39;,<br>  credentials: true<br>}));<br>app.use(express.json());<br><br>app.use(session({<br>  secret: process.env.SESSION_SECRET,<br>  resave: false,<br>  saveUninitialized: true,  <br>  cookie: { secure: false },<br>}));<br><br>// base route<br>app.use(&#39;/api/sessionAuth&#39;, sessionRoutes);<br>app.use(&#39;/api/tokenAuth&#39;, jwtRoutes);<br><br>mongoose.connect(process.env.MONGODBURI)<br>  .then(() =&gt; {<br>    console.log(&quot;MongoDB connected&quot;);<br><br>    app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));<br>  })<br>  .catch((error) =&gt; {<br>    console.error(&quot;Error connecting to MongoDB:&quot;, error);<br>  });</pre><blockquote><strong>Note</strong>: This explanation focuses on the session-related code. General setup code such as MongoDB connection, Express app initialization, and server startup (app.listen) is not included here for simplicity.</blockquote><p><strong>Code Breakdown:</strong></p><pre>app.use(cors({<br>  origin: &#39;http://localhost:5173&#39;,<br>  credentials: true<br>}));</pre><p>This allows your frontend running on port 5173 to make requests to the backend with credentials like cookies, which are required for sessions.</p><p><strong>Session Middleware:</strong></p><pre>app.use(session({<br>  secret: process.env.SESSION_SECRET,<br>  resave: false,<br>  saveUninitialized: true,  <br>  cookie: { secure: false },<br>}));</pre><p>This is the key part of session-based authentication:</p><ul><li>secret: Used to sign the session ID cookie.</li><li>resave: false: Don’t save the session if it wasn’t modified.</li><li>saveUninitialized: true: Save new sessions even if nothing is added to them.</li><li>cookie.secure: false: Should be true in production (only send cookies over HTTPS).</li></ul><p><strong>Base Routes:</strong></p><pre>app.use(&#39;/api/sessionAuth&#39;, sessionRoutes);</pre><p>All session-related routes like login, logout are handled under /api/sessionAuth</p><p>Following the MVC Pattern for Session Authentication. If you’re new to the <strong>MVC </strong>pattern, I’ve covered it in detail in my blog to help organize our code for better structure and maintainability. If you haven’t checked it out yet, you can catch up🔗<a href="https://medium.com/@anthonysebastinj/streamlining-mern-development-with-mvc-architecture-c63a8c7c43b0">here</a>.</p><blockquote><strong>Creating the Session Router</strong></blockquote><p>Next, we need to define the routes for session-based authentication. This router will handle registration, login, and clearing the session.</p><p>Here’s the sessionRouter.js file:</p><pre>import express from &#39;express&#39;;<br>import { clearSession, sessionLogin, sessionRegister } from &#39;../controller/sessionController.js&#39;;<br><br>const router = express.Router();<br><br>router.post(&#39;/sessionRegister&#39;, sessionRegister);<br>router.post(&#39;/sessionLogin&#39;, sessionLogin);<br>router.post(&#39;/clearSession&#39;, clearSession);<br><br>export default router;</pre><blockquote><strong>Controller Logic for Session Authentication</strong></blockquote><p>The controller handles the business logic for registration, login, and clearing sessions. For login, we create the session and send a session ID cookie.</p><p>Here’s the controller code:</p><pre>import bcrypt from &#39;bcrypt&#39;;<br>import User from &#39;../model/model.js&#39;;<br><br>export async function sessionRegister(req, res){<br>    try {<br>        const { username, password } = req.body;<br>        const hashedPassword = await bcrypt.hash(password, 10);<br>        const newUser = new User({ username, password: hashedPassword });<br>        await newUser.save();<br>        res.status(201).json({ message: &#39;User registered successfully&#39; });<br>      } catch (error) {<br>        res.status(500).json({ error: &#39;Error registering user&#39; });<br>      }<br>}<br><br>export async function sessionLogin(req, res){<br>    try {<br>        const { username, password } = req.body;<br>        <br>        const user = await User.findOne({ username });<br>        if (!user || !(await bcrypt.compare(password, user.password))) {<br>          return res.status(401).json({ error: &#39;Invalid credentials&#39; });<br>        }<br>    <br>        req.session.user = user; // Store user session<br>        res.cookie(&#39;session_id&#39;, req.sessionID, { httpOnly: true });<br>        res.json({ message: &#39;Login successful&#39;, sessionID :req.sessionID, user });<br>      } catch (error) {<br>        res.status(500).json({ error: &#39;Error logging in&#39; });<br>      }<br>}<br><br>export async function clearSession(req, res){<br>    req.session.destroy();<br>    res.clearCookie(&#39;session_id&#39;);<br>    res.json({ message: &#39;Logged out successfully&#39; });<br>}</pre><ol><li>The <strong>sessionRegister()</strong> function focuses on saving the user details in the database. The session will be assigned during the login process when the user attempts to authenticate.</li><li><strong>sessionLogin(): Handling User Login and Session Creation</strong></li></ol><p>The goal of this function is to authenticate the user and create a session. Upon successful login, the server generates a session and sends it to the client.</p><pre>export async function sessionLogin(req, res){<br>    try {<br>        const { username, password } = req.body;<br>        <br>        const user = await User.findOne({ username });<br>        if (!user || !(await bcrypt.compare(password, user.password))) {<br>          return res.status(401).json({ error: &#39;Invalid credentials&#39; });<br>        }<br>    <br>        req.session.user = user; // Store user session<br>        res.cookie(&#39;session_id&#39;, req.sessionID, { httpOnly: true });<br>        res.json({ message: &#39;Login successful&#39;, sessionID :req.sessionID, user });<br>      } catch (error) {<br>        res.status(500).json({ error: &#39;Error logging in&#39; });<br>      }<br>}</pre><ul><li><strong>Session Creation</strong>:</li></ul><p>Once the user’s credentials are validated, we store the user information in the session by assigning req.session.user = user. This ensures the user&#39;s state is maintained across multiple requests during their session.</p><ul><li><strong>Session Cookie</strong>:</li></ul><p>We send a session_id cookie to the client with res.cookie(). This cookie helps the client track the session, and it is marked with the httpOnly flag for added security making it inaccessible via JavaScript on the client side.</p><ul><li><strong>Success Response</strong>:</li></ul><p>If the login is successful, we send a response back to the client with a success message, with the sessionID, and the user details just to see how the stored session looks like.</p><blockquote><strong>Note:</strong> Session data is stored on the server, while only the session ID is stored on the client side (browser).</blockquote><h4>Frontend React Component for Session Authentication:</h4><p>To interact with the backend, we’ll create a simple React component. This component will handle user registration, login, and logout requests, and it will manage the session on the frontend.</p><blockquote>Packages Required</blockquote><pre>npm install axios</pre><blockquote>Here’s the React component:</blockquote><pre>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>function SessionAuth() {<br>  const [username, setUsername] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [message, setMessage] = useState(&#39;&#39;);<br>  const [user, setUser] = useState(null);<br><br>  const register = async () =&gt; {<br>    try {<br>      const res = await axios.post(&#39;/api/sessionAuth/sessionRegister&#39;, { username, password }, { withCredentials: true });<br>      setMessage(res.data.message);<br>    } catch (err) {<br>      setMessage(err.response?.data?.error || &#39;Registration failed&#39;);<br>    }<br>  };<br><br>  const login = async () =&gt; {<br>    try {<br>      const res = await axios.post(&#39;/api/sessionAuth/sessionLogin&#39;, { username, password }, { withCredentials: true });<br>      setUser(res.data.user);<br>      setMessage(res.data.message);<br>    } catch (err) {<br>      setMessage(err.response?.data?.error || &#39;Login failed&#39;);<br>    }<br>  };<br><br>  const logout = async () =&gt; {<br>    try {<br>      const res = await axios.post(&#39;/api/sessionAuth/clearSession&#39;, {}, { withCredentials: true });<br>      setUser(null);<br>      setMessage(res.data.message);<br>    } catch (err) {<br>      setMessage(err.response?.data?.error || &#39;Logout failed&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;div style={{ padding: &#39;20px&#39; }}&gt;<br>      &lt;h2&gt;Session Auth&lt;/h2&gt;<br>      &lt;input type=&quot;text&quot; placeholder=&quot;Username&quot; value={username} onChange={e =&gt; setUsername(e.target.value)} /&gt;<br>      &lt;br /&gt;<br>      &lt;input type=&quot;password&quot; placeholder=&quot;Password&quot; value={password} onChange={e =&gt; setPassword(e.target.value)} /&gt;<br>      &lt;br /&gt;&lt;br /&gt;<br>      &lt;button onClick={register}&gt;Register&lt;/button&gt;<br>      &lt;button onClick={login}&gt;Login&lt;/button&gt;<br>      &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>      &lt;br /&gt;&lt;br /&gt;<br>      {message &amp;&amp; &lt;p&gt;{message}&lt;/p&gt;}<br>      {user &amp;&amp; &lt;pre&gt;{JSON.stringify(user, null, 2)}&lt;/pre&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default SessionAuth;</pre><p><strong>Explanation of the Frontend Code SessionAuth.jsx:</strong></p><ul><li>The <strong>axios.post</strong> request sends the user’s credentials (username and password) to the backend, where the server will authenticate the user.</li><li>The withCredentials: true flag is important when making API requests from the frontend. It ensures that the session cookie containing the session ID is included in the request.</li><li>In other words, once a user logs in, all future API requests that rely on the session like fetching user data <strong>must</strong> include withCredentials: true, otherwise the server won&#39;t receive the session ID from the cookie, and the user will be treated as unauthenticated.</li><li>After login, the user data is stored in the state and displayed, and the message indicates the status of the action whether it’s success or failure.</li></ul><blockquote><strong>Session-Based Authentication Flow</strong></blockquote><p><strong>Login:</strong></p><ul><li>The user sends their credentials (username and password) to the backend.</li><li>If the credentials are valid, the backend creates a session for the user and stores the session ID on the server.</li><li>The session ID is sent back to the client, usually in a secure cookie.</li></ul><p><strong>Access Protected Routes:</strong></p><ul><li>To access protected routes, the frontend includes the session cookie (which contains the session ID) in the request headers.</li><li>The backend uses the session ID to retrieve the session data and verify that the user is authenticated.</li></ul><p><strong>Session Middleware:</strong></p><ul><li>On the server-side, middleware checks if the session cookie is present in the request headers.</li><li>The server retrieves the session ID from the cookie, checks if it’s valid, and ensures that the session data corresponds to a valid user.</li><li>If valid, the middleware allows the request to proceed, otherwise, it responds with an authentication error (e.g., 401 Unauthorized).</li></ul><h4>2. Token-Based Authentication (JWT)</h4><p><strong>JSON Web Token </strong>is a popular mechanism for stateless user authentication, commonly used in modern web applications. Rather than storing session data on the server, the user’s identity is securely embedded within a token that is passed between the client and server. This method is <strong>stateless</strong>, meaning the server does not need to retain any session information between requests. The token itself contains all the necessary user data, and once issued, it can be sent in subsequent requests for verification.</p><p>This stateless nature makes JWT highly efficient, particularly in Single Page Applications, and it provides better scalability since no server-side memory is needed.</p><p>Let’s see how we can achieve this using a simple example with JWT and break it down step by step to understand how it works behind the scenes.</p><blockquote><strong>Packages Required for JWT-Based Authentication</strong></blockquote><p>To implement JWT-based authentication, you will need the following npm packages:</p><pre>npm install express jsonwebtoken bcrypt dotenv cors mongoose</pre><blockquote><strong>Setting Up JWT Authentication Routes</strong></blockquote><p>First, we define a dedicated route to handle JWT-based authentication. This helps keep our application organized and scalable by isolating authentication-related logic.</p><pre>app.use(&#39;/api/tokenAuth&#39;, jwtRoutes);</pre><p>This prefix will be used for routes like register, login, and protected routes.</p><blockquote><strong>JWT Authentication Router</strong></blockquote><p>Now, we need to set up routes to handle user registration, login, and protected content. The logic for handling these routes will be placed in a router for clarity.</p><pre>import express from &#39;express&#39;;<br>import { jwtRegister, jwtLogin } from &#39;../controller/tokenController.js&#39;;<br>import { authenticateToken } from &#39;../controller/authMiddleware.js&#39;;<br><br><br>const router = express.Router();<br><br>router.post(&#39;/jwtRegister&#39;, jwtRegister);<br>router.post(&#39;/jwtLogin&#39;, jwtLogin);<br><br>// Protected route<br>router.get(&#39;/protected&#39;, authenticateToken, (req, res) =&gt; {<br>  res.json({ message: &#39;Protected content&#39;, user: req.user });<br>});<br><br>export default router;</pre><blockquote><strong>Controller Logic for JWT Authentication</strong></blockquote><p>Rather than creating server-side sessions, we generate a JWT token upon successful login. This token is sent back to the client and stored (typically in localStorage or cookies), and is included with future requests to access protected routes.</p><pre>import bcrypt from &#39;bcrypt&#39;;<br>import jwt from &#39;jsonwebtoken&#39;;<br>import User from &#39;../model/model.js&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>const JWT_SECRET = process.env.JWT_SECRET;<br><br>export async function jwtRegister(req, res) {<br>  try {<br>    const { username, password } = req.body;<br>    const hashedPassword = await bcrypt.hash(password, 10);<br>    const newUser = new User({ username, password: hashedPassword });<br>    await newUser.save();<br>    res.status(201).json({ message: &#39;User registered successfully&#39; });<br>  } catch (error) {<br>    res.status(500).json({ error: &#39;Error registering user&#39; });<br>  }<br>}<br><br>export async function jwtLogin(req, res) {<br>  try {<br>    const { username, password } = req.body;<br>    const user = await User.findOne({ username });<br><br>    if (!user || !(await bcrypt.compare(password, user.password))) {<br>      return res.status(401).json({ error: &#39;Invalid credentials&#39; });<br>    }<br><br>    const token = jwt.sign({ id: user._id, username: user.username }, JWT_SECRET, {<br>      expiresIn: &#39;1h&#39;,<br>    });<br><br>    res.json({ message: &#39;Login successful&#39;, token });<br>  } catch (error) {<br>    res.status(500).json({ error: &#39;Error logging in&#39; });<br>  }<br>}</pre><p><strong>How JWT is Signed and Sent to the Browser</strong></p><p>User Login<strong> </strong><strong>jwtLogin</strong> function:</p><ul><li>The user sends a <strong>login request</strong> with their credentials username and password.</li><li>If the credentials match the records in the database checked using bcrypt.compare(), a <strong>JWT token</strong> is created.</li><li>The jwt.sign() function generates the token with the user’s ID and username as payload, and it is signed using the <strong>JWT_SECRET</strong>.</li><li>The token is sent back in the response body (res.json({ message: &#39;Login successful&#39;, token })).</li><li>The <strong>client (browser)</strong> stores this token (usually in <strong>localStorage</strong> or <strong>sessionStorage</strong>).</li></ul><blockquote><strong>JWT Middle ware</strong></blockquote><p>JWT middleware is used to protect routes by verifying the token sent by the client in the Authorization header.</p><pre>import jwt from &#39;jsonwebtoken&#39;;<br>import dotenv from &#39;dotenv&#39;;<br>dotenv.config();<br><br>const JWT_SECRET = process.env.JWT_SECRET; <br><br>export function authenticateToken(req, res, next) {<br>  const authHeader = req.headers.authorization;<br><br>  if (!authHeader) return res.status(401).json({ error: &#39;Missing Authorization header&#39; });<br><br>  const token = authHeader.split(&#39; &#39;)[1];<br><br>  jwt.verify(token, JWT_SECRET, (err, user) =&gt; {<br>    if (err) return res.status(403).json({ error: &#39;Invalid or expired token&#39; });<br><br>    req.user = user; // Attach user payload to request<br>    next(); // Proceed to the next middleware or route handler<br>  });<br>}</pre><p><strong>How the Middleware Protects Routes</strong></p><p>JWT Middleware (<strong>authenticateToken</strong> function):</p><ul><li><strong>Authorization Header</strong>: For each <strong>protected route</strong>, the client sends the JWT token in the Authorization header, formatted as Bearer &lt;token&gt;.</li><li><strong>Token Extraction</strong>: The middleware extracts the token from the header using authHeader.split(&#39; &#39;)[1].</li><li><strong>Token Verification</strong>: The token is verified using jwt.verify(). The function checks if the token is valid and has not expired.</li><li>If the token is valid, the user’s data (payload) from the token is attached to req.user.</li><li>The middleware then calls next(), passing control to the next middleware or route handler.</li><li>If the token is missing or invalid, the server responds with an error message.</li></ul><blockquote><strong>Protecting Routes Using JWT Middleware</strong></blockquote><p>For protected routes, the middleware will check if the JWT token is valid. The token must be included in the Authorization header, formatted as Bearer &lt;token&gt;.</p><pre>router.get(&#39;/protected&#39;, authenticateToken, (req, res) =&gt; {<br>  res.json({ message: &#39;Protected content&#39;, user: req.user });<br>});</pre><h4>Frontend React Component for Token Based Authentication:</h4><p>A simple React component to manage user registration, login, and accessing protected content:</p><blockquote><strong>Packages Required</strong></blockquote><pre>npm install axios</pre><blockquote><strong>Here’s the React component</strong></blockquote><pre>import React, { useState } from &#39;react&#39;;<br>import axios from &#39;axios&#39;;<br><br>function JwtAuth() {<br>  const [username, setUsername] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [message, setMessage] = useState(&#39;&#39;);<br>  const [token, setToken] = useState(localStorage.getItem(&#39;token&#39;) || &#39;&#39;);<br>  const [protectedData, setProtectedData] = useState(null);<br><br>  const register = async () =&gt; {<br>    try {<br>      const res = await axios.post(&#39;/api/tokenAuth/jwtRegister&#39;, { username, password });<br>      setMessage(res.data.message);<br>    } catch (err) {<br>      setMessage(err.response?.data?.error || &#39;Registration failed&#39;);<br>    }<br>  };<br><br>  const login = async () =&gt; {<br>    try {<br>      const res = await axios.post(&#39;/api/tokenAuth/jwtLogin&#39;, { username, password });<br>      setToken(res.data.token);<br>      localStorage.setItem(&#39;token&#39;, res.data.token);<br>      setMessage(res.data.message);<br>    } catch (err) {<br>      setMessage(err.response?.data?.error || &#39;Login failed&#39;);<br>    }<br>  };<br><br>  const accessProtectedRoute = async () =&gt; {<br>    try {<br>      const res = await axios.get(&#39;/api/tokenAuth/protected&#39;, {<br>        headers: {<br>          Authorization: `Bearer ${token}`<br>        }<br>      });<br>      setProtectedData(res.data);<br>      setMessage(&#39;Accessed protected route&#39;);<br>    } catch (err) {<br>      setMessage(err.response?.data?.error || &#39;Access denied&#39;);<br>    }<br>  };<br><br>  const logout = () =&gt; {<br>    localStorage.removeItem(&#39;token&#39;);<br>    setToken(&#39;&#39;);<br>    setProtectedData(null);<br>    setMessage(&#39;Logged out&#39;);<br>  };<br><br>  return (<br>    &lt;div style={{ padding: &#39;20px&#39; }}&gt;<br>      &lt;h2&gt;JWT Auth&lt;/h2&gt;<br>      &lt;input type=&quot;text&quot; placeholder=&quot;Username&quot; value={username} onChange={e =&gt; setUsername(e.target.value)} /&gt;<br>      &lt;br /&gt;<br>      &lt;input type=&quot;password&quot; placeholder=&quot;Password&quot; value={password} onChange={e =&gt; setPassword(e.target.value)} /&gt;<br>      &lt;br /&gt;&lt;br /&gt;<br>      &lt;button onClick={register}&gt;Register&lt;/button&gt;<br>      &lt;button onClick={login}&gt;Login&lt;/button&gt;<br>      &lt;button onClick={accessProtectedRoute}&gt;Access Protected&lt;/button&gt;<br>      &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>      &lt;br /&gt;&lt;br /&gt;<br>      {message &amp;&amp; &lt;p&gt;{message}&lt;/p&gt;}<br>      {protectedData &amp;&amp; (<br>        &lt;pre&gt;{JSON.stringify(protectedData, null, 2)}&lt;/pre&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default JwtAuth;</pre><blockquote><strong>Explaining the Login Flow and Accessing Data Using JWT (Stored in Local Storage or Cookie)</strong></blockquote><pre>const login = async () =&gt; {<br>  try {<br>    const res = await axios.post(&#39;/api/tokenAuth/jwtLogin&#39;, { username, password });<br>    setToken(res.data.token); // Store token in state<br>    localStorage.setItem(&#39;token&#39;, res.data.token); // Store token in localStorage<br>    setMessage(res.data.message);<br>  } catch (err) {<br>    setMessage(err.response?.data?.error || &#39;Login failed&#39;);<br>  }<br>};</pre><ul><li>The axios.post() method sends a request to the backend server&#39;s /jwtLogin endpoint with the username and password.</li><li>The backend validates the credentials and responds with a JWT.</li><li>The JWT is stored in both the <strong>React component state</strong> and <strong>localStorage</strong> to persist the user’s session</li></ul><blockquote><strong>Storing JWT (Session Persistence) :</strong></blockquote><p>Once the user logs in, the JWT is stored in either:</p><ul><li><strong>Local Storage</strong>: Easy to use, but vulnerable to XSS attacks.</li><li><strong>HttpOnly Cookie</strong>: More secure, as it cannot be accessed by JavaScript, but vulnerable to CSRF if not protected with a token.</li></ul><pre>res.cookie(&#39;token&#39;, token, { httpOnly: true, secure: true });</pre><blockquote><strong>Using JWT to Access Protected Routes:</strong></blockquote><p>Once the user is logged in and has the JWT, it needs to be included in the <strong>Authorization header</strong> for every subsequent request that requires authentication. This is how the frontend ensures that the server knows the user is authenticated and authorized to access the protected route.</p><pre>const accessProtectedRoute = async () =&gt; {<br>  try {<br>    const res = await axios.get(&#39;/api/tokenAuth/protected&#39;, {<br>      headers: {<br>        Authorization: `Bearer ${token}` // Send JWT in Authorization header<br>      }<br>    });<br>    setProtectedData(res.data); // Store protected data<br>    setMessage(&#39;Accessed protected route&#39;);<br>  } catch (err) {<br>    setMessage(err.response?.data?.error || &#39;Access denied&#39;);<br>  }<br>};</pre><ul><li>The Authorization header is set with the value Bearer ${token}, where token is the JWT stored in localStorage (or a cookie).</li><li>The backend verifies the JWT in the request header and grants or denies access to the protected route based on whether the token is valid.</li></ul><blockquote><strong>JWT Authentication flow</strong></blockquote><ul><li><strong>Login</strong>: When a user logs in, they send their credentials to the backend. If valid, the backend returns a JWT, which is stored in localStorage or a secure cookie on the client-side.</li><li><strong>Access Protected Routes</strong>: To access protected routes, the frontend includes the JWT in the Authorization header of requests, allowing the backend to verify the user’s authenticity.</li><li><strong>JWT Middleware</strong>: On the server-side, the middleware validates the JWT and grants access to protected resources based on the decoded user information.</li></ul><p><strong>Bingo!!</strong> We’ve successfully built a demo app showcasing two popular authentication methods <strong>Session-based</strong> and <strong>JWT-based</strong>.</p><p>Now that our demo is complete, let’s <strong>break down the differences between the two approaches</strong> and explore which might be a better fit depending on the application’s needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*emNZTW_NZW7S215A-yessg.png" /></figure><p>Ultimately, the choice of authentication method depends on your needs. JWT is stateless and doesn’t use server memory, making it more scalable, while Session-based authentication relies on server storage, which could be limiting for larger apps. Consider your app’s scale and security requirements when making the choice.</p><blockquote>That’s a done deal!!</blockquote><p>In this blog, we explored two major authentication strategies <strong>Session-based Authentication</strong> and <strong>JWT Authentication</strong> by building a hands-on demo application. We saw how each method works, where the session is stored, how the client and server communicate, and how protected routes are handled securely.</p><p><strong>Check out the complete source code on my GitHub:</strong><br>🔗<a href="https://github.com/anthonysebastinj/sessionVstoken">https://github.com/anthonysebastinj/sessionVstoken</a></p><p>Stay tuned for more blogs on building web applications using MERN and exploring the latest trending tools!</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b09f32b9047b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack Authentication: Firebase in a Vite React App with Node.js and MongoDB]]></title>
            <link>https://medium.com/@anthonysebastinj/full-stack-authentication-firebase-in-a-vite-react-app-with-node-js-and-mongodb-ee832e3b529b?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee832e3b529b</guid>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[otp-verification]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 12:11:01 GMT</pubDate>
            <atom:updated>2025-02-22T12:11:01.981Z</atom:updated>
            <content:encoded><![CDATA[<h4>Securing React Applications with Firebase OTP-Based Mobile Authentication</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTpNDoWhcpgH79rZyxs-TQ.png" /></figure><p>Hello Devs👨‍💻! Welcome back to my blog</p><p>In my previous blog I’ve covered the fundamental React hooks that every developer should know. If you haven’t read it yet, you can check it out 🔗<a href="https://medium.com/@anthonysebastinj/react-hooks-101-essential-react-hooks-for-optimized-development-1b31c0ce1758">here</a>. I highly recommend checking it out for a solid foundation before diving into this topic.</p><p>Now, let’s explore how to build a full-stack authentication system in a Vite-powered React app. We’ll cover everything from OTP verification with Firebase to securely managing user data with Node.js and MongoDB.</p><blockquote><strong>Firebase : ( </strong><a href="https://firebase.google.com/"><strong>firebase.google.com</strong></a><strong> )</strong></blockquote><p>When it comes to mobile authentication, Firebase is one of the most popular and reliable solutions. It provides a seamless way to implement authentication with features like OTP-based login, social sign-ins, and email-password authentication.</p><p>Now, let’s get started with setting up Firebase for mobile authentication.</p><blockquote><strong>Steps to Set Up Firebase for Authentication</strong></blockquote><ol><li><strong>Create a Firebase Project in Firebase Console :</strong></li></ol><ul><li>Go to Firebase Console and log in with your Google account.</li><li>Click on <strong>“Add Project”</strong> and enter a project name.</li><li>Once the project is ready, click <strong>“Continue”</strong> to access the Firebase dashboard.</li></ul><p>2. <strong>Enable Authentication Method :</strong></p><ul><li>In the Firebase dashboard, go to <strong>Build &gt; Authentication</strong>.</li><li>Click on the <strong>Sign-in method</strong> tab.</li><li>Enable the authentication method you need (e.g., <strong>Phone, Email/Password, Google Sign-In</strong>).</li><li>Save the changes.</li></ul><p>3. <strong>Register Your App and Get Firebase Config :</strong></p><ul><li>In the Firebase console, go to <strong>Project Settings</strong> (⚙️ icon in the left menu).</li><li>Under the <strong>General</strong> tab, find the <strong>“Your apps”</strong> section.</li><li>Click the <strong>“Add app”</strong> button and choose <strong>Web</strong> (&lt;/&gt; icon).</li><li>Enter a name for your app and click <strong>“Register app”</strong>.</li><li>Copy the Firebase <strong>config object</strong> shown on the screen.</li></ul><p>Now that your Firebase app is set up, it’s time to integrate it into our React application.</p><p>Since Create React App is deprecated, we’ll use Vite for a faster and more efficient React setup. Now, let’s integrate Firebase Authentication into our Vite-powered React app.</p><blockquote><strong>Installing Firebase and Setting Up the Config : (FrontEnd)</strong></blockquote><p>Install Firebase in your Vite React project by running:</p><pre>npm install firebase</pre><p>Next, create a firebaseConfig.js file inside the src folder and add your Firebase app configuration:</p><pre>// Import required Firebase services<br>import { initializeApp } from &quot;firebase/app&quot;;<br>import { getAuth } from &quot;firebase/auth&quot;;<br><br>// Your Firebase configuration<br>const firebaseConfig = {<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>  authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>  projectId: &quot;YOUR_PROJECT_ID&quot;,<br>  storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>  messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>  appId: &quot;YOUR_APP_ID&quot;<br>};<br><br>// Initialize Firebase<br>const app = initializeApp(firebaseConfig);<br>const auth = getAuth(app);<br><br>export { auth };</pre><blockquote><strong>Setting Up Firebase Admin SDK : (Backend)</strong></blockquote><p>To manage authentication and user data securely from the backend, we’ll use the <strong>Firebase Admin SDK</strong>. This is essential for handling user verification, token validation, and secure operations like managing user roles.</p><ol><li><strong>Install Firebase Admin SDK :</strong></li></ol><p>Run the following command in your backend project</p><pre>npm install firebase-admin</pre><p>2. <strong>Initialize Firebase Admin in Backend :</strong></p><pre>// backend/firebaseAdmin.js<br>import admin from &quot;firebase-admin&quot;;<br>//add sdk file to the director and import it<br>import serviceAccount from &quot;./path-to-your-service-account-key.json&quot;; <br><br>// Initialize Firebase Admin<br>admin.initializeApp({<br>  credential: admin.credential.cert(serviceAccount),<br>});<br><br>export default admin;</pre><p>3. <strong>Get Service Account Credentials :</strong></p><ul><li>Go to <strong>Firebase Console &gt; Project Settings</strong>.</li><li>Navigate to the <strong>Service accounts</strong> tab.</li><li>Click <strong>Generate new private key</strong>, and download the JSON file.</li><li>Move the file to your backend project and reference it in the config.</li></ul><p>with this now your backend can securely interact with Firebase Authentication.</p><blockquote><strong>FrontEnd Explanation: Mobile Authentication with Firebase in React</strong></blockquote><p>Now that we have Firebase set up, let’s integrate <strong>mobile authentication</strong> using Firebase Authentication. We’ll use <strong>phone number authentication</strong> with OTP verification, ensuring secure and seamless login.</p><ol><li><strong>Setting Up reCAPTCHA for Authentication :</strong></li></ol><p>Firebase requires <strong>reCAPTCHA verification</strong> to prevent abuse when using phone authentication. In our UserAuthContextProvider, we initialize <strong>reCAPTCHA</strong> and provide it globally using React Context:</p><pre>import { createContext, useContext, useEffect, useState } from &quot;react&quot;;<br>import { RecaptchaVerifier } from &quot;firebase/auth&quot;;<br>import { auth } from &quot;./firebase&quot;;<br><br>const userAuthContext = createContext();<br><br>export function UserAuthContextProvider({ children }) {<br>  const [recaptchaVerifier, setRecaptchaVerifier] = useState(null);<br><br>  function setUpRecaptcha() {<br>    const recaptchaVerifier = new RecaptchaVerifier(auth, &quot;recaptcha-container&quot;, {<br>      size: &quot;invisible&quot;,<br>      callback: (response) =&gt; {<br>        console.log(&quot;✅ reCAPTCHA verified:&quot;, response);<br>      },<br>      &quot;expired-callback&quot;: () =&gt; {<br>        console.log(&quot;❌ reCAPTCHA expired, please refresh.&quot;);<br>      },<br>    });<br><br>    setRecaptchaVerifier(recaptchaVerifier);<br>  }<br><br>  useEffect(() =&gt; {<br>    setUpRecaptcha();<br>  }, []);<br><br>  return (<br>    &lt;userAuthContext.Provider value={{ recaptchaVerifier }}&gt;<br>      {children}<br>    &lt;/userAuthContext.Provider&gt;<br>  );<br>}<br><br>export function useUserAuth() {<br>  return useContext(userAuthContext);<br>}</pre><ul><li><strong>RecaptchaVerifier</strong> ensures that only real users can request OTPs.</li><li>We initialize <strong>reCAPTCHA</strong> inside useEffect() so it loads automatically.</li><li>The <strong>context</strong> makes recaptchaVerifier available to all components.</li></ul><p>2. <strong>Phone Authentication Component :</strong></p><p>Let’s create a simple UI that includes an input field for the phone number with a <strong>“Send OTP”</strong> button, followed by a <strong>“Verify OTP”</strong> UI where users can enter the received OTP and authenticate themselves.</p><pre>import React, { useState } from &quot;react&quot;;<br>import { Button, Form } from &quot;react-bootstrap&quot;;<br>import &quot;react-phone-number-input/style.css&quot;;<br>import PhoneInput from &quot;react-phone-number-input&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br>import { auth } from &quot;./firebase&quot;;  <br>import { useUserAuth } from &quot;./UserAuthContext&quot;;<br>import { signInWithPhoneNumber } from &quot;firebase/auth&quot;;<br>import axios from &quot;axios&quot;;<br><br>function PhoneSignup() { <br>  const { recaptchaVerifier } = useUserAuth(); // Get reCAPTCHA from context<br>  const [phone, setPhone] = useState(&quot;&quot;);<br>  const [otp, setOtp] = useState(&quot;&quot;);<br>  const [error, setError] = useState(&quot;&quot;);<br>  const [confirmationResult, setConfirmationResult] = useState(null);<br>  const [otpSent, setOtpSent] = useState(false);<br><br>  const getOtp = async (e) =&gt; {<br>    e.preventDefault();<br>    setError(&quot;&quot;);<br><br>    if (!phone) {<br>      setError(&quot;Please enter a valid phone number.&quot;);<br>      return;<br>    }<br><br>    try {<br>      if (!recaptchaVerifier) {<br>        setError(&quot;reCAPTCHA not initialized. Please refresh.&quot;);<br>        return;<br>      }<br><br>      const confirmation = await signInWithPhoneNumber(auth, phone, recaptchaVerifier);<br><br>      setConfirmationResult(confirmation);<br>      setOtpSent(true);<br>      console.log(&quot;✅ OTP sent successfully to:&quot;, phone);<br>    } catch (error) {<br>      console.error(&quot;❌ Error sending OTP:&quot;, error);<br>      setError(&quot;Failed to send OTP. Please try again.&quot;);<br>    }<br>  };<br><br>  <br>const verifyOtp = async (e) =&gt; {<br>  e.preventDefault();<br>  setError(&quot;&quot;);<br><br>  if (!otp || !confirmationResult) {<br>    setError(&quot;Please enter the OTP.&quot;);<br>    return;<br>  }<br><br>  try {<br>    const result = await confirmationResult.confirm(otp);<br>    const firebaseToken = await result.user.getIdToken(); // Get Firebase ID token<br><br>    // Send token to backend for verification<br>    const response = await axios.post(&quot;http://localhost:5000/api/auth/mobileAuth&quot;, { firebaseToken });<br><br>    console.log(&quot;✅ Server Response:&quot;, response.data);<br>    alert(&quot;Phone number verified successfully!&quot;);<br><br>  } catch (error) {<br>    console.error(&quot;❌ Error verifying OTP:&quot;, error);<br>    setError(&quot;Invalid OTP. Please try again.&quot;);<br>  }<br>};<br><br>  return (<br>    &lt;div style={{display:&quot;flex&quot;, justifyContent:&quot;center&quot;, alignItems:&quot;center&quot;, height:&quot;100%&quot;, margin:&quot;0px&quot;, padding:&quot;0px&quot;}}&gt;<br>      &lt;div style={{backgroundColor:&quot;green&quot;, padding:&quot;20px&quot;, height:&quot;400px&quot;, width:&quot;350px&quot;}}&gt;<br>        &lt;h2 style={{padding:&quot;20px&quot;}} className=&quot;mb-3&quot;&gt;Firebase Auth Login&lt;/h2&gt;<br>        {!otpSent ? (<br>          &lt;Form onSubmit={getOtp}&gt;<br>            &lt;Form.Group className=&quot;mb-3&quot; controlId=&quot;formBasicPhoneNumber&quot;&gt;<br>              &lt;PhoneInput<br>                defaultCountry=&quot;IN&quot;<br>                type=&quot;tel&quot;<br>                placeholder=&quot;Enter phone number&quot;<br>                value={phone}<br>                onChange={setPhone}<br>              /&gt;<br>            &lt;/Form.Group&gt;<br>            &lt;div id=&quot;recaptcha-container&quot;&gt;&lt;/div&gt;<br><br>            {error &amp;&amp; &lt;p style={{ color: &quot;red&quot; }}&gt;{error}&lt;/p&gt;}<br><br>            &lt;div className=&quot;button-right&quot;&gt;<br>              &lt;Link to=&quot;/&quot;&gt;<br>                &lt;Button variant=&quot;secondary&quot;&gt;Cancel&lt;/Button&gt;<br>              &lt;/Link&gt;<br>              &lt;Button variant=&quot;primary&quot; type=&quot;submit&quot;&gt;<br>                Send OTP<br>              &lt;/Button&gt;<br>            &lt;/div&gt;<br>          &lt;/Form&gt;<br>        ) : (<br>          &lt;Form onSubmit={verifyOtp}&gt;<br>            &lt;Form.Group className=&quot;mb-3&quot;&gt;<br>              &lt;Form.Control<br>                type=&quot;text&quot;<br>                placeholder=&quot;Enter OTP&quot;<br>                value={otp}<br>                onChange={(e) =&gt; setOtp(e.target.value)}<br>              /&gt;<br>            &lt;/Form.Group&gt;<br>            {error &amp;&amp; &lt;p style={{ color: &quot;red&quot; }}&gt;{error}&lt;/p&gt;}<br>            &lt;Button variant=&quot;success&quot; type=&quot;submit&quot;&gt;<br>              Verify OTP<br>            &lt;/Button&gt;<br>          &lt;/Form&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default PhoneSignu</pre><blockquote>Note: we need to define a div with a id which will be passed as parameter when creating captcha (In context)</blockquote><blockquote>example : &lt;div id=”recaptcha-container”&gt;&lt;/div&gt;</blockquote><p>Now, let’s break down how mobile authentication works in this React component using Firebase.</p><blockquote><strong>Sending OTP for Phone Authentication</strong></blockquote><pre>const getOtp = async (e) =&gt; {<br>    e.preventDefault();<br>    setError(&quot;&quot;);<br><br>    if (!phone) {<br>      setError(&quot;Please enter a valid phone number.&quot;);<br>      return;<br>    }<br><br>    try {<br>      if (!recaptchaVerifier) {<br>        setError(&quot;reCAPTCHA not initialized. Please refresh.&quot;);<br>        return;<br>      }<br><br>      const confirmation = await signInWithPhoneNumber(auth, phone, recaptchaVerifier);<br><br>      setConfirmationResult(confirmation);<br>      setOtpSent(true);<br>      console.log(&quot;✅ OTP sent successfully to:&quot;, phone);<br>    } catch (error) {<br>      console.error(&quot;❌ Error sending OTP:&quot;, error);<br>      setError(&quot;Failed to send OTP. Please try again.&quot;);<br>    }<br>  };</pre><ul><li>When the user clicks Send OTP it triggers getOtp function.</li><li>Check if the phone number is entered comparing the state</li><li>Verify reCAPTCHA is initialized</li><li>Send OTP using signInWithPhoneNumber</li><li>Store the confirmation result : Saves confirmationResult for later OTP verification. Updates UI to show OTP input field.</li></ul><blockquote>Note : signInWithPhoneNumber(auth, phone, recaptchaVerifier) is a Firebase Authentication method used to send an OTP to a user&#39;s phone number. Takes three parameters:</blockquote><ul><li>auth → Firebase authentication instance</li><li>phone → User’s phone number</li><li>recaptchaVerifier → Ensures the request is from a real user (we are passing the recaptha defined in context)</li></ul><blockquote><strong>Verifying OTP for Phone Authentication</strong></blockquote><p>After the OTP is received, the user enters it, and we verify it using Firebase. If valid, we generate a Firebase ID token and send it to the backend for further authentication.</p><pre>const verifyOtp = async (e) =&gt; {<br>  e.preventDefault();<br>  setError(&quot;&quot;);<br><br>  if (!otp || !confirmationResult) {<br>    setError(&quot;Please enter the OTP.&quot;);<br>    return;<br>  }<br><br>  try {<br>    const result = await confirmationResult.confirm(otp);<br>    const firebaseToken = await result.user.getIdToken(); // Get Firebase ID token<br><br>    // Send token to backend for verification<br>    const response = await axios.post(&quot;http://localhost:5000/api/auth/mobileAuth&quot;, { firebaseToken });<br><br>    console.log(&quot;✅ Server Response:&quot;, response.data);<br>    alert(&quot;Phone number verified successfully!&quot;);<br><br>  } catch (error) {<br>    console.error(&quot;❌ Error verifying OTP:&quot;, error);<br>    setError(&quot;Invalid OTP. Please try again.&quot;);<br>  }<br>};</pre><p><strong>How It Works (Step-by-Step) :</strong></p><ul><li>Validate OTP Input: Checks if the OTP is entered and if confirmationResult exists.</li><li>Confirm OTP : Uses confirmationResult.confirm(otp) to verify the OTP. If successful, it return a user object.</li><li>Get Firebase Token : Call result.user.getIdToken() to retrieve a unique Firebase token.</li><li>Send Token to Backend : Sens the Firebase token to the server using an axios.post request for verification.</li><li>Handle Success &amp; Errors</li></ul><blockquote><strong>Backend Explanation: Phone Authentication with Firebase and MongoDB</strong></blockquote><p>This backend setup enables mobile authentication using Firebase and stores user data in MongoDB.</p><ol><li><strong>Server Setup (</strong><strong>server.js) :</strong></li></ol><pre>import express from &quot;express&quot;;<br>import cors from &quot;cors&quot;;<br>import mongoose from &quot;mongoose&quot;;<br>import authRoutes from &quot;./Routes.js&quot;;<br><br>const app = express();<br>const PORT = 5000;<br><br>// Middleware<br>app.use(cors());<br>app.use(express.json());<br>app.use(&quot;/api/auth&quot;, authRoutes);<br><br>// MongoDB Connection Function<br>async function MongodbConnection(url) {<br>    return mongoose.connect(url);<br>}<br><br>// Connect to MongoDB and Start Server<br>MongodbConnection(&quot;YOUR MONGODB URI&quot;)<br>    .then(() =&gt; {<br>        console.log(&quot;✅ MongoDB connected&quot;);<br>        app.listen(PORT, () =&gt; console.log(`🚀 Server running on port ${PORT}`));<br>    })<br>    .catch((error) =&gt; {<br>        console.error(&quot;❌ Error connecting to MongoDB:&quot;, error);<br>    });</pre><ul><li>When a request comes to <strong>/api/auth</strong>, the server <strong>redirects it</strong> to authRoutes.</li><li>authRoutes then handles authentication-related requests.</li></ul><p>2.<strong> API Route (</strong><strong>Routes.js) Handles Mobile Authentication Requests :</strong></p><pre>import express from &quot;express&quot;;<br>import { verifyMobileAuth } from &quot;./Controller.js&quot;;<br><br>const router = express.Router();<br><br>router.post(&quot;/mobileAuth&quot;, verifyMobileAuth);<br><br>export default router;</pre><ul><li>When a POST request is sent to <strong>/api/auth/mobileAuth</strong>, it calls the verifyMobileAuth function from Controller.js.</li></ul><p>3.<strong> Mobile Authentication Controller (</strong><strong>Controller.js) :</strong></p><p>This <strong>handles</strong> mobile authentication requests by verifying the Firebase token and checking if the user exists in MongoDB.</p><pre>import { admin } from &quot;./firebaseAdmin.js&quot;;<br>import { UserAuthDataModel } from &quot;./Model.js&quot;;<br><br>async function verifyMobileAuth(req, res) {<br>  console.log(&quot;Received request:&quot;, req.body); <br><br>  const { firebaseToken } = req.body;<br>  if (!firebaseToken) {<br>    return res.status(400).json({ error: &quot;Firebase token is required&quot; });<br>  }<br><br>  try {<br>    const decodedToken = await admin.auth().verifyIdToken(firebaseToken);<br>    console.log(&quot;Decoded token:&quot;, decodedToken); <br><br>    const phoneNumber = decodedToken.phone_number;<br>    if (!phoneNumber) {<br>      return res.status(400).json({ error: &quot;Invalid phone number&quot; });<br>    }<br><br>    let user = await UserAuthDataModel.findOne({ mobile: phoneNumber });<br><br>    if (!user) {<br>      user = new UserAuthDataModel({ mobile: phoneNumber, isVerified: true });<br>      await user.save();<br>      console.log(&quot;User saved:&quot;, user);<br>      return res.status(201).json({ message: &quot;User registered successfully&quot;, user });<br>    }<br><br>    return res.status(200).json({ message: &quot;User already exists&quot;, user });<br>  } catch (error) {<br>    console.error(&quot;❌ Error verifying Firebase token:&quot;, error);<br>    return res.status(500).json({ error: &quot;Internal server error&quot; });<br>  }<br>}<br><br>export { verifyMobileAuth };</pre><ul><li>The function receives a request with a <strong>Firebase token</strong> from the frontend.</li><li>If the token is missing, an error is returned.</li><li>The token is verified using admin.auth().verifyIdToken(firebaseToken).</li><li>Extracts phone_number from the decoded token.</li><li>Searches MongoDB to see if the phone number exists.</li><li>If the user is <strong>new</strong>, they are added to the database.</li><li>Return a success response with user details.</li></ul><p>4.<strong> Mobile Authentication Model (</strong><strong>Model.js) :</strong></p><p>Define the <strong>Mongoose schema</strong> for storing <strong>mobile authentication users</strong> in MongoDB.</p><pre>import mongoose from &quot;mongoose&quot;;<br><br>const UserAuthSchema = new mongoose.Schema({<br>  mobile: { type: String, required: true, unique: true },<br>  isVerified: { type: Boolean, default: false },<br>  createdAt: { type: Date, default: Date.now },<br>});<br><br>const UserAuthDataModel = mongoose.model(&quot;Mobile&quot;, UserAuthSchema);<br><br>export { UserAuthDataModel };</pre><blockquote>And just like that, you’ve implemented Firebase mobile authentication in your React app! ✅</blockquote><p>Now, let’s take a look at the responses we get at different stages — when reCAPTCHA is verified, the user is authenticated, and their data is stored in MongoDB.</p><p>Here are some screenshots showcasing the authentication flow — from verifying reCAPTCHA to storing user data in MongoDB.</p><ol><li>Entering the mobile number and requesting an OTP: reCAPTCHA verified and successful server response</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*Elt0tKqnsO8cPoJJdqCXEQ.png" /><figcaption>Enter mobile number UI!</figcaption></figure><p>2. Verifying OTP: Authentication successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PaFtGbKeRgKfRtBk4uurw.png" /><figcaption>Successful Verification</figcaption></figure><p>3. User data successfully stored in MongoDB after OTP verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IdppP5AogAhzn40nvTFCA.png" /><figcaption>Data Stored on MongoDB</figcaption></figure><p>In this blog, we explored how to implement Firebase Mobile Authentication in a Vite-powered React application. We covered:</p><p>✅ Setting up Firebase and configuring authentication<br>✅ Implementing reCAPTCHA and OTP-based login in React<br>✅ Handling user verification and authentication responses<br>✅ Storing authenticated user data in MongoDB</p><p>With this setup, you now have a secure and scalable mobile authentication system integrated into your React app. Feel free to experiment further by adding features like multi-factor authentication, social logins, or user role management. If you have any questions or insights, let me know in the comments I’d love to hear your thoughts!</p><p>Stay tuned for more blogs on building web applications using MERN and exploring the latest trending tools! 🔥</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee832e3b529b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks 101: Essential React Hooks for Optimized Development]]></title>
            <link>https://medium.com/@anthonysebastinj/react-hooks-101-essential-react-hooks-for-optimized-development-1b31c0ce1758?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b31c0ce1758</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 13:31:29 GMT</pubDate>
            <atom:updated>2025-02-01T13:41:16.167Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to build scalable, high-performance React apps with these core hooks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJ4mqbBcbvb_WgqL8hapRQ.jpeg" /></figure><p>Hey there, Devs! 👨‍💻 Welcome back.</p><p>Previously, we explored building CRUD APIs with Node.js, Express, and MongoDB, focusing on creating, reading, updating, and deleting data. If you missed it, no worries — you can check it out 🔗<a href="https://medium.com/@anthonysebastinj/building-crud-apis-with-ease-node-js-and-mongodb-in-action-3e2c3c10a8b2">here</a>.</p><p>Now, let’s shift to the frontend! Managing APIs is important, but handling state and side effects in React is just as crucial. That’s where React Hooks come in — simplifying state management, context sharing, and performance optimization.</p><p>In this guide, we’ll dive into essential hooks and advanced techniques to improve your React app’s efficiency.</p><blockquote>So without any delay, Let’s get started!🚀</blockquote><blockquote>Understanding React Hooks</blockquote><p>Before React introduced hooks, managing state and side effects in functional components was not possible, and developers had to rely on class components for these tasks. React hooks revolutionized this by enabling functional components to handle state, lifecycle events, and context without the need for classes.</p><p>React hooks are JavaScript functions that allow you to “hook into” React features, such as state, lifecycle methods, and context, within functional components. They help make components more concise, reusable, and easier to maintain.</p><p>Some of the key hooks that have become essential in modern React development include:</p><blockquote><strong>useState : Managing Local Component State</strong></blockquote><p>In React, state is a way to store and manage data that changes over time within a component. For example, When working with APIs in React, we often need to store and update data fetched from an external source. The useState hook makes this easy by allowing us to manage data inside functional components.</p><p>Imagine we need to fetch a list of users from an API and display them in our React app. We can use useState to manage this data efficiently.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>function UsersList() {<br><br>  const [users, setUsers] = useState([]); // Stores API data<br><br>    async function DataFromResource() {<br>      try {<br>        const response = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;); <br>        const finalData = await response.json();<br>        setUsers(finalData);<br>      } catch (error) {<br>        console.log(&quot;Trouble fetching data&quot;, error);<br>      }<br>    }<br><br>  useEffect(() =&gt; {<br>        DataFromResource();<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;User List&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {users.map((user) =&gt; (<br>          &lt;li key={user.id}&gt;{user.name} - {user.email}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UsersList;</pre><p>When you call useState, you pass an initial value to it. This initial value is the state of the component when it first renders. useState returns an array with two items:</p><ol><li><strong>State variable</strong> — Holds the current state.</li><li><strong>State updater function</strong> — Used to update the state.</li></ol><p>useState([]) initializes the users state as an empty array. This is where we&#39;ll store the list of users fetched from the API.</p><ul><li><strong>users</strong> holds the current value of the state (initially an empty array).</li><li><strong>setUsers</strong> updates the users state with the fetched data (finalData), causing React to re-render the component and display the list of users.</li></ul><p>After the state is updated, you can use the <strong>current state</strong> (users array) to render and display the data dynamically in your component. In this case, we map over the users array to display each user&#39;s name and email.</p><blockquote><strong>useEffect : to Handle Side Effects</strong></blockquote><p>In React, we shouldn’t directly place tasks like fetching data inside the main part of our component. Instead, we use the useEffect hook to manage such tasks. This way, we can control when the code runs-either when the component first loads or when certain values change.</p><p>Example, let’s take a look at how we can use useEffect to fetch data from an API and update the component’s state:</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>function AuthorPosts() {<br>  const [authors, setAuthors] = useState([]); // Stores list of authors<br>  const [selectedAuthorId, setSelectedAuthorId] = useState(1); // Stores selected author ID<br>  const [posts, setPosts] = useState([]); // Stores posts of selected author<br><br>  async function fetchAuthors() {<br>      const response = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>      const data = await response.json();<br>      setAuthors(data);<br>    }<br><br>  // Fetch authors from the API when the component mounts<br>  useEffect(() =&gt; {<br>    fetchAuthors();<br>  }, []); // Runs only once when the component mounts<br><br>  async function fetchPosts() {<br>      const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${selectedAuthorId}`);<br>      const data = await response.json();<br>      setPosts(data);<br>    }<br><br>  // Fetch posts based on the selected author<br>  useEffect(() =&gt; {<br>    fetchPosts();<br>  }, [selectedAuthorId]); // Runs every time when the selectedAuthorId changes<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Posts by Author&lt;/h2&gt;<br>      <br>      {/* Dropdown to select an author */}<br>      &lt;select onChange={(e) =&gt; setSelectedAuthorId(e.target.value)} value={selectedAuthorId}&gt;<br>        {authors.map((author) =&gt; (<br>          &lt;option key={author.id} value={author.id}&gt;<br>            {author.name}<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br><br>      {/* Display posts for the selected author */}<br>      &lt;div&gt;<br>        {posts.length &gt; 0 ? (<br>          posts.map((post) =&gt; (<br>            &lt;div key={post.id}&gt;<br>              &lt;h3&gt;{post.title}&lt;/h3&gt;<br>              &lt;p&gt;{post.body}&lt;/p&gt;<br>            &lt;/div&gt;<br>          ))<br>        ) : (<br>          &lt;p&gt;No posts available&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default AuthorPosts;</pre><p>In the above code snippet, we see two useEffect hooks—one with an empty dependency array and one with a dependency inside the array. So, how do they differ? Let’s take a look!</p><p>1. useEffect (empty array) — Execute Once on Component Mount :</p><pre>useEffect(() =&gt; {<br>  async function fetchAuthors() {<br>    const response = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>    const data = await response.json();<br>    setAuthors(data);<br>  }<br>  fetchAuthors();<br>}, []);//empty array</pre><ul><li>The <strong>empty array (</strong><strong>[])</strong> means this effect runs <strong>only once</strong>, right after the component loads.</li><li>It <strong>fetches the list of authors</strong> and updates the authors state.</li><li>Since there are <strong>no dependencies</strong>, React <strong>does not run this effect again</strong>.</li></ul><p>2. useEffect (With Dependency) — Runs on Dependency Update :</p><pre>useEffect(() =&gt; {<br>  async function fetchPosts() {<br>    const response = await fetch(<br>      `https://jsonplaceholder.typicode.com/posts?userId=${selectedAuthorId}`<br>    );<br>    const data = await response.json();<br>    setPosts(data);<br>  }<br>  fetchPosts();<br>}, [selectedAuthorId]);//array with dependency </pre><p>The <strong>dependency array contains </strong><strong>[selectedAuthorId]</strong>, meaning:</p><ul><li>The useEffect Re-renders the component whenever the value of <strong>selectedAuthorId</strong> changes (i.e., when the user selects a different author from the dropdown).</li><li>avoids un-necessary Re-renders</li><li>It <strong>fetches posts</strong> for the newly selected author and updates the posts state.</li></ul><blockquote><strong>useContext : for State Management</strong></blockquote><p>useContext is a powerful React hook that allows you to share values across multiple components without passing props down manually at every level. It’s especially useful when you need to manage global state or share data between deeply nested components.</p><p><strong>Steps to implement the useContext :</strong></p><ol><li>First, we create a separate file for the DataProvider component, where we’ll define our context and the state management logic.</li></ol><ul><li>File: DataProvider.js</li></ul><pre>import React, { createContext, useState, useEffect } from &quot;react&quot;;<br><br>// create the context<br>export const DataContext = createContext();<br><br>//write a function to provide the data accross components<br>export function DataProvider({ children }) {<br>  const [authors, setAuthors] = useState([]);<br>  const [selectedAuthorId, setSelectedAuthorId] = useState(1);<br>  const [posts, setPosts] = useState([]);<br><br>  async function fetchAuthors() {<br>      const response = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>      const data = await response.json();<br>      setAuthors(data);<br>    }<br><br>  useEffect(() =&gt; {<br>    fetchAuthors();<br>  }, []); <br><br>  async function fetchPosts() {<br>      const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${selectedAuthorId}`);<br>      const data = await response.json();<br>      setPosts(data);<br>    }<br><br>  useEffect(() =&gt; {<br>    fetchPosts();<br>  }, [selectedAuthorId]);<br><br>  return (<br>//return the context with data that should be passed to the child components<br>    &lt;DataContext.Provider value={{ authors, selectedAuthorId, setSelectedAuthorId, posts }}&gt;<br>      {children}  {/* Allows nested components to access the context */}<br>    &lt;/DataContext.Provider&gt;<br>  );<br>}</pre><ul><li>First, we need to create the context by using createContext(). This creates a context object that will be shared with other components.</li><li>Next, we create a function called DataProvider that accepts child components as a parameter. This function will act as a wrapper for the components that need access to the shared data.</li><li>Inside this function, you can define the data (e.g., state variables) that you want to share with the child components.</li><li>Now, you need to provide the defined data to the child components. To do this, you wrap the {children} component in the DataContext.Provider tag and pass the data using the value attribute.</li></ul><pre>return (<br>    &lt;DataContext.Provider value={{ authors, selectedAuthorId, setSelectedAuthorId, posts }}&gt;<br>      {children}  {/* Allows nested components to access the context */}<br>    &lt;/DataContext.Provider&gt;<br>  );</pre><ul><li>By doing this, any component wrapped in the DataProvider will have access to the shared state, which can be consumed using useContext(DataContext).</li></ul><p><strong>2. Create the Component that Consumes the Context</strong></p><p>Next, we create the component that will consume the context and display the data.</p><ul><li>File: AuthorPosts.js</li></ul><pre>import React, { useContext } from &quot;react&quot;;<br>import { DataContext } from &quot;./DataProvider&quot;; // Import the context<br><br>function AuthorPosts() {<br>  const { authors, selectedAuthorId, setSelectedAuthorId, posts } = useContext(DataContext); // Consume context<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Posts by Author&lt;/h2&gt;<br>      <br>      {/* Dropdown to select an author */}<br>      &lt;select onChange={(e) =&gt; setSelectedAuthorId(e.target.value)} value={selectedAuthorId}&gt;<br>        {authors.map((author) =&gt; (<br>          &lt;option key={author.id} value={author.id}&gt;<br>            {author.name}<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br><br>      {/* Display posts for the selected author */}<br>      &lt;div&gt;<br>        {posts.length &gt; 0 ? (<br>          posts.map((post) =&gt; (<br>            &lt;div key={post.id}&gt;<br>              &lt;h3&gt;{post.title}&lt;/h3&gt;<br>              &lt;p&gt;{post.body}&lt;/p&gt;<br>            &lt;/div&gt;<br>          ))<br>        ) : (<br>          &lt;p&gt;No posts available&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default AuthorPosts;</pre><ul><li>now in this file we are going to use the data passed from context, so how do we do it? let see</li><li><strong>Import the context</strong> from the file where it was created:</li><li>Inside the child component, use the useContext() hook to access the data provided by the context. Pass the context (DataContext) into useContext() to access the shared data.</li></ul><pre>const { authors, selectedAuthorId, setSelectedAuthorId, posts } = useContext(DataContext);</pre><ul><li>You can now use the variables (authors, selectedAuthorId, setSelectedAuthorId, posts) as regular state variables inside your child component.</li><li>By using useContext(), you&#39;re accessing the context and its provided data, allowing you to use it in the component without manually passing it as props.</li></ul><p><strong>3. Set Up the Main App Component</strong></p><p>Now, in the main app component, we’ll import the DataProvider and wrap the entire app in it so that all the components inside can access the context.</p><ul><li>File: App.js</li></ul><pre>import React from &quot;react&quot;;<br>import { DataProvider } from &quot;./DataProvider&quot;;  // Import the DataProvider<br>import AuthorPosts from &quot;./AuthorPosts&quot;;  // Import the AuthorPosts component<br><br>function App() {<br>  return (<br>    &lt;DataProvider&gt;<br>      &lt;AuthorPosts /&gt;<br>    &lt;/DataProvider&gt;<br>  );<br>}<br><br>export default App;</pre><ul><li>Here, the DataProvider component wraps the AuthorPosts component, providing it (and any other child components) with the shared context.</li><li>Now, any child component inside DataProvider can access the data provided through the context.</li></ul><blockquote><strong>useCallback : to Memoize Functions</strong></blockquote><p>In React, the useCallback hook is used to <strong>memoize</strong> functions, preventing them from being recreated on every render. This is particularly helpful for improving performance, especially when functions are passed to child components or used in other hooks like useEffect.</p><p>Without useCallback, every time a component re-renders, <strong>all</strong> functions defined inside it are recreated. This can lead to unnecessary work and inefficient re-renders, especially if the functions are passed down as props or used in dependencies.</p><p>Using useCallback ensures that the function is only <strong>recreated</strong> when its dependencies (such as state or props) change. If there are no dependencies or the dependencies haven&#39;t changed, React will reuse the memoized version of the function, improving performance by avoiding unnecessary re-creations.</p><pre>import React, { useState, useEffect, useCallback } from &quot;react&quot;;<br><br>function AuthorPosts() {<br>  const [authors, setAuthors] = useState([]);<br>  const [selectedAuthorId, setSelectedAuthorId] = useState(1);<br>  const [posts, setPosts] = useState([]);<br><br>  // Memoize the fetchAuthors function to avoid re-creating it on each render<br>  const fetchAuthors = useCallback(async () =&gt; {<br>    const response = await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;);<br>    const data = await response.json();<br>    setAuthors(data);<br>  }, []); // Empty dependency array ensures this function is created once<br><br>  // Memoize the fetchPosts function to avoid re-creating it on each render<br>  const fetchPosts = useCallback(async () =&gt; {<br>    const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${selectedAuthorId}`);<br>    const data = await response.json();<br>    setPosts(data);<br>  }, [selectedAuthorId]); // Function is re-created only when selectedAuthorId changes<br><br>  useEffect(() =&gt; {<br>    fetchAuthors();<br>  }, [fetchAuthors]); <br><br>  useEffect(() =&gt; {<br>    fetchPosts();<br>  }, [fetchPosts]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Posts by Author&lt;/h2&gt;<br>      <br>      {/* Dropdown to select an author */}<br>      &lt;select onChange={(e) =&gt; setSelectedAuthorId(e.target.value)} value={selectedAuthorId}&gt;<br>        {authors.map((author) =&gt; (<br>          &lt;option key={author.id} value={author.id}&gt;<br>            {author.name}<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br><br>      {/* Display posts for the selected author */}<br>      &lt;div&gt;<br>        {posts.length &gt; 0 ? (<br>          posts.map((post) =&gt; (<br>            &lt;div key={post.id}&gt;<br>              &lt;h3&gt;{post.title}&lt;/h3&gt;<br>              &lt;p&gt;{post.body}&lt;/p&gt;<br>            &lt;/div&gt;<br>          ))<br>        ) : (<br>          &lt;p&gt;No posts available&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default AuthorPosts;</pre><p>What Does useCallback Do?</p><ul><li><strong>With an empty dependency array </strong><strong>[]</strong>:<br>The fetchAuthors function is <strong>memoized</strong> and will only be created once, during the initial render of the component. It will not be recreated on subsequent renders unless the component is unmounted and mounted again. This is ideal when the function doesn&#39;t depend on any state or props that might change.</li><li><strong>With a dependency array </strong><strong>[selectedAuthorId]</strong>:<br>The fetchPosts function is <strong>memoized</strong> as well, but it will only be recreated when the selectedAuthorId changes. This ensures that the function reflects the most up-to-date selectedAuthorId when the user selects a different author. Using the dependency array prevents unnecessary re-creations of the function when selectedAuthorId hasn&#39;t changed.</li></ul><blockquote><strong>useMemo : Optimizing Expensive Calculations in React</strong></blockquote><p>In React, the useMemo hook is used to <strong>memoize</strong> the results of expensive calculations or operations, ensuring that the calculation is only re-executed when necessary.</p><p>By default, React re-renders components every time the state or props change, and during each render, all calculations inside the component will be re-executed. If these calculations are expensive (e.g., complex loops, filtering, or sorting), it could lead to performance issues.</p><p>Using useMemo, we can &quot;remember&quot; (memoize) the result of a calculation and return the memoized result instead of re-running the calculation on every render.</p><p>Example of Using useMemo :</p><p>Suppose you have a component that calculates the sum of an array of numbers. Without useMemo, this calculation would be done on every render. But by using useMemo, we can make sure the sum is only recalculated when the numbers change.</p><pre>import React, { useState, useMemo } from &#39;react&#39;;<br><br>function SumCalculator() {<br>  const [numbers, setNumbers] = useState([1, 2, 3, 4, 5]);<br><br>  // Memoize the sum calculation to avoid recalculating on every render<br>  const sum = useMemo(() =&gt; {<br>    console.log(&quot;Calculating sum...&quot;);<br>    return numbers.reduce((acc, num) =&gt; acc + num, 0);<br>  }, [numbers]); // Recalculate only when numbers array changes<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Sum of Numbers: {sum}&lt;/h2&gt;<br><br>      &lt;button onClick={() =&gt; setNumbers([...numbers, Math.floor(Math.random() * 10)])}&gt;<br>        Add Random Number<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default SumCalculator;</pre><ul><li>When the component renders initially it performs the calculations and memoize it so.</li><li>On each render, the sum is <strong>not recalculated</strong> unless the numbers array changes.</li></ul><blockquote>And that’s a wrap — another powerful tool in your React toolkit!✅</blockquote><p>In this blog, we explored the core React hooks: <strong>useState</strong>, <strong>useEffect</strong>, <strong>useContext</strong>, <strong>useCallback</strong>, and <strong>useMemo</strong>. We covered how to use each hook effectively, from managing component state to optimizing performance with memoization techniques.</p><p>Mastering these hooks is essential for building efficient and dynamic React applications. Understanding how to handle state, side effects, context, and function optimization will significantly enhance the performance and scalability of your projects.</p><p>Stay tuned for the next blog, where we’ll explore more about advanced JavaScript topics like <strong>higher-order functions</strong>, <strong>asynchronous programming</strong>, and more. These concepts are crucial for React developers and will help you write cleaner, more efficient code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b31c0ce1758" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building CRUD APIs with Ease: Node.js and MongoDB in Action]]></title>
            <link>https://medium.com/@anthonysebastinj/building-crud-apis-with-ease-node-js-and-mongodb-in-action-3e2c3c10a8b2?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2c3c10a8b2</guid>
            <category><![CDATA[crud-operations]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mern-stack]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 09:16:19 GMT</pubDate>
            <atom:updated>2024-12-22T09:19:24.294Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance your development skills with CRUD operations in Node.js and MongoDB.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Y9PdZAT2upHw_vRgHCLsVg.png" /></figure><p>Hey there, Devs! 👨‍💻 Welcome back.</p><p>Last time, we explored connecting React with a backend API using Node.js, Express, and MongoDB. It was all about fetching and displaying real-time data. Missed it? Don’t worry, you can catch the action 🔗<a href="https://medium.com/@anthonysebastinj/react-and-real-time-data-fetching-and-displaying-data-from-your-backend-api-682aca27e643"><strong>here</strong></a>.</p><p>Now, it’s time to level up! This post will focus on CRUD operations — because what good is an API if you can’t create, read, update, and delete data?</p><blockquote>So without any delay, Let’s get started!🚀</blockquote><blockquote><strong>Setting Up the Environment</strong></blockquote><p>Before we look into the code, make sure you have the following installed:</p><ul><li>Node.js</li><li>MongoDB</li><li>Postman<strong> </strong>(optional, for API testing)</li></ul><p>Also, ensure you’ve created a <strong>MongoDB cluster</strong> on MongoDB Atlas or are running a local instance.</p><blockquote><strong>Connecting to MongoDB</strong></blockquote><p>With the mvc architecture we’ve been implemented from the starting of this series, let’s utilize the same pattern for the CRUD Operations. If you have missed it you can always get it 🔗<a href="https://medium.com/@anthonysebastinj/streamlining-mern-development-with-mvc-architecture-c63a8c7c43b0"><strong>here</strong></a>!</p><p>Create a file called <strong>Connection.js </strong>in the server folder to establish a MongoDB connection:</p><pre>import mongoose from &#39;mongoose&#39;;<br><br>export const MongodbConnection = async (URI) =&gt; {<br>    try {<br>        await mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true });<br>        console.log(&quot;MongoDB connected successfully&quot;);<br>    } catch (error) {<br>        console.error(&quot;MongoDB connection failed:&quot;, error);<br>        throw error;<br>    }<br>};</pre><ul><li>You need to import the <strong>Mongoose</strong> library, which is used to interact with MongoDB.</li><li>The MongodbConnection function is exported so it can be used in other parts of your application.</li><li>It accepts a parameter URI, which is the MongoDB connection string (the address of your database).</li></ul><blockquote><strong>The Server Setup</strong></blockquote><p>Create a file called <strong>serverConf.js</strong> in the server folder that encapsulates this server configuration, Here&#39;s how you can structure the file:</p><pre>import express from &#39;express&#39;;<br>import cors from &#39;cors&#39;;<br>import { MongodbConnection } from &#39;./Connection.js&#39;;<br>import userRoutes from &#39;./routes/Users.js&#39;;<br><br>const app = express();<br>const PORT = process.env.PORT || 5000;<br><br>app.use(cors());<br>app.use(express.json());<br><br>// Routes<br>app.use(&#39;/api/scholars&#39;, userRoutes);<br><br>// Start server after MongoDB connection<br>MongodbConnection(&quot;YOUR_MONGODB_CONNECTION_STRING&quot;)<br>    .then(() =&gt; {<br>        app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));<br>    })<br>    .catch((error) =&gt; console.error(&quot;Error connecting to MongoDB:&quot;, error));</pre><p>Replace &quot;YOUR_MONGODB_CONNECTION_STRING&quot; with your MongoDB connection string.</p><blockquote><strong>Schema Definition</strong></blockquote><p>We do have a folder called <strong>Model</strong> and inside which you will’ll create aSchema.js file for the schema defination and for creating models.</p><pre>import mongoose from &#39;mongoose&#39;;<br><br>const scholarSchema = new mongoose.Schema({<br>    scholarid: String,<br>    name: String,<br>    email: String,<br>    mobile: String,<br>    location: String,<br>    about: String,<br>    gender: String,<br>    password: String,<br>});<br><br><br>const Scholar = mongoose.model(&#39;Scholar&#39;, scholarSchema);<br><br>export { Scholar};</pre><blockquote><strong>CRUD Operations</strong></blockquote><p>With the schema and the model ready ,we can define the functions now in the Controller folder by creating aController.js file which will have our CRUD operations</p><ol><li><strong>Create : </strong>To add a new scholar</li></ol><p>The createScholar function is an <strong>asynchronous handler</strong> for creating a new scholar in the database. It receives a request (usually from an HTTP POST call), processes the data, saves it to the MongoDB database, and sends a response back to the client.</p><pre>async function createScholar(req, res) {<br>    const { scholarid, name, email, mobile, location, about, gender, password } = req.body;<br>    const scholar = new Scholar({ scholarid, name, email, mobile, location, about, gender, password });<br>    try {<br>        await scholar.save();<br>        res.status(201).json(scholar);<br>    } catch (error) {<br>        res.status(500).json({ message: error.message });<br>    }<br>}</pre><p>The req.body contains the data sent by the client in the request. This is typically JSON in a POST request.</p><p>Example: If the client sends,</p><pre>{<br>    &quot;scholarid&quot;: &quot;S123&quot;,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>    &quot;mobile&quot;: &quot;1234567890&quot;,<br>    &quot;location&quot;: &quot;New York&quot;,<br>    &quot;about&quot;: &quot;Researcher in AI&quot;,<br>    &quot;gender&quot;: &quot;Male&quot;,<br>    &quot;password&quot;: &quot;securepassword&quot;<br>}</pre><p><strong><em>Creating a New Scholar Instance</em></strong><em>:</em></p><pre>const scholar = new Scholar({ scholarid, name, email, mobile, location, about, gender, password });</pre><ul><li>Creates a new instance of the Scholar model, defined in Mongoose.</li><li>The provided data (scholarid, name, etc.) is used to populate the fields defined in the Scholar schema.</li></ul><p><strong><em>Saving to the Database</em></strong><em>:</em></p><pre>try {<br>    await scholar.save();<br>    res.status(201).json(scholar);<br>} catch (error) {<br>    res.status(500).json({ message: error.message });<br>}</pre><p><strong>await scholar.save()</strong>:</p><ul><li>The .save() method in Mongoose is used to save a document (<strong>an instance of a model created by the requested body</strong>) to the MongoDB database.</li><li>on success sends a <strong>201 Created</strong> HTTP response to the client.</li></ul><p>2. <strong>Read : </strong>To fetch all scholars</p><p>The getAllScholars function is an <strong>asynchronous controller</strong> function for fetching all scholar documents from the MongoDB database.</p><pre>async function getAllScholars(req, res) {<br>    try {<br>        const scholars = await Scholar.find();<br>        res.json(scholars);<br>    } catch (error) {<br>        res.status(500).json({ message: error.message });<br>    }<br>}</pre><p><strong><em>Fetching Data</em></strong></p><pre>const scholars = await Scholar.find();</pre><ul><li>await <strong>Scholar.find()</strong> It makes an asynchronous call to MongoDB using <strong>Mongoose&#39;s </strong><strong>find()</strong> method, which is used to <strong>fetch all documents</strong> from the <strong>scholars</strong> collection in the database.</li><li>find() returns a <strong>promise</strong>, and by using await, the code waits for the operation to complete before continuing. When the operation finishes, the result (all the scholar documents) is assigned to the scholars variable.</li><li>The result (scholars) will be an array of all scholar documents in the collection.</li></ul><pre>res.json(scholars);</pre><p>After fetching the data, the function sends the list of scholars back to the client as a JSON response using <strong>res.json()</strong>. This sends the scholars array as a JSON response to the client, which can then process or display the data.</p><p><strong>Error Handling:</strong> If any error occurs during the fetching of the scholars (e.g., database connection issues, server errors), the function catches the error using the catch block.</p><p>3. <strong>Update : </strong>To update a scholar’s details</p><p>The updateScholar function is responsible for updating an existing scholar document in the MongoDB database based on the scholarid provided in the request.</p><pre>async function updateScholar(req, res) {<br>    try {<br>        const updatedScholar = await Scholar.findOneAndUpdate(<br>            { scholarid: req.params.id },<br>            req.body,<br>            { new: true }<br>        );<br>        res.json(updatedScholar);<br>    } catch (error) {<br>        res.status(500).json({ message: error.message });<br>    }<br>}</pre><p><strong><em>Finding and Updating the Scholar</em></strong></p><pre>const updatedScholar = await Scholar.findOneAndUpdate(<br>    { scholarid: req.params.id }, // The filter condition<br>    req.body,                     // The updated data<br>    { new: true }                 // Return the updated document<br>);</pre><ul><li><strong>Scholar.findOneAndUpdate()</strong> is used to find and update the first scholar document that matches the filter condition.</li><li>The <strong>filter condition</strong> { scholarid: req.params.id } is used to search for a document where the scholarid matches the id provided in the URL (e.g., /api/scholars/:id).</li><li><strong>req.body</strong> contains the new data that the client wants to update in the document. This data can include fields like name, email, mobile, etc., and is passed as the second argument to findOneAndUpdate().</li><li>The { new: true } option ensures that the function <strong>returns the updated document</strong>, not the old one. If this option were set to false, it would return the document before the update.</li></ul><p>After the scholar document is updated, the function sends the updated document back to the client as a <strong>JSON response</strong>. The updatedScholar variable contains the updated scholar document returned by findOneAndUpdate().</p><p>If an error occurs during the update process (e.g., the scholar with the provided scholarid doesn&#39;t exist or there&#39;s a server/database issue), the catch block catches the error and sends a <strong>500 Internal Server Error response</strong> to the client.</p><p>4. <strong>Delete : </strong>To delete a scholar.</p><p>The deleteScholar function is designed to delete a scholar document from the MongoDB database based on the provided scholarid.</p><pre>async function deleteScholar(req, res) {<br>    try {<br>        const deletedScholar = await Scholar.findOneAndDelete({ scholarid: req.params.id });<br>        res.json({ message: &quot;Scholar deleted&quot;, deletedScholar });<br>    } catch (error) {<br>        res.status(500).json({ message: error.message });<br>    }<br>}</pre><p><strong><em>Finding and Deleting the Scholar</em></strong></p><pre>const deletedScholar = await Scholar.findOneAndDelete({ scholarid: req.params.id });</pre><ul><li><strong>Scholar.findOneAndDelete()</strong> is a Mongoose method that searches for a document matching the specified criteria and deletes it from the database. In this case, it:</li><li><strong>Searches</strong> for a scholar document using the filter { scholarid: req.params.id }, where req.params.id is the scholarid passed in the URL (e.g., /api/scholars/:id).</li><li><strong>Deletes</strong> the matched document if it exists.</li><li>The <strong>await</strong> keyword ensures that the database operation is completed before proceeding to the next step.</li><li><strong>deletedScholar</strong> stores the document that was deleted (if any). If no document is found with the provided scholarid, deletedScholar will be null.</li></ul><p>After successfully deleting the scholar, the server sends a <strong>JSON response</strong> back to the client containing. A <strong>message</strong> indicating that the scholar was deleted: &quot;Scholar deleted&quot;.</p><p>If an error occurs during the deletion process (e.g., an issue with the database), the catch block catches the error.</p><blockquote>what’s next!?</blockquote><blockquote><strong><em>Define Routes</em></strong></blockquote><p>In a typical <strong>RESTful API</strong>, the routes will correspond to the actions you want to perform on the data. Here’s how you should structure your routes for each CRUD operation</p><p>with the base route defined in the <strong>serverCong.js</strong> extending that route we are implementing these routes for CRUD</p><pre>import express from &#39;express&#39;;<br>import { createScholar, getAllScholars, updateScholar, deleteScholar } from &#39;../controllers/scholarController.js&#39;;<br><br>const router = express.Router();<br><br>// POST: Create a new scholar<br>router.post(&#39;/&#39;, createScholar);<br><br>// GET: Get all scholars<br>router.get(&#39;/&#39;, getAllScholars);<br><br>// PUT: Update an existing scholar<br>router.put(&#39;/:id&#39;, updateScholar);<br><br>// DELETE: Delete a scholar<br>router.delete(&#39;/:id&#39;, deleteScholar);<br><br>export default router;</pre><ul><li>Firstly, we need to import thecreateScholar getAllScholars, updateScholar, deleteScholarcontroller functions that will handle the actual business logic for each CRUD operation.</li></ul><p><strong><em>router.post(‘/’, createScholar) : </em></strong>This route listens for POST requests on the / endpoint, which is used to create a new scholar.</p><p><strong><em>router.get(‘/’, getAllScholars) :</em></strong><em> </em>This route listens for GET requests on the / endpoint, used to retrieve a list of all scholars from the database.</p><p><strong><em>router.put(‘/:id’, updateScholar) : </em></strong>This route listens for PUT requests on the /id endpoint, where id is a dynamic parameter. This route is used to update an existing scholar&#39;s details, identified by their id.</p><p><strong><em>router.delete(‘/:id’, deleteScholar) : </em></strong>This route listens for DELETE requests on the /id endpoint, used to delete a scholar by their id.</p><p>Note : Now the second parameter in all kinds of request types defines that for this particular route it should operate on the function defined for it in the <strong>controller.js</strong> file</p><blockquote>Testing the CRUD API Endpoints</blockquote><p>Now that we’ve set up our routes and linked them to the appropriate controller functions, it’s time to see everything in action!</p><p>Do not forget to start the server by running!!</p><pre>node serverConf.js //replace serverConf.js with your server file name<br></pre><p>Each screenshot highlights the request type, endpoint, and the expected responses, so you can follow along and ensure everything is functioning as it should. Check them out below and feel free to try out the API calls on your own!</p><p><strong>Create Scholar Testing:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_8_oQDrvUEiurXPsRRohQ.png" /><figcaption>This image shows the response after sending a POST request to add a scholar.</figcaption></figure><p><strong>Get All Scholars Testing :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsKBY_XBLVQlyFQYNxTs1g.png" /><figcaption>This screenshot shows the response after making a GET request to fetch the list of scholars.</figcaption></figure><p><strong>Update Scholar Testing :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aF-o92tPTrZ_p4vqkhXPQ.png" /><figcaption>Here’s the response after sending a PUT request to modify an existing scholar’s information.</figcaption></figure><p><strong>Delete Scholar Testing :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QD9PGYlmqwLDF35Ng9dVeA.png" /><figcaption>This image shows the response after sending a DELETE request to remove a scholar from the database.</figcaption></figure><blockquote>That’s a done deal, another skill added!✅</blockquote><p>In this blog, we explored the core CRUD operations in a MERN stack application. Starting with the database connection setup, creating schemas and models, defining routes, and implementing controller functions, we’ve covered everything needed to build a foundational backend for any application.</p><p>Building efficient and scalable MERN stack applications requires a solid understanding of <strong>advanced JavaScript concepts</strong>, which play a crucial role in enhancing both the backend and frontend development process.</p><p>Stay tuned for the next blog, where we’ll dive into advanced JavaScript topics like <strong>asynchronous programming, closures, higher-order functions, and more</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2c3c10a8b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React and Real-Time Data: Fetching and Displaying Data from Your Backend API]]></title>
            <link>https://medium.com/@anthonysebastinj/react-and-real-time-data-fetching-and-displaying-data-from-your-backend-api-682aca27e643?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/682aca27e643</guid>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 18:40:57 GMT</pubDate>
            <atom:updated>2024-11-23T19:10:40.370Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive guide to integrating your React app with a Node.js and MongoDB backend to display dynamic content.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*etkPz2bWT0jIypJyFjF0Yg@2x.jpeg" /></figure><p>Hey there, Devs! 👨‍💻 Welcome back to another blog post.</p><p>In our last blog, we built a robust API using Node.js, Express, and MongoDB. If you missed it, no worries! You can catch up 🔗<a href="https://medium.com/@anthonysebastinj/api-development-101-building-and-testing-api-endpoints-in-node-js-and-express-e312037d6bb3">here</a>.</p><blockquote>Now without any delay, Lets get started!🚀</blockquote><p>In this blog, we’ll dive into the process of connecting our React app to the backend API and displaying the data in an engaging way. Here’s a sneak peek of what we’ll be building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zHYY0--K78PxrK0tcR8-A.png" /><figcaption>Visual Representation of Post Data: Each card highlights key information from our API.</figcaption></figure><p>Let’s break down each step to help you build this from scratch!</p><blockquote><strong>Start the Development Server</strong></blockquote><p>If you missed the steps for creating the React app, be sure to check out my previous blog 🔗<a href="https://medium.com/@anthonysebastinj/streamlining-mern-development-with-mvc-architecture-c63a8c7c43b0">here</a> where I walk you through the setup process!</p><p>To see your React app in action, start the development server with</p><pre>npm start</pre><p>This will open your default web browser and display your new React application at http://localhost:3000</p><p>Now that your React app is up and running, it’s time to connect it to your backend API to fetch and display dynamic data.</p><blockquote><strong>Set Up the Backend API :</strong></blockquote><p>Before connecting the frontend, ensure your backend server is up and running.</p><ol><li><strong>Start the Server</strong><br>Run the backend server (e.g., using node serverfilename.js) and confirm it&#39;s listening on http://localhost:5000.</li><li><strong>API Endpoint</strong><br>The React app will fetch data from http://localhost:5000/api/scholars/allposts. This endpoint is set up to handle requests and send responses with the required data.</li><li><strong>Response Format</strong><br>The API returns data in JSON format. This structure makes it straightforward for the frontend to process and display the information.</li></ol><blockquote><strong>Set Up the Content Folder and Component :</strong></blockquote><p>let’s organize the folder structure. It’s a good practice to keep your components well-structured for better maintainability.</p><ul><li>Inside your client folder, create a new folder called content.</li><li>Within the content folder, create a file named contentComp.jsx. This file will hold the React component to fetch and display data from the API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wknaOJZX1WtnYGkITbae-Q.png" /><figcaption>above is a view of the folder structure for the component</figcaption></figure><blockquote><strong>Fetching Data in React :</strong></blockquote><ol><li><strong>Imports :</strong></li></ol><p>Firstly, you need to import everything required for your component to function</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import { faWhatsapp, faTwitter, faInstagram } from &#39;@fortawesome/free-brands-svg-icons&#39;;<br>import { FontAwesomeIcon } from &#39;@fortawesome/react-fontawesome&#39;;<br>import { faEllipsisVertical } from &#39;@fortawesome/free-solid-svg-icons&#39;;</pre><ul><li><strong>React</strong>: The main library for creating components and rendering them.</li><li><strong>useEffect</strong>: Hook for performing side effects, like fetching data.</li><li><strong>useState</strong>: Hook for managing local state, like storing fetched data.</li><li><strong>Additional plugins</strong>: e.g., FontAwesome icons for UI elements (if needed).</li></ul><p>2. <strong>useState Hook :</strong></p><p>The useState hook is used to store and manage the data fetched from the API.</p><pre>const [currentData, setCurrentData] = useState([]);</pre><ul><li><strong>State Initialization</strong>: useState([]) initializes the currentData state with an empty array.</li><li><strong>State Variable</strong>: currentData holds the data that the component will display, and React tracks any changes to it.</li><li><strong>State Setter</strong>: setCurrentData is the function used to update currentData with new values, triggering a re-render of the component when the data changes.</li></ul><p>3. <strong>useEffect Hook :</strong></p><p>The useEffect hook runs after the component mounts. It&#39;s used for side effects, such as fetching data. In this case, the data is fetched from your API when the component first loads.</p><pre>useEffect(() =&gt; {<br>    fetch(&quot;http://localhost:5000/api/scholars/allposts&quot;)<br>        .then((res) =&gt; res.json())<br>        .then((data) =&gt; {<br>            console.log(&quot;data fetched&quot;);<br>            setCurrentData(data); <br>        })<br>        .catch((err) =&gt; {<br>            console.log(&quot;error loading the data&quot;, err);<br>        });<br>}, [newContentAdded] //dependency array);</pre><ul><li><strong>Send a Request:</strong></li></ul><p>The fetch() function is used to send a GET request to http://localhost:5000/api/scholars/allpoststo retrieve data from the server.</p><ul><li><strong>Process the Response:</strong></li></ul><p>After the request completes, .then((res) =&gt; res.json()) is called to convert the response into a JSON object. The parsed data is passed to the next .then() block.</p><ul><li><strong>Update State or Handle Errors:</strong></li></ul><p>If the data is successfully fetched, setCurrentData(data) updates the component&#39;s state with the fetched data, causing a re-render. If there&#39;s an error during the fetch operation, it’s caught by .catch(), which logs the error to the console.</p><ul><li>The second argument to useEffect is the dependency array. This tells React when to rerun the effect.</li><li>In this case, the effect will rerun whenever the value of newContentAdded changes.</li></ul><p>4. <strong>Displaying the Data</strong></p><p>Finally, the data stored in the state (currentData) is rendered inside the component. It checks if there is data to display and maps through it.</p><p><em>Let’s assume this is the data we received from the request:</em></p><pre>[<br>  {<br>    &quot;_id&quot;: {&quot;$oid&quot;: &quot;670fdc2ff33dbc04fd8501ea&quot;},<br>    &quot;username&quot;: &quot;sebastin&quot;,<br>    &quot;dateposted&quot;: &quot;22/09/2024&quot;,<br>    &quot;postcaption&quot;: &quot;Boost Your Brand, Digitally Delivered!&quot;,<br>    &quot;postimage&quot;: &quot;https://www.small-business-guide.com/wp-content/uploads/2022/06/dc27b48d17aa1a76/google-my-business.jpeg&quot;,<br>    &quot;userid&quot;: &quot;213164654561&quot;<br>  },<br>  {<br>    &quot;_id&quot;: {&quot;$oid&quot;: &quot;670fddd3f33dbc04fd8501ec&quot;},<br>    &quot;username&quot;: &quot;rachel&quot;,<br>    &quot;dateposted&quot;: &quot;22/09/2024&quot;,<br>    &quot;postcaption&quot;: &quot;Empowered women empower the world!&quot;,<br>    &quot;postimage&quot;: &quot;https://media.istockphoto.com/id/1437816897/photo/business-woman-manager-or-human-resources-portrait-for-career-success-company-we-are-hiring.jpg?s=612x612&amp;w=0&amp;k=20&amp;c=tyLvtzutRh22j9GqSGI33Z4HpIwv9vL_MZw_xOE19NQ=&quot;,<br>    &quot;userid&quot;: &quot;213164654561&quot;<br>  }<br>]</pre><p>To display the posts from this response, we need to loop through the array of objects using the map() function.</p><p>Each object in the array represents a post, and by using map(), we can access the data for each post and render it on the screen.</p><p>Below is the complete code that loops through each object and displays the post information</p><pre>return (<br>  &lt;div className=&quot;scrollable-container&quot;&gt;<br>    {currentData.length &gt; 0 ? (<br>      currentData.map((item) =&gt; (<br>        &lt;div key={item._id.$oid}&gt;<br>          &lt;div className=&quot;post-container&quot;&gt;<br>            &lt;div className=&quot;top-division&quot;&gt;<br>              &lt;div className=&quot;top-division-left&quot;&gt;<br>                &lt;span&gt;<br>                  &lt;img className=&quot;user-avatar&quot; src={item.userAvatar || &quot;default-avatar.jpg&quot;} alt=&quot;user-avatar&quot; /&gt;<br>                &lt;/span&gt;<br>                &lt;div className=&quot;user-info&quot;&gt;<br>                  &lt;div&gt;{item.username}&lt;/div&gt;<br>                  &lt;div className=&quot;date-posted&quot;&gt;Request posted on {item.dateposted}&lt;/div&gt;<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;caption-container&quot;&gt;{item.postcaption}&lt;/div&gt;<br>            &lt;img className=&quot;post-image&quot; alt=&quot;post&quot; src={item.postimage} /&gt;<br>            &lt;div className=&quot;bottom-division&quot;&gt;<br>              &lt;span&gt;Like&lt;/span&gt; | &lt;span&gt;Comment&lt;/span&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ))<br>    ) : (<br>      &lt;p&gt;No data available&lt;/p&gt;<br>    )}<br>  &lt;/div&gt;<br>);</pre><p><strong>Mapping through the Data</strong>:</p><ul><li>currentData.map((item) =&gt; ...): This loops through each post object in the currentData array and creates a new div for each post.</li><li>Each post has its own div with a unique key based on item._id.$oid to help React identify each item efficiently.</li></ul><p><strong>Displaying Post Information</strong>:</p><ul><li><strong>User Information</strong>: The username, dateposted, and userAvatar (if available) are displayed.</li><li><strong>Post Caption and Image</strong>: The postcaption is shown as text, and the postimage is rendered as an image.</li></ul><p><strong>If No Data Available</strong>:</p><ul><li>If the currentData array is empty, it will show the message No data available.</li></ul><p>Now, let’s combine all the pieces of code together to display the posts. it will look something like this:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import { faWhatsapp, faTwitter, faInstagram } from &#39;@fortawesome/free-brands-svg-icons&#39;;<br>import { FontAwesomeIcon } from &#39;@fortawesome/react-fontawesome&#39;;<br>import { faEllipsisVertical } from &#39;@fortawesome/free-solid-svg-icons&#39;;<br><br>function contentComp() {<br>    const [currentData, setCurrentData] = useState([]);<br><br>        useEffect(() =&gt; {<br>        fetch(&quot;http://localhost:5000/api/scholars/allposts&quot;)<br>            .then((res) =&gt; res.json())<br>            .then((data) =&gt; {<br>                console.log(&quot;data fetched&quot;);<br>                setCurrentData(data); <br>            })<br>            .catch((err) =&gt; {<br>                console.log(&quot;error loading the data&quot;, err);<br>            });<br>    }, [newContentAdded]);<br><br>    return (<br>        &lt;div className=&quot;scrollable-container&quot;&gt;<br>            {currentData.length &gt; 0 ? (<br>                currentData.map((item) =&gt; (<br>                    &lt;div key={item._id}&gt;<br>                        &lt;div className=&quot;post-container&quot;&gt;<br>                            &lt;div className=&quot;top-division&quot;&gt;<br>                                &lt;div className=&quot;top-division-left&quot;&gt;<br>                                    &lt;span&gt;<br>                                        &lt;img className=&quot;user-avatar&quot; src=&#39;https://media.istockphoto.com/id/1347495860/photo/african-american-man-wearing-glasses-side-view.webp?b=1&amp;s=612x612&amp;w=0&amp;k=20&amp;c=0gnj_oulajlDZoILAMToCu7XMlc74VXIcG2WaYjPj88=&#39; alt=&quot;user-avatar&quot; /&gt;<br>                                    &lt;/span&gt;<br>                                    &lt;div className=&quot;user-info&quot;&gt;<br>                                        &lt;div&gt;{item.username}&lt;/div&gt;<br>                                        &lt;div className=&quot;date-posted&quot;&gt;Request posted on {item.dateposted}&lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                                &lt;div&gt;<br>                                    &lt;div className=&#39;d-none d-lg-block social-buttons&#39;&gt;<br>                                        &lt;div style={{ display: &#39;flex&#39;, alignItems: &#39;center&#39; }}&gt;<br>                                            &lt;button className=&quot;social-button btn&quot;&gt;<br>                                                &lt;FontAwesomeIcon icon={faWhatsapp} /&gt;<br>                                            &lt;/button&gt;<br>                                            &lt;button className=&quot;social-button btn&quot;&gt;<br>                                                &lt;FontAwesomeIcon icon={faTwitter} /&gt;<br>                                            &lt;/button&gt;<br>                                            &lt;button className=&quot;social-button btn&quot;&gt;<br>                                                &lt;FontAwesomeIcon icon={faInstagram} /&gt;<br>                                            &lt;/button&gt;<br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                    &lt;div className=&quot;dropdown&quot;&gt;<br>                                        &lt;button className=&quot;btn&quot; type=&quot;button&quot; id=&quot;dropdownMenuButton&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;<br>                                            &lt;FontAwesomeIcon icon={faEllipsisVertical} style={{ color: &quot;#000000&quot; }} /&gt;<br>                                        &lt;/button&gt;<br>                                        &lt;div className=&quot;dropdown-menu&quot; aria-labelledby=&quot;dropdownMenuButton&quot;&gt;<br>                                            &lt;a className=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Action&lt;/a&gt;<br>                                            &lt;a className=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Another action&lt;/a&gt;<br>                                            &lt;a className=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Something else here&lt;/a&gt;<br>                                        &lt;/div&gt;<br>                                    &lt;/div&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div&gt;<br>                                &lt;div className=&quot;caption-container&quot;&gt;{item.postcaption}&lt;/div&gt;<br>                                &lt;div&gt;<br>                                    &lt;img className=&quot;post-image&quot; alt=&quot;post&quot; src={item.postimage} /&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div className=&quot;bottom-division&quot;&gt;<br>                                &lt;span&gt;Like&lt;/span&gt;<br>                                &lt;span className=&quot;separator&quot;&gt;|&lt;/span&gt;<br>                                &lt;span&gt;Comment&lt;/span&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                ))<br>            ) : (<br>                &lt;p&gt;No data available&lt;/p&gt;<br>            )}<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default contentComp;</pre><p>you can also enhance the visual presentation of your posts, you can consider using <strong>Bootstrap Cards</strong> or <strong>Material UI Cards</strong>.</p><p>5. <strong>Setting Up Routing in App.js</strong></p><p>In your App.js, you’ll want to manage the routing for different pages or components in your application. To display your ContentComp component, you can add it as a route in the App.js file, ensuring it is rendered at the appropriate path in your application.</p><p>Let’s set up routing to display your content. First, ensure that React Router is installed:</p><pre>npm install react-router-dom</pre><p>Setting Up Navigation with React Router in Your App : App.js</p><pre>import React from &#39;react&#39;;<br>import { BrowserRouter as Router, Routes, Route } from &#39;react-router-dom&#39;;<br>import ContentComp from &#39;./components/ContentComp&#39;; // Import your ContentComp component here<br><br>function App() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div className=&quot;App&quot;&gt;<br>        {/* Define your routes */}<br>        &lt;Routes&gt;<br>          {/* Route for displaying posts */}<br>          &lt;Route path=&quot;/&quot; element={&lt;ContentComp /&gt;} /&gt;<br>          <br>          {/* Add other routes as needed */}<br>          {/* &lt;Route path=&quot;/anotherPage&quot; element={&lt;AnotherComponent /&gt;} /&gt; */}<br>        &lt;/Routes&gt;<br>      &lt;/div&gt;<br>    &lt;/Router&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Router Setup</strong>:</p><ul><li>We’ll use &lt;BrowserRouter&gt; (aliased as Router) to wrap the app, enabling routing.</li></ul><p><strong>Routes &amp; Route</strong>:</p><ul><li>&lt;Routes&gt; is a wrapper component that contains multiple &lt;Route&gt; elements and ensures that only one of them is rendered based on the current URL path.</li><li>&lt;Route&gt; now uses the element prop to specify which component should be rendered. Instead of the component prop (as in previous versions), you pass the component JSX directly inside element={&lt;Component /&gt;}.</li></ul><p><strong>Path Configuration</strong>:</p><ul><li>The path=&quot;/&quot; specifies that the ContentComp component will be displayed at the root URL (/).</li><li>You can add more &lt;Route&gt; components with different path and element values to define other routes for your app.</li></ul><blockquote>A Done Deal! 🎉</blockquote><p>You’re all set to display posts dynamically in your React app! Now that you’ve learned how to fetch, display, and navigate your data using React Router, you’re ready to move forward.</p><p>Stay tuned for my next blog, where we’ll dive into performing CRUD operations on the front end of a MERN stack application. We’ll explore how to create, read, update, and delete posts, making your app fully interactive.</p><p>Happy coding!🧑‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=682aca27e643" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MERN API Development: Building and Testing API Endpoints in Node.js and Express]]></title>
            <link>https://medium.com/@anthonysebastinj/api-development-101-building-and-testing-api-endpoints-in-node-js-and-express-e312037d6bb3?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e312037d6bb3</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 03:28:44 GMT</pubDate>
            <atom:updated>2024-10-18T05:28:44.298Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Practical Approach to Building and Testing APIs for Developers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJuOIH6le_jYfzZweid_Og.jpeg" /></figure><p>Hello Devs👨‍💻, Welcome back to my blog!</p><p>In our last post, we took a closer look at the MVC architecture and how it helps in organizing our MERN applications. We explored how each layer of the MVC structure plays a crucial role in separating concerns, If you have missed it you can check it out 🔗 <a href="https://medium.com/@anthonysebastinj/streamlining-mern-development-with-mvc-architecture-c63a8c7c43b0">here</a>.</p><p>In this blog, We will take a closer look at the process of creating an API endpoint using Node.js and Express that connects to your MongoDB database. Let’s go through the steps of building a robust API. By the end of this post, you’ll have a solid understanding of how to create an API endpoint that can serve data effectively.</p><p>Alright, let’s crack on with the code! 🚀</p><h4>How the API is Created in Node.js and Express</h4><p>Continuing from the MVC architecture discussed in my previous blog, let’s unpack the process of creating an API using Node.js and Express.</p><blockquote>1. Setting Up the API Route with app.use(&quot;/scholar&quot;, UserRouter)In your mongodbconnection.js file:</blockquote><pre>// mongodbconnection.js (or your main server file)<br>import express from &#39;express&#39;;<br>import cors from &#39;cors&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import UserRouter from &#39;routes.js&#39;;<br>import { MongodbConnection } from &#39;../Connection.js&#39;;<br><br>const app = express();<br><br>const PORT = process.env.PORT || 5000;<br><br>app.use(cors());<br>app.use(express.json());<br><br>MongodbConnection(&quot;your connection string here!!&quot;).then((data)=&gt; console.log(&quot;mongodb connected&quot;));<br><br>const db = mongoose.connection;<br>db.once(&#39;open&#39;, () =&gt; console.log(&#39;Connected to MongoDB&#39;));<br><br>app.use(&quot;/scholar&quot;, UserRouter);<br><br>app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));<br><br></pre><ul><li><strong>Base Route Setup</strong>: app.use(&quot;/scholar&quot;, UserRouter) This line of code establishes a base route for the API.</li><li><strong>Request Handling</strong>: It instructs the Express server to route any incoming request that begins with /scholar to the UserRouter.</li></ul><blockquote>2. Defining the Routes in the Router (UserRouter)</blockquote><p>Within the routes.js file, you should set up routes using the Express router:</p><pre>import express from &#39;express&#39;;<br>import { handelAllPosts } from &#39;controller.js&#39;;<br><br>const router = express.Router();<br><br>router.route(&quot;/allposts&quot;).get(handelAllPosts);<br><br>export default router;</pre><ul><li><strong>Route</strong> /allposts: This endpoint will be accessible at /scholar/allposts due to the app.use(&quot;/scholar&quot;, UserRouter) setup.</li><li><strong>HTTP Method</strong> GET: The .get() method indicates that this route handles GET requests. In this context, it&#39;s used to fetch data.</li><li><strong>Controller Function</strong> handelAllPosts: When a GET request is made to /scholar/allposts, the handelAllPosts function is called to process the request and return the data.</li></ul><blockquote>3. The handelAllPosts Controller Function</blockquote><p>Now let’s look at how the handelAllPosts function works in your controller.js file:</p><pre>import { PostDataModel } from &#39;model.js&#39;;<br><br>// Fetch all posts<br>async function handelAllPosts(req, res) {<br>    try {<br>        const data = await PostDataModel.find();<br>        console.log(&#39;Fetched data successfully&#39;); <br>        res.json(data);<br>    } catch (err) {<br>         console.error(&#39;Error fetching posts:&#39;, err);<br>    }<br>}</pre><ul><li><strong>Data Fetching</strong>: PostDataModel.find() retrieves all the posts from the MongoDB database. This uses Mongoose to interact with the database and fetch the data from the dummyposts collection.</li><li><strong>Response</strong>: If the data is fetched successfully, it is sent back to the client (React app) in JSON format using res.json(data).</li><li><strong>Error Handling</strong>: If an error occurs during data fetching, code is returned with the error message.</li></ul><p>This function is crucial as it directly handles the request from the frontend, fetches the required data from the database, and returns it to the React app for display.</p><blockquote>4. The PostDataModel Schema Definition</blockquote><p>In your model.js file, you have the schema for the posts:</p><pre>import mongoose from &#39;mongoose&#39;;<br><br>const postsDataSchema = new mongoose.Schema({<br>    username: String,<br>    dateposted: String,<br>    postcaption: String,<br>    postimage: String<br>});<br><br>const PostDataModel = mongoose.model(&#39;dummyposts&#39;, postsDataSchema);<br>export { PostDataModel };</pre><ul><li><strong>Schema Definition</strong>: The postsDataSchema defines the structure of the post documents in your MongoDB database. It includes fields like username, dateposted, postcaption, postimage.</li><li><strong>Model Creation</strong>: PostDataModel is created using the schema, and it represents the dummyposts collection in your MongoDB database.</li></ul><p>This model allows you to interact with the dummyposts collection using Mongoose methods like .find() to retrieve posts, making database operations straightforward.</p><h4>Your API is Ready!</h4><p>Before proceeding into testing, make sure to run your server. You can do this by executing the following command in your terminal:</p><pre>node &lt;your-server-file&gt;.js</pre><p>Replace &lt;your-server-file&gt; with the name of your server file. In my case with the example explained its mongodbConnection.js</p><blockquote>4. Testing the API Endpoint</blockquote><p>Now that your API is ready, you can test it! Make sure your server is running first. Since your Express app is set to listen on port <strong>5000</strong>, you can access the endpoint using the following URL:</p><p><a href="http://localhost:5000/scholar/allposts"><strong>http://localhost:5000/scholar/allposts</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUD6_kPLOSCCWo889Thr_A.png" /></figure><p>The API testing was successful. This confirms that our API endpoint is functioning correctly, effectively retrieving data as intended.</p><p>With the successful connection established between our backend and the database, we can now proceed to utilize this data in our frontend application. In my next blog, we will explore how to effectively display this data in a React application, showcasing it in an appealing format, as illustrated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_30U1tbFq1WpF1Y1cUVbg.png" /><figcaption>Visual Representation of Post Data: Each card highlights key information from our API.</figcaption></figure><blockquote>Stay tuned for the next blog, where we’ll delve into displaying this data beautifully in our React application!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e312037d6bb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining MERN Development with MVC Architecture]]></title>
            <link>https://medium.com/@anthonysebastinj/streamlining-mern-development-with-mvc-architecture-c63a8c7c43b0?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63a8c7c43b0</guid>
            <category><![CDATA[mern-stack-training]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mvc-architecture]]></category>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 19:51:10 GMT</pubDate>
            <atom:updated>2024-12-22T06:12:55.675Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimizing Workflow and Structure for Scalable Applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*5m1Kg2nZx077bq4YZF9Row.jpeg" /></figure><p>Hello Devs👨‍💻! Welcome back to my blog</p><p>In my <strong>previous blog,</strong> we explored how to fetch data from MongoDB using Express and Node.js. If you missed that, you can check it out 🔗 <a href="https://medium.com/@anthonysebastinj/from-database-to-api-how-to-fetch-data-from-mongodb-using-node-js-and-express-b587c725b661"><strong>here</strong></a><strong></strong></p><p>Now, as we continue building our MERN app, it’s crucial to structure the code for scalability and maintainability. This blog will explore how the MVC (Model-View-Controller) architecture forms the backbone of an organized, efficient project.</p><p><em>Lets get started🚀!</em></p><p>Before we jump into how the MVC (Model-View-Controller) architecture simplifies application design, let’s first set up the <strong>React</strong> to build our user interface.</p><blockquote>Steps to Create Your React App:</blockquote><ol><li>Install Node.js and npm (Node Package Manager) if you haven’t already.</li><li>Create a new React app by running:</li></ol><pre>npx create-react-app my-app</pre><p>The command npx create-react-app my-app generates a new React project with a pre-configured development environment and essential boilerplate code, including Webpack, Babel, and ESLint. It sets up a default folder structure, allowing you to start building your app immediately without setup hassle.</p><p>Replace my-app with your preferred project name.</p><p>3. Navigate to your project directory:</p><pre>cd my-app</pre><p>after running npx create-react-app my-app, you would use the above command to enter the my-app directory</p><p>Once your app is successfully created, it will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fh9ooDQvLV6HCKwcPn-lBQ.png" /><figcaption>Folder layout of a freshly created React app, ready for customization.</figcaption></figure><p>Now that your React app is set up, let’s dive into the <strong>MVC architecture</strong> and see how it organizes our application for scalability and maintainability!</p><blockquote>How MVC Simplifies Application Design</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*jJ2CN5whsFZMWU-oeY2jaw.jpeg" /></figure><p>The Model-View-Controller (MVC) architecture is a design pattern that organizes an application into three interconnected components, facilitating a clear separation of concerns.</p><p>let’s walk through how these components work together in the MERN stack:</p><ol><li><strong>Model (MongoDB + Mongoose)</strong>: This is where your data is defined and managed.</li><li><strong>Controller (Express)</strong>: This handles the business logic, takes user input, and interacts with the model.</li><li><strong>View (React)</strong>: This renders the data and provides an interactive interface for users.</li><li><strong>Routers : a</strong>dditionally, <strong>routers</strong> play a crucial role in this setup. They define the application’s endpoints and determine which controller should handle each incoming request. used to manage different routes for CRUD operations, like fetching, creating, updating, or deleting data from the database.</li></ol><blockquote>A Peek into the File Structure</blockquote><p>The file structure can be divided into two main parts: <strong>client</strong> and <strong>server</strong>.</p><p>Example Folder Structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*QE5cX7OUs3RwDHBaYKZVCQ.png" /></figure><ol><li><strong>Client:</strong></li></ol><ul><li>This folder contains the <strong>React</strong> front-end application, which is responsible for rendering the user interface (UI) and managing user interactions.</li></ul><p><strong>2. Server:</strong></p><ul><li>The server folder contains the back-end logic of the application, organized using the <strong>MVC (Model-View-Controller)</strong> architecture. It uses <strong>Node.js</strong> and <strong>Express.js</strong> to handle the server-side functionality.</li></ul><blockquote>Breakdown of the MVC Files and Their Code</blockquote><ol><li><strong>Setting Up the Server</strong></li></ol><p>In your main server file (e.g., DbConnection.js), set up your Express application and configure the MongoDB connection:</p><pre>import express from &#39;express&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import cors from &#39;cors&#39;;<br>import UserRouter from &#39;./routes/Users.js&#39;;<br><br>const app = express();<br>const PORT = process.env.PORT || 5000;<br><br>app.use(cors());<br>app.use(express.json());<br><br>mongoose.connect(&#39;your mongodb connection string with db name!!&#39;);<br><br>const db = mongoose.connection;<br>db.once(&#39;open&#39;, () =&gt; console.log(&#39;Connected to MongoDB&#39;));<br><br>app.use(&quot;/students&quot;, UserRouter);<br><br>app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));</pre><p>2. <strong>Creating the Mongoose Model</strong></p><p>The file Model.js, define your Mongoose schema and model as follows:</p><pre>import mongoose from &#39;mongoose&#39;;<br><br>const DataSchema = new mongoose.Schema({<br>  name: String,<br>  age: Number,<br>});<br><br>const studentDataModel = mongoose.model(&#39;students&#39;, DataSchema);<br><br>export {studentDataModel} ;</pre><ul><li>DataSchema: Defines the structure of documents in your MongoDB collection. In this case, each document will have name and age fields.</li><li>studentDataModel: The model that represents the students collection in the MongoDB database.</li></ul><p>3.<strong> Controller to Handle Database Queries</strong></p><p>In Controller.js, create a function to handle fetching all the students from the database:</p><pre>import { studentDataModel } from &#39;../model/Model.js&#39;;<br><br>async function handelAllStudents(req, res) {<br>    try {<br>        const data = await studentDataModel.find();<br>        console.log(&#39;Fetched data:&#39;, data);<br>        res.json(data);<br>      } catch (err) {<br>       console.log(&quot;error fetching data from db&quot;, err)<br>      }<br>}<br>y<br>export { handelAllStudents };</pre><ul><li>The handelAllStudents function fetches data from the MongoDB database using Mongoose&#39;s find() method and sends the result as a JSON response.</li></ul><p>4. <strong>Setting Up the Express Router</strong></p><p>In Routes.js, define the route that will handle the requests for fetching the student data:</p><pre>import express from &#39;express&#39;;<br>import { handelAllStudents } from &#39;../controller/Controller.js&#39;;<br><br>const router = express.Router();<br><br>router.route(&quot;/allStudentsdata&quot;).get(handelAllStudents)<br><br>export default router;</pre><p>The router defines a GET request on /allStudentsdata, which triggers the handelAllStudents function in the controller.</p><blockquote>And finally…</blockquote><p><strong>5. Views</strong><br>The “View” in the MVC architecture represents the user interface or what the user interacts with. Since it involves the frontend, I will be explaining this aspect in detail in my next blog.</p><p><strong>Stay Tuned:</strong> We’ll explore how to design responsive and intuitive user interfaces that effectively display data while ensuring a seamless user experience.</p><blockquote>And That’s a Done Deal!✅</blockquote><p>In this blog, we’ve walked through the<strong> MVC</strong>, focusing on how the <strong>Model</strong> and <strong>Controller</strong> work together to manage data and handle requests. This structure is key to building clean, organized, and scalable applications. By breaking responsibilities into these layers, we create a more maintainable codebase, especially as your app grows.</p><p>In the next post, we’ll dive into the <strong>View</strong> layer, where the data comes to life on the frontend. Until then, you can experiment with what we’ve covered, and get ready to see how everything ties together when we integrate the user interface.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63a8c7c43b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Database to API: How to Fetch Data from MongoDB Using Node.js and Express]]></title>
            <link>https://medium.com/@anthonysebastinj/from-database-to-api-how-to-fetch-data-from-mongodb-using-node-js-and-express-b587c725b661?source=rss-3280bb18e92e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b587c725b661</guid>
            <dc:creator><![CDATA[Anthony Sebastin J]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 06:54:18 GMT</pubDate>
            <atom:updated>2024-08-25T17:25:58.464Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From Database to API: How to Fetch Data from MongoDB Using Node.js and Expres</strong>s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gf_XcvKMkfwiQLxTVqGiaA.png" /></figure><p>Hello, Devs! This is my first blog, and I’ll be walking you through the process of fetching data from MongoDB using a Node.js and Express server. Whether you’re just starting out or looking to sharpen your skills, I hope this guide will be helpful for you!</p><blockquote><strong>Let’s Get Started!</strong></blockquote><p>Together, MongoDB, Express.js, and Node.js form the backend part of the MERN stack, which is widely used to build full-stack web applications. In this guide, we’ll explore how these technologies work together to fetch data from MongoDB and serve it through an API using Express and Node.js.</p><blockquote>Necessary Dependencies</blockquote><p>Before we get into the code, you’ll need to install a few libraries to get everything up and running:</p><p><strong>Express</strong>: A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.</p><p><strong>Mongoose</strong>: A MongoDB object modeling tool designed to work in an asynchronous environment. It simplifies working with MongoDB in Node.js.</p><p><strong>Cors</strong>: A middleware package that allows your API to be accessed from different domains by enabling Cross-Origin Resource Sharing (CORS).</p><pre>npm install express mongoose cors</pre><blockquote>Setting Up Your Node.js Server with MongoDB</blockquote><p>Now that we have our essential packages installed, let’s dive into the code that sets up our server. The following snippet demonstrates how to connect to MongoDB, define a schema, and implement an API endpoint to retrieve data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prgDSuCTBz6ABujhlQMkjA.png" /></figure><blockquote>Code Breakdown</blockquote><ol><li>Importing Dependencies</li></ol><pre>import express from &#39;express&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import cors from &#39;cors&#39;;</pre><ul><li><strong>import express from &#39;express&#39;;</strong><br>Imports the Express framework, simplifying the creation of web servers and handling of HTTP requests in Node.js.</li><li><strong>import mongoose from &#39;mongoose&#39;;</strong><br>Imports Mongoose, an ODM library that helps structure and interact with MongoDB databases in a Node.js environment.</li><li><strong>import cors from &#39;cors&#39;;</strong><br>Imports the CORS middleware, enabling your server to handle requests from different domains, essential for cross-origin communication.</li></ul><p>2. Setting Up the Express Application</p><pre>const app = express();<br>const PORT = process.env.PORT || 5000;</pre><ul><li><strong>app</strong>: Creates an instance of the Express application, which will be used to define routes and middleware.</li><li><strong>PORT</strong>: <em>Specifies the port on which the server will run</em>. It uses an environment variable if available, or defaults to port 5000.</li></ul><p>3. Middleware Configuration</p><pre>app.use(cors());<br>app.use(express.json());</pre><ul><li><strong>app.use(cors())</strong>: Applies the CORS middleware to handle cross-origin requests, allowing your API to be accessed from different domains.</li><li><strong>app.use(express.json())</strong>: Configures Express to parse incoming JSON payloads, making it easier to handle data sent in request bodies.</li></ul><p>4. Connecting to MongoDB</p><pre>mongoose.connect(&#39;mongodb://localhost:27017/College&#39;, {<br>  useNewUrlParser: true,<br>  useUnifiedTopology: true<br>});</pre><p><strong>mongoose.connect</strong>: Connects to a MongoDB database named <strong><em>College</em></strong> running locally. The options useNewUrlParser and useUnifiedTopology ensure compatibility with the latest MongoDB features and prevent deprecation warnings.</p><blockquote>The Url “<strong>mongodb://localhost:27017/”</strong> is the connection string on your MobgoDB Compass and College will be the database name your trying to fetch data from.</blockquote><p>5. Handling Database Connection</p><pre>const db = mongoose.connection;<br>db.once(&#39;open&#39;, () =&gt; console.log(&#39;Connected to MongoDB&#39;));</pre><ul><li><strong>db</strong>: Gets the default connection object.</li><li><strong>db.once(&#39;open&#39;)</strong>: Sets up a listener that logs a message when the connection to MongoDB is successfully established.</li></ul><p>6. Defining a Schema and Model</p><pre>const DataSchema = new mongoose.Schema({<br>  name: String,<br>  age: Number,<br>});<br><br>const DataModel = mongoose.model(&#39;students&#39;, DataSchema);</pre><p><strong>DataModel</strong>: This then provides a way to interact with your data, letting you add new student records, search for existing ones, and update them based on the blueprint you’ve set up.</p><p><strong>“Students” </strong>is the collection name on your database which need to be defined in DataModel</p><p><strong>DataSchema</strong>: This sets up the rules for how documents in the collection should look, like a template for your data.</p><blockquote>example :</blockquote><p>if you want to store information about students, you’d set up a schema to define what details each student’s record should include, such as name, age, and ect. The schema acts like a blueprint that outlines the structure of each document in your collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*loMor3eD067VaD6ii1EmGQ.png" /></figure><p>7. Creating an API Route</p><pre>app.get(&#39;/api/data&#39;, async (req, res) =&gt; {<br>  try {<br>    const data = await DataModel.find();<br>    console.log(&#39;Fetched data:&#39;, data); // Log the data<br>    res.json(data);<br>  } catch (err) {<br>    res.status(500).json({ message: err.message });<br>  }<br>});</pre><p><strong>app.get(&#39;/api/data&#39;)</strong>: Defines a route that responds to GET requests at /api/data.</p><p><strong>async (req, res)</strong>: An asynchronous function that handles the request and response.</p><p><strong>const data = await DataModel.find()</strong>: Retrieves all documents from the students collection.</p><p><strong>res.json(data)</strong>: Sends the retrieved data as a JSON response to the client.</p><p><strong>catch (err)</strong>: Catches any errors that occur during the data retrieval and sends a 500 status code with an error message.</p><p><strong>8. Starting the Server</strong></p><pre>app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));</pre><p><strong>app.listen(PORT)</strong>: Starts the server on the specified port.</p><p><strong>console.log</strong>: Logs a message indicating that the server is running and listening on the specified port.</p><blockquote><strong>With all the pieces in place, the code is ready to roll!</strong></blockquote><p>Before you start testing your API, don’t forget to start the server by running:</p><pre>node serverfilename.js</pre><p>Also, <strong>make sure your MongoDB database is up and running</strong> so Mongoose can connect and interact with it. Without the server running and the database active, the API won’t work as expected.</p><blockquote>Testing Your MongoDB API</blockquote><p>Once your server is up and running, you can test the API using an API testing tool like Postman or Insomnia. Simply send a GET request to the appropriate endpoint (e.g., http://localhost:5000/api/data) to see if your data is being fetched correctly from the database.</p><p><strong>And that’s a wrap!</strong></p><p>I hope this guide has helped you understand how to set up and test a simple API with Node.js, Express, and MongoDB. If you have any questions or feedback, feel free to leave a comment below. Thanks for reading, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b587c725b661" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>