<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ali Shour </title>
    <description>The latest articles on DEV Community by Ali Shour  (@iamshour).</description>
    <link>https://dev.to/iamshour</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F395700%2Fe9cce208-c5cb-4396-b68b-03bb6dee8007.png</url>
      <title>DEV Community: Ali Shour </title>
      <link>https://dev.to/iamshour</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/iamshour"/>
    <language>en</language>
    <item>
      <title>React state management - Part 1: Introduction &amp; local state management</title>
      <dc:creator>Ali Shour </dc:creator>
      <pubDate>Mon, 02 May 2022 23:30:34 +0000</pubDate>
      <link>https://dev.to/iamshour/react-state-management-part-1-introduction-local-state-management-23h0</link>
      <guid>https://dev.to/iamshour/react-state-management-part-1-introduction-local-state-management-23h0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;While building a website using React, one of the most important things that you'll heavily use and rely upon is managing your state.&lt;/p&gt;

&lt;p&gt;Throughout this series, I'll illustrate on the best use cases and ways to manage state throughout my applications and websites.&lt;/p&gt;

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

&lt;p&gt;More than a decade ago, developers used to build websites using Vanilla JS, while writing a lot of redundant code, resulting in longer processes. After a couple of years, developers were able to use newly introduced JS Frameworks based on UI components. This made the process easier and shorter to produce modern websites, with extra features such as re-using any component on our website. React thus was born (by Facebook), and today it's simply the most popular JS framework around.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is React state management?
&lt;/h2&gt;

&lt;p&gt;Each React component have a built-in state object, where you store data/assets that are persistent between component renderings. We can manage any component state locally or using an external state management library.&lt;/p&gt;

&lt;h2&gt;
  
  
  Local state management
&lt;/h2&gt;

&lt;p&gt;Throughout this part of the series, We'll talk about managing our state locally.&lt;/p&gt;

&lt;p&gt;Whilst React ships with many useful hooks, one of the most widely used ones is the &lt;code&gt;useState()&lt;/code&gt; hook.&lt;/p&gt;

&lt;p&gt;Well first, what is a hook exactly? From the official &lt;a href="https://reactjs.org/docs/hooks-intro.html"&gt;docs&lt;/a&gt;, a Hook is a special function that lets you hook into React features. &lt;code&gt;useState&lt;/code&gt; is a Hook that lets you add React state to function components.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example #1
&lt;/h2&gt;

&lt;p&gt;Lets say we have a button that a user could toggle to show/hide specific data. In order to persist the status of this button, we have to use the &lt;code&gt;useState&lt;/code&gt; hook to keep track of the state itself. Let's see the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useState} from 'react'

