<?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>Forem: Tirth Raval</title>
    <description>The latest articles on Forem by Tirth Raval (@tirthraval1999).</description>
    <link>https://forem.com/tirthraval1999</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%2F1276593%2F3d0bc95e-33de-4b04-862d-dce017460e47.jpg</url>
      <title>Forem: Tirth Raval</title>
      <link>https://forem.com/tirthraval1999</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/tirthraval1999"/>
    <language>en</language>
    <item>
      <title>Building a Todo Application Backend with MongoDB and Express</title>
      <dc:creator>Tirth Raval</dc:creator>
      <pubDate>Thu, 11 Apr 2024 05:09:02 +0000</pubDate>
      <link>https://forem.com/tirthraval1999/building-a-todo-application-backend-with-mongodb-and-express-2k34</link>
      <guid>https://forem.com/tirthraval1999/building-a-todo-application-backend-with-mongodb-and-express-2k34</guid>
      <description>&lt;p&gt;In modern web development, creating robust backend services is essential, especially when dealing with dynamic data like todos. In this tutorial, I will build a Todo Application backend using MongoDB as our database and Express.js as our server framework. We'll leverage the Mongoose library to interact with MongoDB in a schema-based manner.&lt;/p&gt;

&lt;p&gt;Getting Started&lt;br&gt;
First things first, let's set up our environment. Ensure you have Node.js installed, and then install the necessary dependencies:&lt;/p&gt;

&lt;p&gt;npm install express mongoose --save&lt;/p&gt;

&lt;p&gt;Connecting to MongoDB&lt;br&gt;
To begin, import the required libraries:&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;Next, establish a connection to your MongoDB database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongoose.connect('your MongoDB connection string/collection_name');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Defining the Schema&lt;br&gt;
Even though MongoDB is a schema-less database, Mongoose requires us to define a schema before creating models. Let's define our Todo schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const todoSchema = mongoose.Schema({
    title: String,
    description: String,
    isComplete: {
        type: Boolean,
        default: false
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Creating the Model&lt;br&gt;
With the schema in place, let's create a model for our Todo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const todo = mongosse.model('todo' , todoSchema);

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

&lt;/div&gt;



&lt;p&gt;Get all Todos&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/todos', async (req, res) =&amp;gt; {
    try {
        const todos = await Todo.find({});
        if (!todos) {
            res.status(404).json({ msg: "Data not found" });
        } else {
            res.json({ todos });
        }
    } catch (error) {
        res.status(500).json({ msg: error });
    }
});

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

&lt;/div&gt;



