<?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 Sahil Bisht on Medium]]></title>
        <description><![CDATA[Stories by Sahil Bisht on Medium]]></description>
        <link>https://medium.com/@codemaniac-sahil?source=rss-3ec3e9c464ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uTQTh13qux2T1O1AkQk_oQ.jpeg</url>
            <title>Stories by Sahil Bisht on Medium</title>
            <link>https://medium.com/@codemaniac-sahil?source=rss-3ec3e9c464ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:50:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codemaniac-sahil/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[Authentication in Node.js and MongoDB using JWT and Cookies]]></title>
            <link>https://medium.com/@codemaniac-sahil/authentication-in-nodejs-and-mongodb-using-jwt-and-cookies-d617bd98cdea?source=rss-3ec3e9c464ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/d617bd98cdea</guid>
            <dc:creator><![CDATA[Sahil Bisht]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 07:51:03 GMT</pubDate>
            <atom:updated>2025-06-06T11:47:47.006Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication is a critical aspect of web development, ensuring that only authorized users gain access to protected resources. In this blog, we will delve into the world of authentication in Node.js and storing the user’s credentials on MongoDB, focusing on the powerful combination of JWT(JSON Web Token) and cookies. By the end of this blog, you’ll have a solid understanding of how to implement secure user authentication in your Full-stack applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCIQXMbwLJj3JIvD2lyjuw.png" /></figure><h3>What is Authentication?</h3><p>Authentication is the process of verifying the identity of a user, system, or entity.<strong> </strong>The primary goal of authentication is to ensure that the entity trying to access a system or resource is who it claims to be.</p><h4>How is it different from authorization?</h4><p>Authorization is the process of granting or denying access to specific resources or actions based on the authenticated user’s privileges. The primary goal of authorization is to define the actions or resources a user is permitted to access after their identity has been confirmed through authentication.</p><h3>What is JWT(JSON Web Tokens)?</h3><p>It is a compact, URL-safe means of representing claims between two parties. The claims in a JWT are typically used to authenticate a user and provide additional information about them. JWTs are commonly used for authentication and information exchange in web development.</p><h4>Key Advantages of JWT:</h4><p>Stateless: JWTs are stateless, meaning the server doesn’t need to keep track of the user’s session. This is particularly advantageous for scalability.</p><p>Compact and Efficient: JWTs are compact and can be easily transmitted over the network, making them ideal for use in web applications.</p><p>Token-Based Authentication: JWTs are commonly used for token-based authentication, eliminating the need for continuous database queries during each request.</p><p>Versatility: JWTs can carry custom claims and information, providing developers with flexibility in designing authentication and authorization systems.</p><p>Security: JWTs can be signed to ensure the integrity of the token. They can also be encrypted to protect sensitive information within the token.</p><h3>Setting up a Node.js project</h3><h4>Initialize a New Node.js Project</h4><p>Open your terminal or command prompt and navigate to the directory where you want to create your Node.js project.</p><p>Run the following command to initialize a new Node.js project:</p><pre>mkdir user-authentication<br>cd user-authentication<br>npm init -y</pre><h4>Install Necessary Packages</h4><p>For this project, you’ll need to install these packages:</p><ol><li>Express: It is a popular web application framework for Node.js that simplifies the process of building robust, scalable, and secure web applications.</li><li>jsonwebtoken: A library for generating and verifying JSON Web Tokens (JWT).</li><li>cookie-parser: A middleware for parsing cookies</li><li>Bcrypt: A library for hashing passwords</li><li>Mongoose: It allows developers to write MongoDB queries in JavaScript syntax and provides a layer of abstraction between the application and the database.</li><li>Cors: It is used to enable secure cross-origin data transfers between a client (usually a web browser) and a server, particularly when the client and server are hosted on different domains.</li><li>body-parser: It helps to parse the incoming data that is being sent by the API call</li></ol><p>To install these packages, run the following command:</p><pre>npm install express jsonwebtoken cookie-parser bcrypt cors body-parser dotenv</pre><h4>Create Project Files</h4><p>Now, create an index.js file inside the working directory and copy or write this code (I prefer to write the code if you’re a beginner):</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br><br>const PORT = 8000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on PORT ${PORT}`);<br>});</pre><p>Run this code by using the node index.js command if it is showing this:</p><pre>Server is running on PORT 8000</pre><p>Then you have done the first step. If you encounter the error, try this again.</p><h3>Setting up MongoDB</h3><h4>Connecting to Database</h4><p>To connect the MongoDB to your Node.js environment, you need to create a folder. I am naming it by database, under this folder, you need to create the file db.js.</p><pre>const mongoose = require(&quot;mongoose&quot;);<br>const env = require(&quot;dotenv&quot;);<br><br>env.config();<br>const dbconnection = async () =&gt; {<br>  mongoose<br>    .connect(process.env.MONGODB_URL)<br>    .then(() =&gt; console.log(&quot;Database connected&quot;))<br>    .catch((err) =&gt; console.error(err));<br>};<br>module.exports = dbconnection;</pre><p>Now, you need to update the index.js file.</p><pre>const express= require(&quot;express&quot;);<br>const Connection=require(&quot;./database/db&quot;);<br><br>const app=express();<br><br>const PORT=8000;<br><br>Connection();<br><br>app.listen(PORT, () =&gt; {<br>     console.log(`server is running at port ${PORT}`);<br>});</pre><p>To check if you are connected to the database, write the npm start command on the command prompt. If it shows this output on the command prompt screen:</p><pre>The server is running at port 8000<br>Database connected</pre><p>Then it clearly shows that you successfully established the connection between your Node.js environment and MongoDB.</p><p>In case of any errors encountered, just go through the steps again.</p><h4>Building User Schema</h4><p>Now, our next step is to create the schema of the collection(The collection is the equivalent of a table in a relational database).</p><p>Create a folder named schema under this folder and create a file named Schema.js.</p><pre>const mongoose=require(&quot;mongoose&quot;);<br><br>const userSchema=mongoose.Schema({<br>      name:String,<br>      username:String,<br>      email:String,<br>      password:String,<br>})<br>const user=mongoose.model(&quot;user&quot;,userSchema);<br>module.exports=user;</pre><h3>Building Authentication</h3><h4>Token Generation</h4><p>Before we build the user registration, we first need to generate a token for the authentication.</p><p>Create a folder named tokenGeneration(you can name anything), under that create a file named generateToken.js.</p><p>Write or copy the code given :</p><pre>require(&quot;dotenv&quot;).config();<br>const jwt = require(&quot;jsonwebtoken&quot;);<br><br>module.exports.createSecretToken = (id) =&gt; {<br>  return jwt.sign({ id }, process.env.TOKEN_KEY, {<br>    expiresIn: 3 * 24 * 60 * 60,<br>  });<br>};</pre><h4>User Registration</h4><p>Now our next step is to create a function to create or register the user on our platform.</p><p>We need to create a folder named controller under which we will be creating a new file named signup.js.</p><p>Write or copy this code to create the signup.js</p><pre>const User = require(&quot;../database/model/user&quot;);<br><br>const { createSecretToken } = require(&quot;../tokenGeneration/generateToken&quot;);<br>const bcrypt = require(&quot;bcrypt&quot;);<br><br>const createUser = async (req, res) =&gt; {<br>  try {<br>    if (<br>      !(<br>        req.body.email &amp;&amp;<br>        req.body.password &amp;&amp;<br>        req.body.name &amp;&amp;<br>        req.body.username<br>      )<br>    ) {<br>      res.status(400).send(&quot;All input is required&quot;);<br>    }<br><br>    const oldUser = await User.findOne({ email: req.body.email });<br><br>    if (oldUser) {<br>      return res.status(409).send(&quot;User Already Exist. Please Login&quot;);<br>    }<br>    const salt = 10;<br>    const hashedPassword = await bcrypt.hash(req.body.password, salt);<br>    const newUser = new User({<br>      name: req.body.name,<br><br>      username: req.body.username,<br>      email: req.body.email,<br>      password: hashedPassword,<br>    });<br>    const user = await newUser.save();<br>    const token = createSecretToken(user._id);<br><br>    res.cookie(&quot;token&quot;, token, {<br>      path: &quot;/&quot;, // Cookie is accessible from all paths<br>      expires: new Date(Date.now() + 86400000), // Cookie expires in 1 day<br>      secure: true, // Cookie will only be sent over HTTPS<br>      httpOnly: true, // Cookie cannot be accessed via client-side scripts<br>      sameSite: &quot;None&quot;,<br>    });<br><br>    console.log(&quot;cookie set succesfully&quot;);<br><br>    res.json(user);<br>  } catch (error) {<br>    console.log(&quot;Gott an error&quot;, error);<br>  }<br>};<br>module.exports = createUser;</pre><h4>User login</h4><p>Now our next step is to create a function to log in and verify the user on our platform.</p><p>We need to create a folder named controller under which we will be creating a new file named login.js.</p><p>Write or copy this code to create the login.js</p><pre>const User = require(&quot;../database/model/user&quot;);<br>const bcrypt = require(&quot;bcrypt&quot;);<br><br>const env = require(&quot;dotenv&quot;);<br>const { createSecretToken } = require(&quot;../tokenGeneration/generateToken&quot;);<br><br>env.config();<br><br>const login = async (req, res) =&gt; {<br>  const { email, password } = req.body;<br>  if (!(email &amp;&amp; password)) {<br>    return res.status(400).json({ message: &quot;All input is required&quot; });<br>  }<br>  const user = await User.findOne({ email });<br>  if (!(user &amp;&amp; (await bcrypt.compare(password, user.password)))) {<br>    return res.status(404).json({ message: &quot;Invalid credentials&quot; });<br>  }<br>  const token = createSecretToken(user._id);<br>  res.cookie(&quot;token&quot;, token, {<br>    domain: process.env.frontend_url, // Set your domain here<br>    path: &quot;/&quot;, // Cookie is accessible from all paths<br>    expires: new Date(Date.now() + 86400000), // Cookie expires in 1 day<br>    secure: true, // Cookie will only be sent over HTTPS<br>    httpOnly: true, // Cookie cannot be accessed via client-side scripts<br>    sameSite: &quot;None&quot;,<br>  });<br><br>  res.json({ token });<br>};<br>module.exports = login;</pre><h3>Creating routes</h3><p>Now, create a folder named route under which we need to create a file named route.js.</p><p>This is the code, you can write or copy the code:</p><pre>const express = require(&quot;express&quot;);<br><br>const login = require(&quot;../controller/login&quot;);<br>const createUser = require(&quot;../controller/Signup&quot;);<br><br>const router = express.Router();<br><br>router.post(&quot;/signup&quot;, createUser);<br>router.post(&quot;/login&quot;, login);<br>router.get(&quot;/logout&quot;, (req, res) =&gt; {<br>  res.clearCookie(&quot;token&quot;);<br>  res.json({ message: &quot;Logged out&quot; });<br>});<br>module.exports = router;</pre><h4>Connecting these routes to the main file</h4><p>Now, to make these routes work, we need to update the main file, which is index.js like this:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const Connection = require(&quot;./database/Connection&quot;);<br>const PORT = 8000;<br>const authRoute = require(&quot;./routes/route&quot;);<br>Connection();<br>app.use(&quot;/api&quot;, authRoute); // Updated part<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on PORT ${PORT}`);<br>});</pre><h3>Errors in our code</h3><p>There are three main errors in our code:</p><ol><li>Body-parser error: We did not add the body-parser to our,, which will cause the error in which our code is not able to parse the JSON body data while calling the API.</li><li>Cookie-parser error: It is the same as the body-parser error, but the difference is that instead of JSON, it will not parse the cookie that we are sending while calling the API.</li><li>CORS error: I know you have encountered this error many times, and you fix this error by adding the CORS middleware, but when we are dealing with cookies, we need to make some small changes to the code.</li></ol><p>Now, to solve these errors, you need to update the index.js file like this:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const Connection = require(&quot;./database/Connection&quot;);<br>const PORT = 8000;<br>const authRoute = require(&quot;./routes/route&quot;);<br>Connection();<br>// updatd code<br>app.use(bodyParser.json({ extended: true }));<br>app.use(bodyParser.urlencoded({ extended: true }));<br>app.use(cookieParser());<br><br>app.use((req, res, next) =&gt; {<br>  // Set CORS headers<br>  res.header(&quot;Access-Control-Allow-Origin&quot;, process.env.FRONTEND_URL); // Replace with your frontend domain<br>  res.header(&quot;Access-Control-Allow-Methods&quot;, &quot;GET, POST, PUT, DELETE&quot;);<br>  res.header(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type, Authorization&quot;);<br>  res.header(&quot;Access-Control-Allow-Credentials&quot;, &quot;true&quot;); // Allow credentials (cookies, etc.)<br><br>  // Pass to next layer of middleware<br>  next();<br>});<br>app.use(&quot;/api&quot;, authRoute);<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on PORT ${PORT}`);<br>});</pre><p>Now, in this project, we have used many credentials that we don&#39;t want to expose to the public, and you have also seen in the code that I have written something like this process. envv.VARIABLE_NAME. This is called the setting of the environment variable. It is simple to create. You just need to make a file named .env and inside this file declare the variable that you don&#39;t want to expose to the public.Alsoo you need to install a package named dotenv by writing this:</p><pre>npm i dotenv</pre><p>Here is an example of the .env file</p><pre>TOKEN_KEY=abc@123<br>FRONTEND_URL=http://localhost:3000<br>MONGODB_URL=mongodb://localhost:27017/{YOUR_DATABASE_NAME}</pre><h3>Testing the APIs</h3><p>Here are the screenshots of the API test</p><p>Signup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1dx3xCWG0txFrwraRofDQ.png" /><figcaption>Testing Signup</figcaption></figure><p>Login</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWdBnbbO8XqK895ITHAP9Q.png" /><figcaption>Testing Login</figcaption></figure><p>Logout</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UW952-dbeTaOINllVZtSg.png" /><figcaption>Testing Logout</figcaption></figure><h3>Conclusion</h3><p>In conclusion, this blog has provided a comprehensive guide to implementing authentication in Node.js and MongoDB using JWT and cookies. Armed with this knowledge, developers can create secure, scalable, and user-friendly full-stack applications with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d617bd98cdea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Storing data in MongoDB through Node.JS]]></title>
            <link>https://medium.com/@codemaniac-sahil/storing-data-in-mongodb-through-node-js-61bccec987eb?source=rss-3ec3e9c464ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/61bccec987eb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sahil Bisht]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 09:39:27 GMT</pubDate>
            <atom:updated>2023-04-18T17:35:01.320Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, MongoDB has become one of the most popular NoSQL databases. Its flexibility and scalability have made it a preferred choice for storing data in modern web applications. In this blog, we will learn how to store data in MongoDB using Node.js.</p><p>Before starting the blog we first get to know about MongoDB and Node.Js.</p><h3><strong>What is MongoDB?</strong></h3><p>MongoDB is a popular open-source document-oriented NoSQL database that is designed to store and manage large volumes of unstructured or semi-structured data.</p><h3>What is Node.js?</h3><p>Node.js is an open-source, cross-platform, JavaScript runtime environment allowing developers to run JavaScript code outside a web browser.</p><h3>Creating a Node.js project</h3><p>The first step is to initialize your app and for that, you have to write the <strong>npm init</strong> command on your command prompt.</p><pre>mkdir node-mongo<br>cd node-mongo<br>npm init</pre><p>It will generate two files named package.json and package-lock.json, you don’t have to do anything with these files as these files are very important for the installation process.</p><p>Now, you have to install 2 dependencies:</p><ol><li>Express: It is a popular web application framework for Node.js that simplifies the process of building robust, scalable, and secure web applications.</li><li>Mongoose: It allows developers to write MongoDB queries in JavaScript syntax and provides a layer of abstraction between the application and the database.</li></ol><p>You can install these dependencies by writing <strong>npm i express mongoose cors body-parser </strong>on the command prompt in the same directory in which you are working.</p><pre>npm i express mongoose</pre><p>Now, create a file named index.js and copy this code:</p><pre>import express from &quot;express&quot;;<br><br>const app = express();<br>const PORT = 8000;<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`The server is running at port ${PORT}`);<br>});</pre><h3>Connecting to database</h3><p>For connecting the MongoDB to your node.js environment you need to create a folder here I am naming it by database, under this folder you need to create the file db.js.</p><pre>import mongoose from &quot;mongoose&quot;;<br><br>const Connection = async () =&gt; {<br>  mongoose.set(&quot;strictQuery&quot;, false);<br> <br>  const URL = `mongodb://localhost:27017/{YOUR_DATABASE_NAME}`<br>  try {<br>    await mongoose.connect(URL, {<br>      useUnifiedTopology: true,<br>      useNewUrlParser: true,<br>    });<br>    console.log(&quot;Database connected&quot;);<br>  } catch (error) {<br>    console.log(&quot;you got this &quot;, error);<br>  }<br>};<br>export default Connection;<br></pre><p>Now, you need to update your index.js like this:</p><pre>import express from &quot;express&quot;;<br>import Connection from &quot;./database/db.js&quot;;<br>import Routes from &quot;./routes/route.js&quot;;<br>	<br><br>const app = express();<br>const PORT = 8000;<br>	<br>app.use(&quot;/&quot;, Routes);<br>	<br>Connection();<br>app.listen(PORT, () =&gt; {<br>     console.log(`server is running at port ${PORT}`);<br>});<br><br></pre><p>To check if you are connected to the database, write the npm start command on the command prompt. If it shows this output on the command prompt screen:</p><pre>The server is running at port 8000<br>Database connected</pre><p>Then it clearly shows that you successfully established the connection between your node.js environment and MongoDB.</p><p>In case of any error encounters, just go through the steps again.</p><h3>Creating Schema</h3><p>Now, our next step is to create the schema of the collection(The collection is the equivalent of a table in a relational database).</p><p>Create a folder named schema under this folder and create a file named Schema.js.</p><pre>import mongoose from &quot;mongoose&quot;;<br>	<br><br>const userSchema = mongoose.Schema({<br>      name: String,<br>      username: String,<br>      email: String,<br>      phone: String,<br>});<br>const user = mongoose.model(&quot;user&quot;, userSchema);<br>export default user;<br><br></pre><h3>Creating APIs</h3><p>Now, the next step is to create APIs in order to store data in Mongodb through Nodejs.</p><p>Create a folder named routes inside this folder create a file named route.js. In this file, you are going to define the APIs that we will be using to store data.</p><pre>import express from &quot;express&quot;;<br>import User from &quot;../schema/user-schema.js&quot;;<br><br><br>const router = express.Router();<br><br>router.post(&quot;/add&quot;, async (req, res) =&gt; {<br>  const user = req.body;<br>  const newUser = new User(user);<br>  try {<br>    await newUser.save();<br>    res.status(201).json(newUser);<br>  } catch {<br>    res.status(409).json({ message: error.message });<br>  }<br>});<br>router.get(&quot;/all&quot;, async (req, res) =&gt; {<br>  try {<br>    const users = await User.find({});<br>    res.status(200).json(users);<br>  } catch (error) {<br>    res.status(404).json({ message: error.message });<br>  }<br>});<br>router.put(&quot;/:id&quot;, async (req, res) =&gt; {<br>  let user = req.body;<br>  const editUser = new User(user);<br>  try {<br>    await User.updateOne({ _id: req.params.id }, editUser);<br>    res.status(201).json(editUser);<br>  } catch (error) {<br>    res.status(409).json({ message: error.message });<br>  }<br>});<br>router.delete(&quot;/:id&quot;,  async (req, res) =&gt; {<br>  try {<br>    await User.deleteOne({ _id: req.params.id });<br>    res.status(200).json({ message: &quot;User deleted Successfully&quot; });<br>  } catch (error) {<br>    console.log(error);<br>  }<br>});<br><br></pre><h3>Testing APIs</h3><p>For this blog, I’ll be using Thunder client for testing the API as it is easy to install and easy to execute the APIs. You just need to install its extension on the visual studio code.</p><p>This is how you can test your API on the Thunder client:</p><ol><li>Post</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K39JeNWOW0W64ZeqS48HMw.png" /></figure><p>2. Get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YssufP9aVFqth8SVnrrzjg.png" /></figure><p>3. Delete</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ih0CqOghLhLXcUuDzZA56A.png" /></figure><h3>Conclusion</h3><p>In this blog, we learned how to perform CRUD operations in MongoDB with the help of RESTful API created using Nodejs. With this knowledge, you should be able to build more complex applications using MongoDB as your data store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61bccec987eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>