export default function App() {

    // Declare a new state variable, which we'll call "isVisible"
    // It could be of any type, but here its a Boolean

    const [isVisible, setIsVisible] = useState(false)

    return (
        &amp;lt;&amp;gt;
            &amp;lt;button onClick={setIsVisible(prev =&amp;gt; !prev)}&amp;gt;Toggle&amp;lt;/button&amp;gt;
            {isVisible &amp;amp;&amp;amp; &amp;lt;div&amp;gt;Hello there my friends, again!!&amp;lt;/div&amp;gt;}
        &amp;lt;/&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;First, when we called the useState hook, we declared a new "state variable". It returns a pair of values: the current state variable, which is in our example &lt;code&gt;isVisible&lt;/code&gt;, and a function that we must use in order to update this value, aka &lt;code&gt;setIsVisible&lt;/code&gt; in our example. The argument we passed to the hook itself is the initial state, which in our example represents a Boolean (false).&lt;/p&gt;

&lt;p&gt;Next we hooked our button with a callback function, calling the &lt;code&gt;setIsVisible(prev =&amp;gt; !prev)&lt;/code&gt;. Clicking on this button would effectively flip this Boolean value to the opposite of its previous value.&lt;/p&gt;

&lt;p&gt;Thus, when a user presses the toggle button for the first time, it changes the &lt;code&gt;isVisible&lt;/code&gt; boolean value from false to true, which results in showing the message &lt;code&gt;&amp;lt;div&amp;gt;Hello there my friends, again!!&amp;lt;/div&amp;gt;&lt;/code&gt;. Clicking it again results in hiding the value again as it was originally.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example #2
&lt;/h2&gt;

&lt;p&gt;Now let's take another example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useState} from 'react'

const Message = ({user}) =&amp;gt; {
    return (
        &amp;lt;h1&amp;gt;User Name: {user.name}&amp;lt;/h1&amp;gt;
        &amp;lt;h2&amp;gt;User Age: {user.age}&amp;lt;h2&amp;gt;
    )
}

export default function App() {

    const [user, setUser] = useState({
        name: 'Sam',
        age: '24'
    })

    return (
        &amp;lt;&amp;gt;
            &amp;lt;p&amp;gt;User information:&amp;lt;/p&amp;gt;
            &amp;lt;Message user={user} &amp;gt;
        &amp;lt;/div&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;In the above example, In the App component (Parent) we declared a new state variable &lt;code&gt;user&lt;/code&gt; using the &lt;code&gt;useState&lt;/code&gt; hook, while passing the initial state as an object containing some user information (mimicking an object fetched from some auth API). We then called a child component &lt;code&gt;Message&lt;/code&gt; that we 'll create now and passed the &lt;code&gt;user&lt;/code&gt; state variable as a prop. Then we create this &lt;code&gt;Message&lt;/code&gt; child component and destructure the user state variable from the props and consumed it as we want (in our example we just displayed user's name and age in a simple message).&lt;/p&gt;

&lt;p&gt;This example is just a very simple and basic presentation on how state variables gets passed from a parent component to its child, which relates to prop-drilling. Whilst we should always keep in mind that this flow of data is always downwards, which means we simply can't declare a state variable in a child component and consume it in the parent, but its the other way around.&lt;/p&gt;

&lt;h2&gt;
  
  
  Downside of prop-drilling
&lt;/h2&gt;

&lt;p&gt;Throughout a more complex development environment, sometimes simple prop-drilling of some state may create complexity to our work-flow. The reason is what if we need to consume a certain state variable not in a child directly, but rather in a deeper nested child. We'll need to tweak our code and find a better way of consuming state coming from a grand ancestor (grandparent). This is exactly where state management libraries come in hand. In the following parts of this blog series, we'll take a look at my implementations when dealing with global state management.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final thoughts
&lt;/h2&gt;

&lt;p&gt;State management is mandatory in any web development architecture, thus mastering your way through the best practices and ways of dealing with state management is a huge boost to your web development career, so please make sure to read the next upcoming parts of this blog series.&lt;/p&gt;

&lt;p&gt;I'm constantly writing new blog posts where I share my expertise &amp;amp; skills in topics related to web development. If you're interested in such topics to boost your development career, consider following me! 😇 Or visit my personal &lt;a href="https://iamshour.com"&gt;website&lt;/a&gt;!&lt;br&gt;&lt;br&gt;
Thanks for reading, Ciao! 👋&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>statemanagement</category>
    </item>
    <item>
      <title>Creating a RESTful API easily using node.js | Part 3</title>
      <dc:creator>Ali Shour </dc:creator>
      <pubDate>Mon, 25 Apr 2022 20:40:05 +0000</pubDate>
      <link>https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-3-5hm0</link>
      <guid>https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-3-5hm0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Throughout the two previous parts, we've learned how to setup a very basic RESTful API from scratch, and tested this API locally in a very simple example. In this post, we're going to integrate this API with MongoDB Atlas, and use mongoose to manipulate our database collection by fetching, editing, and deleting some data. Fist step is to open your project with your favorite code editor (VS code in my case). You can download the source code from the previous part by cloning/downloading this &lt;a href="https://github.com/iamshour/RESTful-api-testing.git"&gt;repo&lt;/a&gt;. Or Download Full project by cloning/downloading this &lt;a href="https://github.com/iamshour/RESTful-api-testing/tree/rest-api-mongodb-integration"&gt;repo&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding new packages
&lt;/h2&gt;

&lt;p&gt;First of all, let's add some new packages we're going to use in our project. Open up the terminal, and make sure you're in the root directory of your project, then run the following script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i dotenv mongoose

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

&lt;/div&gt;



&lt;p&gt;The first package (dotenv) is used to add environment variables in our project. The second package (mongoose) is just a JS library that creates a connection between MongoDB and the Express web app framework fluently.&lt;/p&gt;

&lt;h2&gt;
  
  
  File Structure
&lt;/h2&gt;

&lt;p&gt;Our next step is to create an intuitive, easy-to-use file structure for our project. This step is vital for the long-term life of your project for many reasons. For starters, a messy structure and code often leads to critical issues in the future. However, a good file structure helps us not only write cleaner and readable code, but also avoid repetition by writing reusable pieces of code across our app, in addition to ability to add new features and blocks of code (middleware) without disrupting any existing code.&lt;/p&gt;

&lt;p&gt;Let's take a look at the structure I'm initially going to follow:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Opx5r_Wl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918563849/DNTQBcOzz.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Opx5r_Wl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918563849/DNTQBcOzz.PNG" alt="file-structure.PNG" width="256" height="233"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each folder serves its unique purpose:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Routes folder contains each route file for our project&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Controllers folder contains the logic that each specific route performs&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Models folder containing all the models created (each model is an instance f a document). Models are responsible for creating and reading documents from the underlying MongoDB database&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Middleware folder contains each middleware function we may for specific routes&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Utils folder contains useful utility functions&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;.env file which contains all environment variables we're going to use&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Signing up with MongoDB Atlas
&lt;/h2&gt;

&lt;p&gt;Next, we're going to (sign up &lt;a href="https://www.mongodb.com/cloud/atlas/register2"&gt;here&lt;/a&gt;) in order to integrate our API with mongoDB Atlas services. After signing up, follow the steps below:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Choose the Shared Cluster option (free tier option), and click 'Create Cluster'&lt;/li&gt;
&lt;li&gt;Add a username and password under the 'How would you like to authenticate your connection?' option and click 'Add user'. Make sure to save those credentials to use later&lt;/li&gt;
&lt;li&gt;Add an IP address to access the project. For now, just add 0.0.0.0 and click 'Add Entry'&lt;/li&gt;
&lt;li&gt;After finishing all the above steps, click 'Finish and Close' on the bottom. Note that creating a cluster would take about 3-5 mins&lt;/li&gt;
&lt;li&gt;Next, click on connect button -&amp;gt; Connect your application -&amp;gt; Copy the connection string provided&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0BMmPY6H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918835493/LAgPUNQVM.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0BMmPY6H--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918835493/LAgPUNQVM.PNG" alt="pic-2.PNG" width="562" height="77"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;6.&lt;/code&gt; Open .env file which we created earlier, and add the following (Make sure to replace &lt;code&gt;yourusername&lt;/code&gt; and &lt;code&gt;&amp;lt;password&amp;gt;&lt;/code&gt; with your actual credentials):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MONGO_URL = mongodb+srv://yourusername:&amp;lt;password&amp;gt;@cluster0.yv.mongodb.net/myFirstDatabase?retryWrites=true&amp;amp;w=majority

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating a monogoDB connection
&lt;/h2&gt;

&lt;p&gt;After setting up our cluster, we're going to connect to it right from our application.&lt;/p&gt;

&lt;p&gt;First create a new file inside Utils folder called connectDB.js then navigate inside the file and add the following helper function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import mongoose from "mongoose"

const options = {
    useUnifiedTopology: true,
    useNewUrlParser: true,
}

const connectDb = () =&amp;gt; {
    if (mongoose.connections[0].readyState) {
        console.log("MongoDB already connected")
        return
    }
    return mongoose.connect(process.env.MONGO_URL, options, () =&amp;gt; {
        console.log("Connected successfully to the DB!")
    })
}

export default connectDb

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Modifying index.js
&lt;/h2&gt;

&lt;p&gt;Next, we'll modify our index.js file as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from "express"
import cors from "cors"
import helmet from "helmet"
import msgsRoute from "./routes/msgs.js"
import dotenv from "dotenv"
import connectDb from "./utility/connectDb.js"

const app = express()
const port = process.env.PORT || 5000

const corsOptions = {
    origin: "*",
    "Access-Control-Allow-Origin": true,
    optionSuccessStatus: 200,
}

app.use(cors(corsOptions))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(helmet())

dotenv.config()
connectDb()

app.use("/msgs", msgsRoute)

app.get("/", (req, res) =&amp;gt; {
    res.send("Welcome to our RESTful API!")
})

app.use((req, res, next) =&amp;gt; {
    const error = new Error("Something went wrong")
    error.status = 404
    next(error)
})
app.use((error, req, res, next) =&amp;gt; {
    res.status(error.status || 500)
    res.json({
        error: {
            message: error.message,
        },
    })
})

app.listen(port, (err) =&amp;gt; {
    if (err) throw new Error("Error while connecting to the server")
    console.log(`Server is live and running at: http://localhost:${port}`)
})

export default app

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

&lt;/div&gt;



&lt;p&gt;The only changes we've made from our setup in &lt;a href="https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-2-4l6h"&gt;part-2&lt;/a&gt; are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;imported the dotenv package at the top, then called config() method on it (after app initialization)&lt;/li&gt;
&lt;li&gt;imported our newly created helper function (connectDb) used to connect to our mongodb cluster, then called this function (after app initialization)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Creating our first Model
&lt;/h2&gt;

&lt;p&gt;As mentioned before, models are responsible for creating and reading documents from the underlying MongoDB database. For example, most database collections contains a User model, which basically resembles an object containing some useful data about a user (name, email, password, bio, age, etc...).&lt;/p&gt;

&lt;p&gt;Lets create a Message model by first creating a file called message.js inside models folder, then add the following to the file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import mongoose from "mongoose"

const messageSchema = new mongoose.Schema(
 {
  content: {
   type: String,
   required: [true, "Please provide message content"],
  },
 },
 {
  timestamps: true,
 }
)

const Dataset = mongoose.models.message || mongoose.model("message", messageSchema)

export default Dataset

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Modifying msgs route
&lt;/h2&gt;

&lt;p&gt;In the previous part, we created a msgs route in the routes folder which gathers all http methods related to msgs collection. Let's edit this file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from "express"
import { addMsg, deleteMsg, getMsgs, updateMsg } from "../controllers/msgs.js"

const router = express.Router()

router.get("/", getMsgs)
router.post("/", addMsg)
router.put("/:msgId", updateMsg)
router.delete("/:msgId", deleteMsg)

export default router

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

&lt;/div&gt;



&lt;p&gt;In the above modification, we've separated the logic of each http method (GET, POST, PUT, DELETE) by importing new helper functions created in a new separate controller file, which resides inside the controllers folder. So let's navigate to this newly created file and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Message from "../models/message.js"

export const getMsgs = async (req, res) =&amp;gt; {
    try {
        const msgs = await Message.find()

        res.status(201).json(msgs)
    } catch (error) {
        res.status(500).json({
            msg: error,
        })
    }
}

export const addMsg = async (req, res) =&amp;gt; {
    try {
        const newMsg = await Message.create({ content: req.body.content })
        res.status(201).json(newMsg)
    } catch (error) {
        res.status(500).json({
            msg: error,
        })
    }
}

export const updateMsg = async (req, res) =&amp;gt; {
    try {
        await Message.findByIdAndUpdate(
            req.params.msgId,
            { $set: req.body },
            {
                new: true,
            }
        )
        res.status(200).json("Message has been updated successfully!")
    } catch (error) {
        res.status(500).json({
            msg: error,
        })
    }
}

export const deleteMsg = async (req, res) =&amp;gt; {
    try {
        let msg = await Message.findById(req.params.msgId)

        if (!msg)
            return res.status(404).json({
                msg: "msg Not Found",
            })

        await msg.remove()

        res.status(200).json("Msg has been deleted successfully!")
    } catch (err) {
        res.status(500).json({
            msg: error,
        })
    }
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Testing the newly created endpoints
&lt;/h2&gt;

&lt;p&gt;After adding the functions above, we're ready to start our server in order to test our endpoints. Open up your terminal, and run the following script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start-dev

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

&lt;/div&gt;



&lt;p&gt;Now that our server is live, let's open up &lt;a href="https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client"&gt;Thunder client&lt;/a&gt;, or your favorite API testing tool, such as &lt;a href="https://www.postman.com/downloads/"&gt;postman&lt;/a&gt; to test our newly created endpoints.&lt;/p&gt;

&lt;h3&gt;
  
  
  Post request
&lt;/h3&gt;

&lt;p&gt;Our first test would be posting a new message to our database since its still empty.&lt;/p&gt;

&lt;p&gt;Lets add our endpoint at the top, change the http method to POST on the left, click on the body tab, pick raw JSON option, and add the following JSON object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "content": "Hey there my great friends!"
}

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

&lt;/div&gt;



&lt;p&gt;Then click on the send button to add our message model to our database collection. The process would look something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--STXWvwqA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918651102/NTZwJGp1N.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--STXWvwqA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918651102/NTZwJGp1N.PNG" alt="post-req-1.PNG" width="632" height="265"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The response we'll get back would look something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--y9qLHB0I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918680260/pbFfm-BiF.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--y9qLHB0I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918680260/pbFfm-BiF.PNG" alt="post-req-2.PNG" width="435" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To see our live changes, lets navigate to our database collection going back to our cluster options in the mongoDB Atlas website and clicking on the browse collections option, which will show us our collection:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ov6yZjHy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918711460/FEqQN3gi7.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ov6yZjHy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918711460/FEqQN3gi7.PNG" alt="pic-11.PNG" width="552" height="79"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--WvRvojrZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918723519/kxtvI0JyF.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--WvRvojrZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918723519/kxtvI0JyF.PNG" alt="pic-12.PNG" width="620" height="319"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  PUT request
&lt;/h3&gt;

&lt;p&gt;Now that we have an existing model inside our messages collection, we can add as much as we want. Now, we'll edit an existing message like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3NfsrmmH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918873649/1ZIHg_wI_.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3NfsrmmH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918873649/1ZIHg_wI_.PNG" alt="put-1.PNG" width="635" height="235"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The response we'll get back would look something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--e3IrUw9D--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918904440/yGJq9NzSG.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--e3IrUw9D--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918904440/yGJq9NzSG.PNG" alt="put-2.PNG" width="439" height="142"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Delete request
&lt;/h3&gt;

&lt;p&gt;Now we're going to delete an existing model from our collection by adding its unique ID to the request params (similar to what we did above for the PUT request). The process will look something like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--YayY1FQO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918922153/ue3UCbrtR.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--YayY1FQO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650918922153/ue3UCbrtR.PNG" alt="delete.PNG" width="641" height="476"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Throughout this series, we've learned how to create a simple RESTful API from scratch, tested it locally, and the integrated it with mongoDB to simulate CRUD operations in our platform. Knowing how to properly use a RESTful API is definitely a huge asset to add in your skill-set. Download Full project by clonning/downloading this &lt;a href="https://github.com/iamshour/RESTful-api-testing/tree/rest-api-mongodb-integration"&gt;repo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I'm constantly writing new blog posts where I share my expertise &amp;amp; skills in topics related to web development. If you're interested in such topics to boost your development career, consider following me! 😇 Or visit my personal &lt;a href="https://iamshour.com"&gt;website&lt;/a&gt;!&lt;br&gt;&lt;br&gt;
Thanks for reading, Ciao! 👋&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>restapi</category>
      <category>node</category>
      <category>mongodb</category>
    </item>
    <item>
      <title>Creating a RESTful API easily using node.js | Part 2</title>
      <dc:creator>Ali Shour </dc:creator>
      <pubDate>Mon, 25 Apr 2022 03:07:01 +0000</pubDate>
      <link>https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-2-4l6h</link>
      <guid>https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-2-4l6h</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Throughout the &lt;a href="https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-1-2fh2"&gt;first part&lt;/a&gt;, we've learned how to create a very basic RESTful API, which could be used to communicate with our back-end architecture and fetch data from our database. During this post, I'm going to test this API locally in a simple example to understand its technical usage.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Helmet
&lt;/h2&gt;

&lt;p&gt;Our first step is to install a new package called helmet to our dependencies. It is used to automatically secure our app by setting various HTTP headers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i helmet
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;h2&gt;
  
  
  New Routes folder
&lt;/h2&gt;

&lt;p&gt;Next, we're going to create a new folder called routes in the root directory and add a file inside this folder called msgs.js. This file stands for a specific route (msgs route) that contains one or more http method/s (GET, POST, PUT, DELETE).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8jqLyAUZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650853612886/oWoOc31ai.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8jqLyAUZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650853612886/oWoOc31ai.PNG" alt="Capture-1.PNG" width="259" height="158"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now open this newly created msgs.js route, and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from "express"

const router = express.Router()

const msgs = [
    {
        "id": "1",
        "content": "Hey there my friends!"
    },
    {
        "id": "2",
        "content": "Hello hello hello!"
    },
    {
        "id": "3",
        "content": "I hope everything is great!"
    },
    {
        "id": "4",
        "content": "How are you today?"
    }
];

router.get('/', (req, res) =&amp;gt; {
    res.send(msgs);
});

export default router
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;h2&gt;
  
  
  Modifying index.js
&lt;/h2&gt;

&lt;p&gt;Next, we'll modify our index.js file as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from "express"
import cors from "cors"
import helmet from "helmet"
import msgsRoute from "./routes/msgs.js"

const app = express()
const port = process.env.PORT || 5000

const corsOptions = {
    origin: "*",
    "Access-Control-Allow-Origin": true,
    optionSuccessStatus: 200,
}

app.use(cors(corsOptions))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(helmet())

app.use("/msgs", msgsRoute)

app.get("/", (req, res) =&amp;gt; {
    res.send("Welcome to our RESTful API!")
})

app.use((req, res, next) =&amp;gt; {
    const error = new Error("Something went wrong")
    error.status = 404
    next(error)
})
app.use((error, req, res, next) =&amp;gt; {
    res.status(error.status || 500)
    res.json({
        error: {
            message: error.message,
        },
    })
})

app.listen(port, (err) =&amp;gt; {
    if (err) throw new Error("Error while connecting to the server")
    console.log(`Server is live and running at: http://localhost:${port}`)
})

export default app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The only changes we've made from our setup in &lt;a href="https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-1-2fh2"&gt;part-1&lt;/a&gt; are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;calling helmet package on our app&lt;/li&gt;
&lt;li&gt;Initializing a corsOptions object and passing it as an argument when we called cors()&lt;/li&gt;
&lt;li&gt;calling our msgs route to be able to consume it

&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Testing using Thunder client
&lt;/h2&gt;

&lt;p&gt;Last but not least, open your terminal, and type the following script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that our server is live, we'll test our API endpoints using any API testing tool, such as &lt;a href="https://www.postman.com/downloads/"&gt;postman&lt;/a&gt;. But I prefer to use &lt;a href="https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client"&gt;Thunder client&lt;/a&gt; which is a VS code extension for simple API testing. After installing the extension, open it from the left bar (or ctrl + shift + p and search for thunder client), add the API endpoint on top and click send:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--69UoaD1W--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650853631734/BVDNcva9k.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--69UoaD1W--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650853631734/BVDNcva9k.PNG" alt="Capture-2.PNG" width="487" height="647"&gt;&lt;/a&gt;&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Throughout the example above, we've tested our API locally by manually creating msgs array (simulating a database model), and fetching its items using our API. Of course this isn't anywhere near complete, but it's just a simple starting way for beginners to understand how an API works in general. Click &lt;a href="https://github.com/iamshour/RESTful-api-testing"&gt;here&lt;/a&gt; for source code of this blog-post. Throughout the next blog post, I'm going to connect this API with a database (MongoDB) and use other http methods (PUT, POST, DELETE) to modify my database collection.&lt;/p&gt;

&lt;p&gt;I'm constantly writing new blog posts where I share my expertise &amp;amp; skills in topics related to web development. If you're interested in such topics to boost your development career, consider following me! 😇 Or visit my personal &lt;a href="https://iamshour.com"&gt;website&lt;/a&gt;!&lt;br&gt;&lt;br&gt;
Thanks for reading, Ciao! 👋&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>restapi</category>
      <category>node</category>
    </item>
    <item>
      <title>Creating a RESTful API easily using node.js | Part 1</title>
      <dc:creator>Ali Shour </dc:creator>
      <pubDate>Tue, 19 Apr 2022 01:05:24 +0000</pubDate>
      <link>https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-1-2fh2</link>
      <guid>https://dev.to/iamshour/creating-a-restful-api-easily-using-nodejs-part-1-2fh2</guid>
      <description>&lt;h2&gt;
  
  
  What is a RESTful API?
&lt;/h2&gt;

&lt;p&gt;First off, an API, short for Application Programming Interface, is simply a way of communication between two or more services, sometimes described as a mediator between users/clients &amp;amp; resources/services they request. RESTful APIs, however, is a set of principles that conforms to the constraints of REST architecture style and thus allowing for integration with RESTful web services.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step.1: Initializing a new project
&lt;/h2&gt;

&lt;p&gt;The very first step is to create an empty folder manually in the directory of your choice (Using Right-click), or via Terminal/Bash:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir myProject
cd ./myProject

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

&lt;/div&gt;



&lt;p&gt;Then setting up a new empty npm package using legacy init (-y for ignoring questions):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y

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

&lt;/div&gt;



&lt;p&gt;Note that you first have to have node.js installed on your machine. Another side note is that you can edit the package.json file and add your specified info such your name (author), git repo, description, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step.2: Installing necessary dependencies
&lt;/h2&gt;

&lt;p&gt;Although I'll be using the most basic setup to create a very simple RESTful api, you can definitely add any other package you find useful. The two main packages I'll be using are express, which is a minimal node.js framework used to simplify our workload, and CORS which handles Cross-Origin-Resource-Sharing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express cors

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

&lt;/div&gt;



&lt;p&gt;I'll also be using nodemon, which is a tool that automatically restarts our node application when file changes in the directory are detected:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i --save-dev nodemon

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step. 3: Creating an entry point
&lt;/h2&gt;

&lt;p&gt;The next step is to create an entry point for our node.js application (usually named index.js) inside the root of our project. Then modifying our package.json file as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "project-name",
  "version": "1.0.0",
  "description": "Add project description here if you want to",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node index.js",
    "start-dev": "nodemon index.js",
  },
  "keywords": [],
  "author": "your-name",
  "license": "ISC"
}

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

&lt;/div&gt;



&lt;p&gt;Notice that in order to run our application locally (development environment), We'll use the second script (start-dev), whilst the first one is only for production environment. Another side note is that adding "type": "module" to the package.json enables ES6 features.&lt;/p&gt;

&lt;p&gt;Next, and before starting our app, open the newly created index.js file and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from "express"
import cors from "cors"

const app = express()

app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cors())