&lt;p&gt;Create a new todo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post('/create-todo', async(req, res) =&amp;gt;{
    //create the todos
    const {title, descrption} = req.body;

    try{
        await todo.create({
            title,
            description
        })
        res.json({
            msg :"To do created"
        })
    }
    catch(error){
        res.status(411).json({
            msg: "Error"
        })
    }
    //write the logic of creating a todo
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update a Todo&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.put('/update-todo', async(req,res) =&amp;gt;{
    //update the todo

    const {id} = req.body;
    try{
        await todo.updateOne({
            _id : id
        }, {
            isComplate : true
        })
        res.json({
            msg : "Task completed"
        })
    }
    catch(error){
        res.status(505).json({
            msg : "Server Error"
        })
    }

})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conclusion&lt;br&gt;
In this tutorial, we've covered the basics of building a Todo Application backend using MongoDB and Express. We've learned how to define schemas, create models, and implement CRUD operations. &lt;/p&gt;

&lt;p&gt;Please see the below Github link for the code:&lt;br&gt;
&lt;a href="https://github.com/tirthraval/todo-backend"&gt;https://github.com/tirthraval/todo-backend&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Happy coding! 🚀&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>express</category>
      <category>mongodb</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Getting Started with MongoDB: A Beginner's Guide</title>
      <dc:creator>Tirth Raval</dc:creator>
      <pubDate>Wed, 10 Apr 2024 01:54:13 +0000</pubDate>
      <link>https://forem.com/tirthraval1999/getting-started-with-mongodb-a-beginners-guide-25g5</link>
      <guid>https://forem.com/tirthraval1999/getting-started-with-mongodb-a-beginners-guide-25g5</guid>
      <description>&lt;p&gt;Are you intrigued by the flexibility and power of NoSQL databases? If so, MongoDB might be the perfect starting point for your journey into the world of non-relational databases. In this beginner-friendly guide, we'll walk you through the basics of MongoDB, from setting up your first MongoDB instance to connecting it with a MongoDB compass.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding NoSQL and MongoDB&lt;/strong&gt;&lt;br&gt;
NoSQL databases, also known as non-relational databases, offer a schema-less approach to data storage. Unlike traditional relational databases, NoSQL databases like MongoDB allow you to store various types of data without rigid schemas. MongoDB, in particular, operates on a key-value pair model, offering flexibility and scalability for modern applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating Your MongoDB Instance&lt;/strong&gt;&lt;br&gt;
Sign Up for MongoDB: Begin your MongoDB journey by creating an account on the MongoDB website(&lt;a href="https://account.mongodb.com/account/login"&gt;https://account.mongodb.com/account/login&lt;/a&gt;). Navigate to MongoDB's website and follow the prompts to create your account.&lt;/p&gt;

&lt;p&gt;Create a New Project: Once logged in, create a new project by providing a project name and following the on-screen instructions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjcs6is6u93l0p3pp1tts.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjcs6is6u93l0p3pp1tts.png" alt="Create a new Project" width="800" height="376"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Provide a suitable name for your project and click on next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkzsgogkvn437uhia2gu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbkzsgogkvn437uhia2gu.png" alt="name of the project" width="800" height="378"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you create the project, you should get the below screen now click on the create button and select MO as a free cluster for learning purposes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F840wbwwlzoi5k89dfovz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F840wbwwlzoi5k89dfovz.png" alt="connect with compass" width="800" height="373"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With your MongoDB instance deployed, it's time to connect to the server. Follow the prompts to create a database user and choose a connection method, preferably Compass, for local visualization.&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8ntx4ealdzi0h6pwrzzp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8ntx4ealdzi0h6pwrzzp.png" alt="creating compass URL -1" width="800" height="380"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fokijll5kajjmvi0khtex.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fokijll5kajjmvi0khtex.png" alt="creating compass url-2" width="800" height="399"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Accessing MongoDB with Compass: Install MongoDB Compass if you haven't already, and paste the connection string provided during the setup process. Ensure to use the Mongo Cluster password for authentication.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft59ccnq7vidw0xsakgrz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft59ccnq7vidw0xsakgrz.png" alt="CONNETCTING with compass" width="800" height="403"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fymfegf9zec98q9f016lp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fymfegf9zec98q9f016lp.png" alt="connecting with compass -2" width="800" height="436"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exploring Your MongoDB Instance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Once successfully connected, you can explore your MongoDB instance using MongoDB Compass. This intuitive tool allows you to visualize and interact with your MongoDB databases effortlessly. Take time to familiarize yourself with the interface and the data stored in your instance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What's Next?&lt;/strong&gt;&lt;br&gt;
In our next blog post, we'll dive deeper into MongoDB by connecting it with an Express.js application. You'll learn how to integrate MongoDB into your backend stack, allowing you to leverage its capabilities for building robust and scalable web applications. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>nosql</category>
      <category>mongodb</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Understanding Token-Based Authentication with JSON Web Tokens (JWT) in Express.js</title>
      <dc:creator>Tirth Raval</dc:creator>
      <pubDate>Mon, 08 Apr 2024 06:51:12 +0000</pubDate>
      <link>https://forem.com/tirthraval1999/understanding-token-based-authentication-with-json-web-tokens-jwt-in-expressjs-5286</link>
      <guid>https://forem.com/tirthraval1999/understanding-token-based-authentication-with-json-web-tokens-jwt-in-expressjs-5286</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;:&lt;br&gt;
Authentication is a critical aspect of web applications, ensuring that only authorized users can access sensitive data and functionalities. Among various authentication methods, token-based authentication stands out for its simplicity and effectiveness. In this article, we'll delve into token-based authentication using JSON Web Tokens (JWT) in an Express.js application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Authentication Matters&lt;/strong&gt;:&lt;br&gt;
Authentication safeguards sensitive user data from unauthorized access. Without proper authentication mechanisms, anyone could access confidential information, posing significant security risks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Authentication?&lt;/strong&gt;:&lt;br&gt;
Authentication is the process of verifying the identity of a user. It typically involves combining a username and password to validate user credentials before granting access to resources.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Common Authentication Methods&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Password-based authentication&lt;/li&gt;
&lt;li&gt;Token-based authentication&lt;/li&gt;
&lt;li&gt;Cookie-based authentication&lt;/li&gt;
&lt;li&gt;OAuth-based authentication&lt;/li&gt;
&lt;li&gt;Token-Based Authentication with JWT&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Let us understand the Token-Based Authentication&lt;/strong&gt;:&lt;br&gt;
JWT, or JSON Web Token, is a compact, URL-safe means of representing claims to be transferred between two parties securely. It consists of three parts: header, payload, and signature.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JWT has three parts seperated by dots(.)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; Header - It has the JWT and the signing algorithm&lt;/li&gt;
&lt;li&gt; payload - It is just data which used to create the JWT&lt;/li&gt;
&lt;li&gt; signature - It is a kind of password to verify the JWT&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa66gp261o15iori46hx7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa66gp261o15iori46hx7.png" alt="JWT Working" width="800" height="338"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The user sends a request to authenticate (e.g., /signin) with their credentials.&lt;/li&gt;
&lt;li&gt;Upon successful validation, the server generates a JWT containing relevant user information.&lt;/li&gt;
&lt;li&gt;The client receives the JWT and includes it in subsequent requests to access protected resources.&lt;/li&gt;
&lt;li&gt;The server verifies the JWT's signature to ensure its authenticity and grants access to authorized resources.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Implementing JWT in Express.js&lt;/strong&gt;:&lt;br&gt;
We can integrate JWT seamlessly into Express.js applications using the jsonwebtoken library. Here's a step-by-step guide:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Install the jsonwebtoken library: npm install jsonwebtoken&lt;/li&gt;
&lt;li&gt;Import the library into your application.&lt;/li&gt;
&lt;li&gt;Utilize the provided methods (jwt.sign() and jwt.verify()) to manage JWTs.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const jwt = require('jsonwebtoken);
const jwtPassword = '12345678'

const user = {
    userName : "Tirth",
    password : "test@123"
}

//create the JWT

const token = jwt.sign({username : user.userName}, jwtPassword);
//token is nothing but very long string
//verify the token
const data = jwt.verify(token, jwtPasssword);
//data --&amp;gt; {
//  username : "Tirth" }
//
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In above code, I just explain how to manage JWT. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example Implementation:&lt;/strong&gt;&lt;br&gt;
We'll walk through a basic Express.js application demonstrating token-based authentication:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const jwt = require("jsonwebtoken");
const jwtPassword = "123456";

const app = express();
app.use(express.json())

const ALL_USERS = [
  {
    username: "harkirat@gmail.com",
    password: "123",
    name: "harkirat singh",
  },
  {
    username: "raman@gmail.com",
    password: "123321",
    name: "Raman singh",
  },
  {
    username: "priya@gmail.com",
    password: "123321",
    name: "Priya kumari",
  },
];

function userExists(username, password) {
  // write logic to return true or false if this user exists
  // in ALL_USERS array
const userFind = ALL_USERS.filter(user =&amp;gt; user.username === username &amp;amp;&amp;amp; user.password === password);

return userFind.lenght &amp;gt; 0 ?false:true


}

app.post("/signin", function (req, res) {
  const username = req.body.username;
  const password = req.body.password;

  if (!userExists(username, password)) {
    return res.status(403).json({
      msg: "User doesnt exist in our in memory db",
    });
  }

  var token = jwt.sign({ username: username }, jwtPassword);
  return res.json({
    token,
  });
});

app.get("/users", function (req, res) {
  const token = req.headers.authorization;
  try {
    const decoded = jwt.verify(token, jwtPassword);
    const username = decoded.username;
    console.log(decoded)
    const filteredUser = ALL_USERS.filter((user) =&amp;gt; user.username != username)
    res.json({
        userdata : filteredUser
    })
    // return a list of users other than this username
  } catch (err) {
    return res.status(403).json({
      msg: "Invalid token",
    });
  }
});

app.listen(3001)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above code implements a basic sign-in system that allows users to authenticate and obtain a JWT upon successful login. The JWT can then be used to access authorized resources (like the /users endpoint) that require authentication. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;:&lt;br&gt;
Token-based authentication using JSON Web Tokens provides a secure and efficient method for authenticating users in web applications. By understanding the principles behind JWT and its implementation in Express.js, developers can enhance the security of their applications while providing a seamless user experience.&lt;/p&gt;

&lt;p&gt;To learn more about the JWT please visit below link:&lt;br&gt;
&lt;a href="https://www.npmjs.com/package/jsonwebtoken"&gt;https://www.npmjs.com/package/jsonwebtoken&lt;/a&gt;&lt;br&gt;
&lt;a href="https://jwt.io/"&gt;https://jwt.io/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thank you so much for reading the Blog. &lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>jwt</category>
    </item>
    <item>
      <title>Simplifying Input Validation in Node.js with Zod</title>
      <dc:creator>Tirth Raval</dc:creator>
      <pubDate>Sun, 07 Apr 2024 07:38:50 +0000</pubDate>
      <link>https://forem.com/tirthraval1999/simplifying-input-validation-in-nodejs-with-zod-2cjm</link>
      <guid>https://forem.com/tirthraval1999/simplifying-input-validation-in-nodejs-with-zod-2cjm</guid>
      <description>&lt;p&gt;As developers, ensuring that the data flowing into our applications is accurate and well-structured is paramount. One small error in input validation can lead to significant issues down the line, compromising security and stability. Thankfully, with tools like Zod, handling input validation in Node.js applications has never been easier.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why Input Validation Matters
&lt;/h3&gt;

&lt;p&gt;Let's assume, instead of sending the username and the password a user sends some random data and tries to crash the server. It is our (Software Engineer) responsibility to check the data is in the proper format.&lt;/p&gt;

&lt;h3&gt;
  
  
  Introducing Zod
&lt;/h3&gt;

&lt;p&gt;Zod is a powerful JavaScript and TypeScript library that simplifies the process of defining data schemas and validating them at runtime. With Zod, developers can effortlessly define blueprints for their data, making input validation a breeze.&lt;/p&gt;

&lt;h3&gt;
  
  
  Install Zod: Start by installing Zod via npm using the command
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;npm install zod&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Import Zod:
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;cosnt {z} = require('zod');&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Creating Schemas with Zod
&lt;/h4&gt;

&lt;p&gt;Zod allows developers to create schemas that define the structure and constraints of their data. Let's take a look at how we can define schemas using Zod:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const usernameSchema = z.string()
const phoneSchema = z.number()

//we can create the object also

const user = z.object({
    username : z.string().min(5), //username will be a string with a min of 5 char
    email:z.email(), //email should be email
    firstname:z.sting().max(5) //first name will be string, and length should not exceed 5 char
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Let's see a few more primitive schemas.
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();

// empty types
z.undefined();
z.null();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Validating Inputs
&lt;/h3&gt;

&lt;p&gt;Once we've defined our schemas, Zod provides convenient methods for validating input data:&lt;br&gt;
&lt;/p&gt;

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

const {z} = require('zod');

//create the schema

const userSchema = z.object({
    firstname : z.string().min(5),
    lastname : z.string().min(5),
    email:z.email();
    password :z.string()
})

//parse the Shema

try{
    userSchema.safeparse({
        firstname: "Tirth",
        lastname:"Raval",
        email:"tirth.b.raval@gmail.com"
        password:"titrh@1234"
    })
}
catch (error){
    console.log("error ${error}")
}

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

&lt;/div&gt;



&lt;p&gt;Using safeParse, we can validate input data against our schema and handle any validation errors that may occur.&lt;/p&gt;

&lt;h3&gt;
  
  
  Integrating Zod with Express.js
&lt;/h3&gt;



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


app.use(express.json());
const useInputValidation = (req,res,next) =&amp;gt; {
    const input  = req.query.Kidneys;
    const inputSchema = zod.string();
    // console.log(typeof(input))
    if(!inputSchema.safeParse(input).success){

        res.status(400).json({
            msg:"Input are wrong"
        })
        return;
    }
    else{
       next();
    }

}
app.get('/health-chek', useInputValidation, (req,res)=&amp;gt;{

    res.json({
        msg :"You are find"
    })

});

app.listen(3000);

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

&lt;/div&gt;



&lt;p&gt;In this example, we've created a middleware function userInputValidation to validate incoming data before processing it further. If the input fails validation, we return a 400 Bad Request response with an error message.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Zod simplifies input validation in Node.js applications, providing a robust solution for ensuring data integrity and security. Developers can build more reliable, maintainable, and secure applications by defining clear schemas and leveraging Zod's validation capabilities. Whether you're working on a small personal project or a large-scale enterprise application, Zod has you covered when it comes to input validation in Node.js.&lt;/p&gt;

&lt;p&gt;Start using Zod today and streamline your input validation process like never before!&lt;/p&gt;

&lt;p&gt;Thank you!!&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>node</category>
      <category>express</category>
      <category>zod</category>
    </item>
    <item>
      <title>Enhance Your Express.js Backend with Middleware for Efficient Request Processing</title>
      <dc:creator>Tirth Raval</dc:creator>
      <pubDate>Sat, 06 Apr 2024 07:53:40 +0000</pubDate>
      <link>https://forem.com/tirthraval1999/enhance-your-expressjs-backend-with-middleware-for-efficient-request-processing-1mib</link>
      <guid>https://forem.com/tirthraval1999/enhance-your-expressjs-backend-with-middleware-for-efficient-request-processing-1mib</guid>
      <description>&lt;h3&gt;
  
  
  What is Middlewares in Express.js?
&lt;/h3&gt;

&lt;p&gt;In the realm of backend development with Express.js, managing repetitive tasks like user authentication and input validation across multiple endpoints can become cumbersome and lead to code redundancy. However, there's an elegant solution at hand: Middleware.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let's understand using an example Why do we need Middlewares?
&lt;/h3&gt;

&lt;p&gt;Whenever a user makes a new request to the backend, we need to do the following prechecks before resolving the request.&lt;/p&gt;

&lt;p&gt;1) Check if the user is valid or not (Authentication)&lt;br&gt;
2) do the input validation&lt;/p&gt;

&lt;p&gt;One simple solution I can think of is to write the logic of authentication and input validation for each endpoint. This solution is good but not the best because we are repeating our code and increasing the code readability.&lt;/p&gt;
&lt;h3&gt;
  
  
  What can we do to overcome this challenge?
&lt;/h3&gt;
&lt;h2&gt;
  
  
  THE BEST SOLUTION IS TO USE MIDDLEWARES
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Before jumping into the implementation part, first understand the flow of code execution.
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg1qe2zfwscdofdirf9jh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg1qe2zfwscdofdirf9jh.png" alt="Basic flow of the middlewares" width="800" height="618"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Let's understand how to create the middleware
&lt;/h3&gt;


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


app.get('/courses' , userAuthentication , (req, res) =&amp;gt; {
  //write the logic of getting all courses
})

app.listen(3000, () =&amp;gt;{
  console.log('server is running on 3000 port')
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In the above code, we can see an endpoint ‘/courses’, and the purpose of that endpoint is to get all the courses. &lt;/p&gt;

&lt;p&gt;Before it gets the course and sends the response, we need to check whether the user is logged in or not, and then if a user is logged in, we can move forward and get all the course and send back the response.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const app = express();
app.use(express.json());

const userAuthentication = (req, res, next) =&amp;gt; {
  //Let's assume you will write the logic for checking if a user is logged in.
  let isLogged;
  //islogged is a boolean value, and it will keep checking if a user is logged in or not
  if (!isLogged) {
    res.json({
      msg: "User is not logged in",
    });
  } else {
    next();
  }
};
app.get("/courses", userAuthentication, (req, res) =&amp;gt; {
  //write the logic of getting all courses
});

app.listen(3000, () =&amp;gt; {
  console.log("server is running on 3000 port");
});

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

&lt;/div&gt;



&lt;p&gt;middleware is nothing but a JS function, and it has three parameters &lt;/p&gt;

&lt;p&gt;1) req object&lt;br&gt;
2) res object&lt;br&gt;
3) next() —&amp;gt; The purpose of this method is to move the controller to the next middleware.&lt;/p&gt;

&lt;h3&gt;
  
  
  Execution Flow
&lt;/h3&gt;

&lt;p&gt;1) The user hits the endpoint ‘/courses’&lt;/p&gt;

&lt;p&gt;2) The controller will call the middleware userAuthentication&lt;/p&gt;

&lt;p&gt;3) userAuthentication will check if the user is logged in. if logged in, it will call the next(), and there is no more middleware; the controller will reach the end and get the courses. if not logged in, the user will get a response saying, “User is not logged in.”&lt;/p&gt;

