<?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 Deepansh Makkar on Medium]]></title>
        <description><![CDATA[Stories by Deepansh Makkar on Medium]]></description>
        <link>https://medium.com/@makkardeepansh?source=rss-51cd8d279cd8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mgUiCW3LRWhYILgS6klmqQ.jpeg</url>
            <title>Stories by Deepansh Makkar on Medium</title>
            <link>https://medium.com/@makkardeepansh?source=rss-51cd8d279cd8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:29:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@makkardeepansh/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[Create NodeJS Server for a Real-Time Quiz App]]></title>
            <link>https://makkardeepansh.medium.com/create-nodejs-server-for-a-real-time-quiz-app-92feac80c458?source=rss-51cd8d279cd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/92feac80c458</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Deepansh Makkar]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 06:57:23 GMT</pubDate>
            <atom:updated>2021-06-04T07:01:13.209Z</atom:updated>
            <content:encoded><![CDATA[<p>Build a quiz app server using NodeJS in less than 10 minutes!</p><figure><img alt="nodejs" src="https://cdn-images-1.medium.com/max/1024/1*AYoRr9oEPzZb6Lfpoy-yRQ.png" /></figure><blockquote>“You can never understand everything. But, you should push yourself to understand the system.” — Ryan Dahl (Creator of NodeJS)</blockquote><h4><strong>In this article, we’re going to build a server for a real-time quiz app using the following technologies:</strong></h4><ul><li>ExpressJS</li><li>Socket.io</li><li>MongoDB</li><li>Mongoose</li></ul><p>If you have a fundamental knowledge of these technologies and want to use them to create something awesome, then this article is for you!</p><p>You can view the <a href="https://github.com/iamakkar/Back-end">source code</a> for your reference from my Github.</p><h3>Setup the Development Environment</h3><ol><li>Install the latest NodeJS for your operating system from <a href="https://nodejs.org/en/download/">here</a>.</li><li>Let us check whether it is installed properly or not. Open your terminal/command prompt and type node -v and npm -v . If you get something similar to this, then congratulations! NodeJS has been installed successfully.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pjra-suPoYWrXMFG_0FrFQ.png" /></figure><h3>Creating the Project</h3><ol><li>Open your Terminal/Command prompt and change your directory to where you want to store the project by doing cd path/to/the/directory .</li><li>Create a new NodeJS project using the following command npm init .</li><li>After filling all the details, you’ll see that a package.json file is created. This file contains list of all the dependencies installed and all metadata information about your Node JS Project.</li><li>Let us install the dependencies that we will be using in our project.</li></ol><pre>npm install express mongoose socket.io body-parser cors jsonwebtoken --save</pre><p>It will create a new folder node_modules which contains the data of dependencies. Check your package.json file, it will show the list of dependencies along with their versions.</p><h3>Running you Server</h3><p>Remember while creating the project, we set the entry point named <em>index.js</em>. Create a new javascript file and name it index.js . This file will be responsible for running server. Now let us write some code in the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba82cc245d1178b399a203b58c1b4723/href">https://medium.com/media/ba82cc245d1178b399a203b58c1b4723/href</a></iframe><p>Body-parser parses the incoming request bodies and cors is used for cross-origin resource sharing. You can learn more on it <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">here</a>.</p><p>We have set the port for our server as 3000. To run the server, cd to the project folder and run node index. You’ll see “server running on port 3000” written on your console. You have set your server up and running!</p><h3>Structuring our Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vac1PRWfzTHhSfkQUmisIg.png" /><figcaption>Full operation of our app</figcaption></figure><p>A request, for example <em>“/api/createaccount”</em> will be initiated from the client. When it reaches the server, our server performs the action which is associated with this request using a callback function. In this case, it will send the data to the Users model in the database and create a new user. It is an example of a post request.</p><p>We’ll divide our project into 2 parts:</p><ul><li><strong>Models:</strong> This will store our data in JSON format in the database.</li><li><strong>Routes:</strong> This will contain all the requests and their callback functions i.e. actions performed through it.</li></ul><p>Create 2 folders in project directory and name them Models and Routes .</p><h3>Creating Models</h3><p>Model is basically a set of parameters that defines what is our data. In this case, our model is a JSON. Create a Users.js file in models folder. We will use the following snippet for creating our User model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/569f11a210699be53c2c7ba30d380b64/href">https://medium.com/media/569f11a210699be53c2c7ba30d380b64/href</a></iframe><p>In the above snippet, we have a user schema which contains details that form a user. Below(line 50–64) is a method to compare entered password with the original password. It will be used further when we’ll setup authentication.</p><p><strong>Note:</strong> In Line no. 54, I’ve used bcrypt’s function because I’ve hashed my passwords with bcrypt. It’s not necessary to hash passwords. You can simply just compare the enteredPassword with user.password:</p><pre>if(enteredPassword != user.password) return reject({&quot;error&quot;: &quot;Password doesn&#39;t match&quot;});<br>return resolve(true);</pre><p>Similarly, we have our questions model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0484e967e89e215b050e7d5a23226022/href">https://medium.com/media/0484e967e89e215b050e7d5a23226022/href</a></iframe><h3>Creating Routes:</h3><p>We’ll only create routes for authentication, creating account and displaying user data. Create a userRoutes.js file in routes folder. Now lets add some code in it:</p><p>Import the required modules:</p><pre>const express = require(&quot;express&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>const jwt = require(&quot;jsonwebtoken&quot;);</pre><p>Initialise an express router to create requests and a User model to perform CRUD operations in the DB. Export the router at last:</p><pre>const router = express.Router();<br>const User = mongoose.model(&quot;User&quot;);</pre><pre>//All your requests</pre><pre>module.exports = router;</pre><p>While writing any request, we should keep track of the following things:</p><ul><li><strong>Request name:</strong> It is a string that acts as a unique identifier for the client.</li><li><strong>Callback Function: </strong>This function is triggered whenever the request is called from the client. A basic function have two main parameters <em>req </em>and<em> res. Req </em>contains data received from the client, headers, etc. and <em>Res</em> is the object that is to be sent to the client as a response. <em>Res </em>may contain data, status code, etc.</li></ul><p>An ideal post request in NodeJS looks like:</p><pre>router.post(&quot;/api/&lt;request_name&gt;&quot;, (req, res) =&gt; {</pre><pre>//your code here<br>});</pre><p>The below snippet are the requests we will be using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8acbab21833a5f8f6e5164645ecd5bea/href">https://medium.com/media/8acbab21833a5f8f6e5164645ecd5bea/href</a></iframe><p><strong>Note:</strong> I’ve sent a JSON Web Token after signin and signup. This is a proof of authentication for the client and is valid for whatever time you set. I will not discuss it here, but you can always <a href="https://www.npmjs.com/package/jsonwebtoken">learn it</a>.</p><p>Import and use these routes in Index.js :</p><pre>var userRoutes = require(&quot;./Routes/userRoutes.js&quot;);<br>app.use(userRoutes);</pre><h3>Implementing Socket Communication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*obJohCdYojTxJdBwW9fsCQ.png" /><figcaption>credits: <a href="https://www.geeksforgeeks.org/">https://www.geeksforgeeks.org</a></figcaption></figure><p>Web Sockets are used to create a real-time bidirectional event-based communication. It is superfast and works on every browser and device. Mostly, sockets are used in chating apps, gambling apps, games, etc. We will create a functionality for a user to invite any other user(provided the latter is online) for a match. We’ll also show their respective scores to both of them after the match.</p><p><strong>Note: </strong>Sockets will be used in the server as well as the client.</p><p>In Index.js, initialise the socket protocol:</p><pre>const io = require(&quot;socket.io&quot;).listen(server);</pre><p>We’ll now create a socket for every event. An socket in server API looks like this:</p><pre>io.on(&quot;connection&quot;, (socket) =&gt; {<br>//all the sockets</pre><pre>socket.on(&quot;&lt;event_name&gt;&quot;, (data) =&gt; {<br>//callback function<br>})<br>}</pre><p>The question is how to make it bidirectional. We’ll use a socket.io function to receive data from one socket, send any event’s socket to other client, and transfer the data. It is written as:</p><pre>io.to(&lt;socket_id&gt;).emit(&quot;&lt;event_name&gt;&quot;,data); </pre><p>A socket id is a unique string which is generated every time a socket connection is initialised. For example, if I want to play with “Jason”, I’ll find his updated socket id from the database and emit an “invite” socket to it.</p><p>The socket’s we’re using are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/793f7bed9e590fff6223e586c8025f0a/href">https://medium.com/media/793f7bed9e590fff6223e586c8025f0a/href</a></iframe><p>Whenever an invite socket is emitted, the other user has 2 choices: either accept or reject. When accepted, 5 questions of the respective topic are chosen from the DB randomly and sent to both the users.</p><p>After the match, both scores are sent to both the clients. They are compared there and respective sockets are emitted where user’s coins and streak are changed on the basis of whether he wins or loses.</p><h3>Deploying our Server on Web</h3><blockquote>“We’re in the endgame now” — Dr. Stephen Strange</blockquote><ul><li><strong>Deploying DB:</strong> I’ve used free tier of MongoDB atlas to deploy my database. You can follow these <a href="https://docs.atlas.mongodb.com/getting-started/">simple steps</a> to deploy yours.</li></ul><p>You’ll get a connection string for your MongoDB cluster. To connect it to server, go to index.js and just before running the server, write:</p><pre>mongoose.connect(&lt;connection_string&gt;, {  <br>useNewUrlParser: true, <br>useUnifiedTopology: true,<br>});</pre><pre>mongoose.connection.on(&quot;connected&quot;, () =&gt; {  <br>console.log(&quot;connected to mongoDB&quot;);<br>});</pre><pre>mongoose.connection.on(&quot;error&quot;, (err) =&gt; { <br>console.log(err);<br>});</pre><ul><li><strong>Deploying Server: </strong>I’ve deployed my server on heroku for free. It’s upto you which service you choose.</li></ul><h3>Conclusion</h3><p>Finally, we have come to end. Following these article we have seen the power of NodeJS.</p><p>This is not the end of the road. You can use your creativity and always add some cool extra features like a profile picture, hash passwords and anything you think of!</p><p>You can always find me on my <a href="https://www.linkedin.com/in/deepansh-makkar-175012197/">linkedIn</a>.</p><p>Thanks for being with me till the end :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92feac80c458" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>