<?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 Purti Aggarwal on Medium]]></title>
        <description><![CDATA[Stories by Purti Aggarwal on Medium]]></description>
        <link>https://medium.com/@purtiAggarwal?source=rss-dd88e0dbf640------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3udtFzYj-1RmTL7e</url>
            <title>Stories by Purti Aggarwal on Medium</title>
            <link>https://medium.com/@purtiAggarwal?source=rss-dd88e0dbf640------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:00:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@purtiAggarwal/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[Registration And Login With JWT Using NodeJs & ExpressJs]]></title>
            <link>https://medium.com/aeologic/registration-and-login-with-jwt-using-nodejs-expressjs-257ec33baf1f?source=rss-dd88e0dbf640------2</link>
            <guid isPermaLink="false">https://medium.com/p/257ec33baf1f</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 13:34:34 GMT</pubDate>
            <atom:updated>2020-07-05T13:34:34.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ABvBg3tBCDdK1-KF.png" /></figure><p><em>JWT provides a perfect system for issuing and validating authentication tokens. The authentication token will ensure that the client doesn’t need to log in every time they want to operate on the serve.</em></p><p>The JWT is separated into three parts by dot(.) which are</p><ol><li><strong>Header</strong>: <em>The header has two parts: First the type of token, which is JWT, Second the singing algorithm which is being used.</em></li><li><strong>Payload</strong>: <em>The payload consists of the user data. The data means the ‘claims’ of the JWT. The data saved as a JSON object.</em></li><li><strong>Signature</strong>: <em>The signature consist of the secret code which is hashed with the header and the payload. This is used to verify the authenticate the token.</em></li></ol><h3>Let’s start building the project</h3><h4>Step-1: Set up the directories</h4><p>First, create the base folder(application) which contains all project-related directories. Now create the src folder which contains the server-side specific file.</p><blockquote><strong>Check out my </strong><a href="https://medium.com/@purtiaggarwal1997/57b90b928b9"><strong>previous blog</strong></a><strong> on how to setup a project from scratch.</strong></blockquote><p>Inside the src folder create new folders — <strong>controller</strong>, <strong>DB</strong>, <strong>middleware</strong>, <strong>models </strong>&amp; <strong>router</strong>.</p><p>Now the directory structure will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKcS5ag651lMO4t0XgMDjg.png" /></figure><h4>Step-2: Setting up package.json file</h4><p>We need to setup <strong>package.json</strong> file by running below command in the terminal inside application directory:</p><pre>$ npm init -y</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJMENtnncT3ImYj7f82fBA.png" /></figure><blockquote><strong>npm init -y command </strong>will take default configuration like description, name and other config.</blockquote><blockquote>If you want to provide custom configuration use <strong>npm init </strong>and it will ask you to enter all the details manually.</blockquote><h4>Step-3: Installing the modules.</h4><pre>$ npm i express mongoose mongodb jsonwebtoken bcryptjs validator body-parser</pre><ol><li><strong>Express:</strong> Express is used as a web application framework.</li><li><strong>Mongoose: </strong>The mongoose is used to connect the database with our project.</li><li><strong>Jsonwebtoken:</strong> Jsonwebtoken is used for Authentication and Authorization.</li><li><strong>Bcryptjs: </strong>Bcryptjs is used to hash and compare the password.</li><li><strong>MongoDB: </strong>MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need</li><li><strong>Validator: </strong>This library validates and sanitizes strings only.</li><li><strong>Body-parser: </strong>Extract the entire body portion of an incoming request stream and exposes it on req.body.</li></ol><p>Here’s how our package.json will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZ6OXz889dkuDIZfAzPinQ.png" /><figcaption>package.json file</figcaption></figure><h4>Step-4: Configure the DataBase</h4><p>First, we have to create a file ./src/db/mongoose.js under the root project.</p><p>Second, import the mongoose module in the file.</p><pre>const mongoose = require(&#39;mongoose&#39;)</pre><p>Third, declare the MongoDB URL for the connection</p><pre>...<br>const MONGO_URL = mongodb://127.0.0.1:27017/app</pre><p>Above <strong>127.0.0.1:27017</strong> is the localhost server and the <strong>app</strong> is the database name.</p><p>Fourth, and the last step to connect with the database.</p><pre>...<br>mongoose.connect(MONGO_URL, () =&gt; { <br>      console.log(&#39;Database is connected!&#39;)<br>}</pre><p><strong>Step-4: Creating the model</strong></p><p>First, create a new file inside ./src/models/user.js &amp; import the required modules:</p><pre>const mongoose = require(&#39;mongoose&#39;)<br>const validator = require(&#39;validator&#39;)</pre><p>Second, now we will create the user’s schema (Schema defines the structure of the data).</p><pre>// Defining User collection schema structure.<br>// We have name, email, password field.</pre><pre>const userSchema = mongoose.Schema({<br>      name: {<br>        type: String,<br>        require: true,<br>        trim: true<br>      },<br>     email: {<br>        type: String,<br>        required: true,<br>        trim: true,<br>        lowercase: true,<br>        unique: true,<br>        validate(value){<br>            if(!validator.isEmail(value)){<br>                 throw new Error(&#39;Email is invalid&#39;)<br>              }<br>         }<br>     },<br>     password: {<br>       type: String,<br>       required: true,<br>       trim: true,<br>       minlength: 7,<br>       validate(value){<br>           if(value.toLowerCase().includes(&#39;password&#39;)){<br>               throw new Error(&#39;Password cannot contain &quot;Password&quot;&#39;)<br>           }<br>        }<br>    }<br>    <br>})</pre><pre>const User = mongoose.model(&#39;User&#39;, userSchema)<br>module.exports = User</pre><p>Now, we have to hash the password for security reasons before saving the password in the database.</p><pre>...<br>const bcrypt = require(&#39;bcryptjs&#39;);</pre><pre>// This function will be called before user object get saved in the Users collection. It will simply hash the plain text passord if it is modified by the user.</pre><pre>userSchema.pre(&#39;save&#39;, async function(next) {<br>      const user = this</pre><pre>// It will check if the password is being modified or not.<br>      if(user.isModified(&#39;password&#39;)) {<br>          user.password = await bcrypt.hash(user.password, 8)<br>      }<br>      next()<br>)}<br>...</pre><blockquote>pre is used when we have to perform any task before saving, updating, delating or fetching the document from any collection.</blockquote><p>Now we integrating the JWT into our application. The generateAuthToken method is responsible for generating the token. This method will be called when the user signs up and sign in.</p><pre>...<br>const jwt = require(&#39;jsonwebtoken&#39;)</pre><pre>userSchema.methods.generateAuthToken = async function () {<br>     const user = this<br>     const token = jwt.sign({_id: user._id.toString() }, &#39;thesecretcode&#39;)<br>     user.tokens = user.tokens.concat({ token })<br>     await user.save()<br>     return token<br>}<br>...</pre><p><em>Note: “thesecretcode ”used in above for signing the token will be the private key and you need to generate a unique key for different projects.</em></p><p>Now we have to store the token in the database for the user who signing or registered.</p><pre>// other property of model, you need to add this property in User Schema for storing the multiple token for each user.</pre><pre>...<br>tokens: [{<br>        token: {<br>            type: String,<br>            required: true<br>        }<br>    }]<br>...</pre><h3><em>REGISTRATION API</em></h3><p>First, we are going to route and test the registration API.</p><h4>Step-5: Route the request</h4><p>The router is used to define the interaction with APIs and used to send and receive the requests from the server.</p><p>First, we create the file ./src/router/userRouter.js</p><p>Now we have to route the request</p><pre>const express = require(&#39;express&#39;)<br>const AuthController = require(&#39;../controller/authController&#39;)</pre><pre>const router = express.Router()</pre><pre>//Signup request<br>router.post(&#39;/signup&#39;, AuthController.registration)</pre><pre>modue.exports = router</pre><p>A router is supposed to forward the request to the appropriate controller function. So, our next step is to create the controller.</p><h4><strong>Step-6: Creating Controller</strong></h4><p>Now we are going to create a controller which helps in getting the requested data from the model.</p><p>Create the directory ./src/controller/userController.js</p><p>First, we create the controller for user signup and the sign in.</p><pre>const User = require(&#39;../modeld/user&#39;)</pre><pre>class AuthController {<br>     static registration= async (req, res) =&gt; {<br>         const user = new User(req.body) <br>         try {<br>             await user.save()<br>             res.status(200).send({<br>                      status: 200,<br>                      message: &#39;Successfully Registered&#39;,<br>                      userData: user<br>              })<br>          } catch (error) {<br>                  res.status(400).send({<br>                      status: 400,<br>                      message: error.message<br>                  })<br>          }<br>      }</pre><h4><strong>Step-7: Create the Index.js</strong></h4><p>Now we going to create the main file of our project that is the index.js</p><p>We have to require all files in index.js because it handles our application startups and all other functions.</p><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br>const userRouter = require(&#39;./router/userRouter&#39;)<br>require(&#39;./db/mongoose&#39;)</pre><pre>const app = express()<br> <br>app.use(bodyParser.json())<br>app.use(bodyParser.urlencoded({extended: true})</pre><pre>app.use(userRouter)</pre><pre>const port = process.env.PORT || 3000</pre><pre>app.listen(port, ()=&gt; {<br>    console.log(&#39;Server is up to &#39;+ port)<br>})</pre><h4>Test Registration API</h4><p>We have to send the data in the JSON form through the JSON body of the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*OsT23mvBeEtG3HvwoIjoyA.png" /><figcaption>Send Registration API Data</figcaption></figure><p>If your code correctly then you will get the status 200 OK and the result as follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*QnXHugnVGlw9DYrt7CC42w.png" /><figcaption>Result of Registration API</figcaption></figure><h3>LOGIN API</h3><p>For Login, we already have a model of the user now just we have to find the credentials in the database if credentials it exists you will get 200 OK status or not then you will get 404 Not Found.</p><p>So we have to make the function for finding the credentials in the model i.e, user.js.</p><pre>...<br>userSchema.statics.findByCredentials = async (email, password) =&gt; {<br>       const user = await User.findOne ({ email })<br>       if(!user) {<br>           throw new Error(&#39;Unable to Signin&#39;)<br>       }<br>       const isMatch = await bcrypt.compare(password, user.password)<br>       if(!isMatch) {<br>            throw new Error(&#39;Unable to Signin&#39;)<br>       }<br>       return user<br>}<br>...</pre><h4><strong>Step-8: Creating Controller</strong></h4><p>We are creating the controller for user sign in.</p><pre>...<br>     <br>     static signin = async (req, res) =&gt; {<br>         try{<br>           //find the credentials from the database<br>           const user = await User.fendByCredentials(req.body.email , req.body.password)<br>           //generate a token <br>           const token = await user.generateAuthToken()<br>           res.status(200).send({<br>               status: 200,<br>               message: &#39;Successfully Signin&#39;<br>               data: {<br>                  userData: user, token <br>               }<br>           })<br>        }catch(error) {<br>            res.status(400).send({<br>                status: 400,<br>                message: error.message<br>            })<br>        }<br>     }<br>...</pre><h4><strong>Step-9: Create the router</strong></h4><p>Now, route the request for the sign in.</p><pre>...</pre><pre>router.post(&#39;/signin&#39;, AuthController.signin)</pre><pre>...</pre><h4>Test Login API</h4><p>We have to send the credentials in the JSON form through the JSON body of the postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*PyWSHLVFhNdUe4KtYUJT_w.png" /><figcaption>Send Sign-in Request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*75sjPX0kWrBTKwqGjt8LFg.png" /><figcaption>Result of Sign-in API</figcaption></figure><h4>Summary</h4><p>In this blog, we learned about JWT. JWT is a standard that defines a compact and self-contained way to securely transmit information between a client and a server as a JSON object. In this blog, we made the registration and the login REST API. Here we did the basic validation as well keeping in mind to hash the password before saving in the database. Also integrated the function for the JWT authentication.</p><p>In my next blog, we will learn how to upload single and multiple images and save them in the database. Hopefully, this article helps you with Registration And Login With JWT Using NodeJs &amp; ExpressJs. <br>For the reference of the above code <a href="https://github.com/purtiAggarwal123/registration-and-login-with-jwt-authentication.git">https://github.com/purtiAggarwal123/registration-and-login-with-jwt-authentication.git</a></p><p>Feel free to connect with us read more articles from <a href="http://www.aeologic.com/">Aeologic.com</a>.</p><p><a href="http://www.aeologic.com/"><strong>Aeologic Technologies</strong></a> is a dynamic, solution, and value-driven technology company. We position ourselves as a new generation cutting edge technology company. We work creatively to enable businesses with leading technologies and solutions. You can connect with us on <a href="https://www.facebook.com/AeoLogicTech/">Facebook</a>, <a href="https://twitter.com/aeologictech">Twitter</a>, and <a href="https://www.linkedin.com/company/aeologic-technologies/">LinkedIn </a>for any queries.</p><figure><a href="https://www.aeologic.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GM5-_fTVNgVFfWJznrY2cg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=257ec33baf1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aeologic/registration-and-login-with-jwt-using-nodejs-expressjs-257ec33baf1f">Registration And Login With JWT Using NodeJs &amp; ExpressJs</a> was originally published in <a href="https://medium.com/aeologic">Aeologic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with NodeJs]]></title>
            <link>https://medium.com/aeologic/getting-started-with-nodejs-10e6180aea96?source=rss-dd88e0dbf640------2</link>
            <guid isPermaLink="false">https://medium.com/p/10e6180aea96</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Purti Aggarwal]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 16:39:06 GMT</pubDate>
            <atom:updated>2020-06-22T07:51:35.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FkEFhvtHjNqZThy2.png" /></figure><p>NodeJs came about when the developer took javascript something that at that point we could only run in the browser and they allowed it to run as a standalone process on your machine. So before NodeJs javascript just was used as a more general-purpose programming language. With the help of the NodeJs now Javascript could build the web-server and connect the application to the database.</p><p>In this blog, we will cover the following areas of NodeJS:</p><ol><li>Introduction of <strong>NodeJS</strong>.</li><li>Installation of NodeJS and <strong>NPM</strong>.</li><li>Installation of <strong>VS Code</strong>.</li><li>Basic project setup with <strong>express</strong>.</li><li>“<strong>Hello World</strong>” with NodeJs</li></ol><h3>What is NodeJs?</h3><p>NodeJs is a free open source server that allows us to run Javascript on the server. With the help of NodeJs, we can create, open, read, write, delete, and close files on the server. We can generate dynamic websites and add delete our data from the database.</p><p>For developing a NodeJs application we require the following tools.</p><ol><li>NodeJs</li><li>Node Package Manager (NPM)</li><li>IDE (Integrated Development Environment) or TextEditor</li></ol><p>The Modules in NodeJs have simple or complex functionalities all are organized in single or multiple Js files which can be reused in the NodeJs application project.</p><p>Each module in NodeJs has its different context, so it cannot interfere with other modules or pollute the global scope.</p><h3>NodeJs Module Types:</h3><p>NodeJs includes three types of modules:</p><h4>1. Core Modules:</h4><p><em>The Core Modules are those modules that coded into the binary distribution and loaded whenever the NodeJs process starts. However, we need to import the module to use the module in your application.</em></p><h4>2. Local Modules:</h4><p><em>The Local Modules are those modules that we create locally for the application project. In other words, we can say the different functions that we created for the different functions of the application project.</em></p><h4>3. Third-Party Modules:</h4><p><em>The Third-Party Modules are those modules that can be downloaded through the npm. These modules are created by someone else but we can use it in our project.</em></p><h3>Let’s start building the project.</h3><h4>Step-1: Download the required tools</h4><p>First, we download the NodeJs from the given link <a href="https://nodejs.org/en/">https://nodejs.org/en/</a></p><p>For making sure that NodeJs downloaded correctly, for that open terminal or CMD and run the node -v command as below.</p><pre>$ node -v<br>v13.12.0</pre><p>It will show the version of the NodeJs installed. If you are not getting this it means you didn’t download the tool correctly.</p><p>NPM is included in NodeJs installation, so there is no need to install it separately.</p><p>Second, we need to download the Texteditor tool where we write our code.</p><p>We use the Visual Studio code editor. So download the editor from the given link <a href="https://code.visualstudio.com/download"><em>https://code.visualstudio.com/download</em></a></p><h4>Step-2: Creating the directory</h4><p>First, we have to make the base folder in which we have all the project related directories. An example we made the application folder.</p><p>Second, now we make the src(source) folder. This folder contains the server-side specific files. Inside the src folder create a new file index.js that will be the entry page for the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9izKUGcMPkCjfO5cl1fNtw.png" /><figcaption>File Structure</figcaption></figure><h4>Step-3: Installing the express module</h4><p>To use NodeJs NPM modules, you first to install the module in the terminal using below command</p><pre>$ npm i express</pre><p>Here we install the Express Module.</p><h4>Step-4: Import the Module</h4><p>Now we have to load the module in our project (index.js file).</p><pre>const express = require(&#39;express&#39;);</pre><pre>const app = express();</pre><p>In the above example, require() function returns object because the express module returns its functionality as an object.</p><h4>Step-5: Listen to the Port</h4><p>Now we have to bind and listen for connections on the specified host and port.</p><p>First, we have to declare the port inside the index.js file.</p><pre>...<br>const port = process.env.PORT || 3000</pre><p>In the above, we set the environment variable PORT or the port will be 3000.</p><p>Second, we have to listen to the port that should be declared at the end of the page with the callback the function to console the statement.</p><pre>...<br>app.listen(port, () =&gt; {<br>     console.log(&#39;Server is up to &#39; + port)<br>}</pre><h4>Step-6: Route the request</h4><p>Now we send the request to the server</p><p>We are using the app object with the callback function which is called whenever the server receives the request</p><pre>...<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>     req.send(&#39;Hello World&#39;);<br>}<br>...</pre><p><strong>Step-7: Final Step</strong></p><p>Run the command in the terminal.</p><pre>$ node index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K97H4IOV7geikR2YgZpzig.png" /><figcaption>The result after the server is up</figcaption></figure><p>You will see the application is served on localhost on port 3000 and it is returning “Hello World”.</p><h3>Summary</h3><p>In this blog, we learned about NodeJs and it’s the express framework. First, we have set up the file structure then we see the module installation and how to route the request to the server. NodeJs has owns a huge world. We can do many things with NodeJs like make the Authenticate the website. The dataBase can be linked to the backend where we can save the data of the registered users and many other things. Hopefully, this article helps you with getting started with the NodeJs.</p><h4>For more learning, you should go through the link <a href="https://nodejs.org/docs/latest-v13.x/api/synopsis.html"><em>https://nodejs.org/docs/latest-v13.x/api/synopsis.html</em></a></h4><p>Feel free to connect with us read more articles from <a href="http://www.aeologic.com/">Aeologic.com</a>.</p><p><a href="http://www.aeologic.com/"><strong>Aeologic Technologies</strong></a> is a dynamic, solution, and value driven technology company. We position ourselves as a new generation cutting edge technology company. We work creatively to enable businesses with leading technologies and solutions. You can connect with us on <a href="https://www.facebook.com/AeoLogicTech/">Facebook</a>, <a href="https://twitter.com/aeologictech">Twitter</a>, and <a href="https://www.linkedin.com/company/aeologic-technologies/">LinkedIn </a>for any queries.</p><figure><a href="http://www.aeologic.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GM5-_fTVNgVFfWJznrY2cg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10e6180aea96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aeologic/getting-started-with-nodejs-10e6180aea96">Getting started with NodeJs</a> was originally published in <a href="https://medium.com/aeologic">Aeologic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>