&lt;p&gt;By leveraging middleware, you achieve:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Improved code readability and maintainability.&lt;/li&gt;
&lt;li&gt;Centralized handling of common tasks like authentication and validation.&lt;/li&gt;
&lt;li&gt;Modular architecture, facilitating easier debugging and testing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3jag372nqhqpaa8monlo.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3jag372nqhqpaa8monlo.gif" alt="Easy" width="498" height="498"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>node</category>
      <category>express</category>
    </item>
    <item>
      <title>Building a Robust HTTP Server with Node.js: A Step-by-Step Guide</title>
      <dc:creator>Tirth Raval</dc:creator>
      <pubDate>Fri, 05 Apr 2024 06:39:51 +0000</pubDate>
      <link>https://forem.com/tirthraval1999/building-a-robust-http-server-with-nodejs-a-step-by-step-guide-4nn6</link>
      <guid>https://forem.com/tirthraval1999/building-a-robust-http-server-with-nodejs-a-step-by-step-guide-4nn6</guid>
      <description>&lt;h4&gt;
  
  
  What is an HTTP server?
&lt;/h4&gt;

&lt;p&gt;HTTP server can be defined as software that can take clients' requests and deliver the web pages to the user as the response.&lt;/p&gt;

&lt;h4&gt;
  
  
  What is Node.js?