const port = process.env.PORT || 5000

app.get("/", (req, res) =&amp;gt; {
    res.send("Welcome to our new custom API!")
})

app.use((req, res, next) =&amp;gt; {
    const error = new Error("Something went wrong")
    error.status = 404
    next(error)
})
app.use((error, req, res, next) =&amp;gt; {
    res.status(error.status || 500)
    res.json({
        error: {
            message: error.message,
        },
    })
})

app.listen(port, (err) =&amp;gt; {
    if (err) throw new Error("Error while connecting to the server")
    console.log(`Server is live and running at: http://localhost:${port}`)
})

export default app

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

&lt;/div&gt;



&lt;p&gt;Throughout the above setup, we initiated our app using express, called some useful express methods, and used the cors package which we installed earlier. We also assigned a port variable, created a welcome message to appear when calling our API, and simply handled any unexpected future errors. Last but not least, we called the listen method in order to start a server on our custom port.&lt;/p&gt;

&lt;p&gt;Now fire the following command on your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start-dev

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

&lt;/div&gt;



&lt;p&gt;Pressing ctrl + link provided on our terminal will fire a localhost server as the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--T1dYHN8n--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650329994522/8zYmTCd8r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--T1dYHN8n--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1650329994522/8zYmTCd8r.png" alt="localhost.png" width="556" height="382"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Throughout this example, we created a very basic RESTful API, which of course isn't anywhere near complete, but a good building block for an API. In the upcoming part, we'll add more functionalities to our API, and test it with and without a connection to a database.&lt;/p&gt;