&lt;/h4&gt;

&lt;p&gt;Node.js is JavaScript run time which allows user to run JavaScript on their local machine. User can create their own HTTP server using different frameworks.&lt;/p&gt;

&lt;h4&gt;
  
  
  Why do we want to create the HTTP servers?
&lt;/h4&gt;

&lt;p&gt;The primary purpose of creating the HTTP servers is that, once we create the HTTP server, we want to expose it to the world so people can use it without worrying about the underlying concept.&lt;/p&gt;

&lt;p&gt;One good example I can think of is ChatGPT. If we ask ChatGPT anything, it will make some network calls and generate a response. As users, we do not have to worry about how ChatGPT generates the response.&lt;/p&gt;

&lt;h4&gt;
  
  
  How can we create the HTTP server using Node.js?
&lt;/h4&gt;

&lt;p&gt;Express.js is a framework that allows us to create HTTP servers using JavaScript as the programming language.&lt;/p&gt;

&lt;p&gt;Let us understand the status code before jumping into code.&lt;/p&gt;

&lt;h4&gt;
  
  
  What is the status code?
&lt;/h4&gt;

&lt;p&gt;It is a message that the server sends to the browser telling the status of the request.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Status Code&lt;/th&gt;
&lt;th&gt;Message&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;200&lt;/td&gt;
&lt;td&gt;The Request succussed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;404&lt;/td&gt;
&lt;td&gt;The Server can not find the resource&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;500&lt;/td&gt;
&lt;td&gt;Internal Server Error&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;For more details, visit:&lt;br&gt;
&lt;a href="https://dev.tourl"&gt; https://www.geeksforgeeks.org/10-most-common-http-status-codes/#&lt;/a&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Use&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Get&lt;/td&gt;
&lt;td&gt;To receive the data from the Database.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Post&lt;/td&gt;
&lt;td&gt;To add a new entry into the Database.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Put&lt;/td&gt;
&lt;td&gt;To update an entry in the Database.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Delete&lt;/td&gt;
&lt;td&gt;To delete an entry from the Database.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;For a better understanding of the types of requests, please visit: &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Let's make our own HTTP server using Express.js
&lt;/h4&gt;