&lt;p&gt;I'm constantly writing new blog posts where I share my expertise &amp;amp; skills in topics related to web development. If you're interested in such topics to boost your development career, consider following me! 😇 Or visit my personal &lt;a href="https://iamshour.com"&gt;website&lt;/a&gt;!&lt;br&gt;
Thanks for reading, Ciao! 👋&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>restapi</category>
      <category>node</category>
      <category>express</category>
    </item>
    <item>
      <title>Send emails from your website to any user super easily!</title>
      <dc:creator>Ali Shour </dc:creator>
      <pubDate>Mon, 18 Apr 2022 13:54:02 +0000</pubDate>
      <link>https://dev.to/iamshour/send-emails-from-your-website-to-your-users-it-cant-get-any-easier-p62</link>
      <guid>https://dev.to/iamshour/send-emails-from-your-website-to-your-users-it-cant-get-any-easier-p62</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;First of all, let me give you a heads up of what I'm going to be talking about, and the purpose of this blog. In today's world, almost every website or web-app sends all kinds of emails to their respective users, each with a distinct functionality or purpose.&lt;/p&gt;

&lt;h2&gt;
  
  
  Purpose of sending such emails
&lt;/h2&gt;

&lt;p&gt;Some examples of those emails are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;User verification emails (authentication)&lt;/li&gt;
&lt;li&gt;Reset authentication passwords&lt;/li&gt;
&lt;li&gt;Marketing emails&lt;/li&gt;
&lt;li&gt;Subscribing to a newsletter&lt;/li&gt;
&lt;li&gt;Responding to a report case (ticket) &lt;/li&gt;
&lt;li&gt;Responding to a contact-me form&lt;/li&gt;
&lt;li&gt;Transactional emails&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you can tell, there are a plenty of use cases where it's almost mandatory to send emails to our users right from our platform. But how can we implement an easy way to do so, without so much hassle?&lt;/p&gt;

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