&lt;h4&gt;
  
  
  Step 1: Initialize a new Node.js project.
&lt;/h4&gt;

&lt;p&gt;Write the below commands in your terminal&lt;br&gt;
&lt;code&gt;npm i&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 2: Install Express.js.
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;npm install express&lt;/code&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 3: Initialize the index.js
&lt;/h4&gt;



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

//we can create the different server based on the request

app.listen(3000, () =&amp;gt; {
console.log("Server is running on port 3000") 
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 5: Create your HTTP server based on the requests
&lt;/h4&gt;



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

//GET request handler
app.get('/api/resource', (req, res) =&amp;gt; {
    // Your logic for handling GET request
    res.send('GET request received');
});

// POST request handler
app.post('/api/resource', (req, res) =&amp;gt; {
    // Your logic for handling POST request
    res.send('POST request received');
});

// PUT request handler
app.put('/api/resource/:id', (req, res) =&amp;gt; {
    const resourceId = req.params.id;
    // Your logic for handling PUT request
    res.send(`PUT request received for resource with ID: ${resourceId}`);
});

// DELETE request handler
app.delete('/api/resource/:id', (req, res) =&amp;gt; {
    const resourceId = req.params.id;
    // Your logic for handling DELETE request
    res.send(`DELETE request received for resource with ID: ${resourceId}`);
});

app.listen(3000, () =&amp;gt; {
console.log("Server is running on port 3000") 
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;code&gt;req&lt;/code&gt;&lt;/strong&gt; stands for request and represents the HTTP request from the client to the server. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;res&lt;/code&gt;&lt;/strong&gt; stands for response and represents the HTTP response that the server sends back to the client.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6yg8podcus79633220d.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs6yg8podcus79633220d.gif" alt="Thank you Post" width="432" height="498"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>programming</category>
      <category>node</category>
      <category>express</category>
    </item>
  </channel>
</rss>