&lt;p&gt;&lt;a href="https://nodemailer.com/about/"&gt;Nodemailer&lt;/a&gt;, by their own definition, is a module for Node.js applications to allow easy as cake email sending. It is the solution most users turn to by default.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project Implementation
&lt;/h2&gt;

&lt;p&gt;To start with this quick project, you must have a node.js application pre-set and running already. If you're not very familiar with node.js and need a little help setting up a simple back-end environment, check out my upcoming blog to help you out.&lt;/p&gt;

&lt;p&gt;Next up, install Nodemailer in your root directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i nodemailer

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

&lt;/div&gt;



&lt;p&gt;Now you need to use an email delivery service, which provides you with a simple way to send those quick emails to your clients/visitors. There are plenty of those services available, with each having it's own features and pros over the other. The most common ones are Sendgrid, SendInBlue, HubSpot, omniSend, etc. The one I'll be using is going to be SendIbBlue, due to the ease of their service, and their pretty good customer support, in case of any unexpected issue. Steps for creating an account:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visit their official &lt;a href="https://www.sendinblue.com/"&gt;website&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Click on the sign up button on the top right corner&lt;/li&gt;
&lt;li&gt;Go to the SMTP &amp;amp; API tab, &lt;a href="https://account.sendinblue.com/advanced/api#tab-account-nodejs-sample"&gt;here&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Keep this tab open for later on, where we'll be using an API key or SMTP Server necessary for the setup later&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Modifying our node.js app
&lt;/h2&gt;

&lt;p&gt;Now in order to see the magic happen, we need to modify our node.js app. First, Create a file inside the root directory, and call it whatever you like, ex. sendMail.js. Next, import nodemailer as below (P.S. To use import method over require, go to package.json file, and add the option, "type": "module")&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import nodemailer from 'nodemailer'

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

&lt;/div&gt;



&lt;p&gt;Then, we'll create and export a function, which contains the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Creating a transport using nodemailer's createTransport() method, while passing server info, which we got from sendInBlue as an argument&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Creating a mailOptions object, which contains our email options such as sender email, receiver email, subject of the email, and the email itself &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Calling SendMail() method on the transport while passing the above options as an argument&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import nodemailer from "nodemailer"

//Note that I stored my credentials in my .env file
const { SMTP_KEY, SMTP_PASS, SENDER_EMAIL, REPORT_PASS } = process.env

export const sendReportMail = (to, mailContent) =&amp;gt; {
    const smtpTransport = nodemailer.createTransport({
        host: "smtp-relay.sendinblue.com",
        service: "Sendinblue",
        port: 587,
        auth: {
            user: SMTP_KEY,
            pass: SMTP_PASS,
        },
    })

    const mailOptions = {
        from: SENDER_EMAIL,
        to: [to, SENDER_EMAIL],
        subject: "Email subject",
        html: `
            &amp;lt;div &amp;gt;
                    Dear ${mailContent?.name},
                    Thanks for contacting us! We'll make sure to get back in touch as soon as possible!
            &amp;lt;/div&amp;gt;
        `,
    }

    smtpTransport.sendMail(mailOptions, (err, info) =&amp;gt; {
        if (err) return err
        return info
    })
}

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

&lt;/div&gt;



&lt;p&gt;Last but not least, we can use this function inside any router controller to easily send user emails, as the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const sendReport = async (req, res) =&amp;gt; {
// Getting report data, which the user himself added, while we received this data with a POST request
    const { firstName, lastName, subject, message } = req.body

    try {

            const mailContent = {
                name: `${firstName} ${lastName}`,
                subject,
                message,
            }

            sendReportMail(user?.email, mailContent)

            res.status(200).json({
                message:
                    "Report submitted successfully! Please check your email for confirmation.",
            })
        }
    } catch (err) {
        if (err?.errors?.email?.name === "ValidatorError") {
            res.status(403).json({
                message: "Please enter a valid email",
            })
        } else {
            res.status(500).json({
                message: "Server Error",
            })
        }
    }
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;By Implementing the above steps correctly, you could hugely benefit in any of your projects that requires authentication, or if you simply want to send quick marketing emails to your end users. The use cases are definitely much more than that, but in short this would be a great tool to at least try.&lt;/p&gt;

&lt;p&gt;I'm constantly writing new blog posts where I share my expertise &amp;amp; skills in topics related to web development. If you're interested in such topics to boost your development career, consider following me! 😇 Or visit my personal &lt;a href="https://iamshour.com"&gt;website&lt;/a&gt;!&lt;br&gt;
Thanks for reading, Ciao! 👋&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>node</category>
      <category>nodemailer</category>
      <category>emails</category>
    </item>
  </channel>
</rss>
