<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NPM Node package manager &#8211; Digitaldocblog</title>
	<atom:link href="https://digitaldocblog.com/tag/npm-node-package-manager/feed/" rel="self" type="application/rss+xml" />
	<link>https://digitaldocblog.com</link>
	<description>Various digital documentation</description>
	<lastBuildDate>Thu, 23 Feb 2023 06:29:42 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://digitaldocblog.com/wp-content/uploads/2022/08/cropped-website-icon-star-500-x-452-transparent-32x32.png</url>
	<title>NPM Node package manager &#8211; Digitaldocblog</title>
	<link>https://digitaldocblog.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Role Based Access Control using express-session in a node-js app</title>
		<link>https://digitaldocblog.com/webdesign/role-based-access-control-using-express-session-in-a-node-js-app/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 04 May 2021 12:00:00 +0000</pubDate>
				<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webdesign]]></category>
		<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Java Script]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=141</guid>

					<description><![CDATA[In this article I refer to an application I created a couple of months ago. It&#8217;s about a booking system with which players can book ice-hockey trainings in different locations,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In this article I refer to an application I created a couple of months ago. It&#8217;s about a booking system with which players can book ice-hockey trainings in different locations, the coach can confirm participation in a training session  and a club manager can organize training sessions and bill the players for booked trainings. You can see the code on my <a href="https://github.com/prottlaender/bookingsystem" title="Node-Js Booking-System Code on GitHub Account of Patrick Rottlaender">GitHub Account</a> and read a detailed application description in the style of a user manual on my blog <a href="https://digitaldocblog.com/singleblog?article=9" title="Booking-System Application Description on Digitaldocblog Website owned by Patrick Rottlaender">Digitaldocblog</a>.</p>



<p>In my booking system I give users different roles in my app and depending on their role, the users have different authorizations. An <em>admin</em> for example is able to access more sensitive data and functionalities than a normal <em>player</em> or a <em>coach</em>. So my app must know the role of a user to assign different authorizations to the particular user.</p>



<p>Clients, usually browsers send requests the app. The app responds to requests and is solely responsible for ensuring that the client only has access to the data that are intended for it. This request and response game is based on the HTTP protocol. HTTP is a stateless network protocol and requests cannot be related to each other. Each request is isolated and unrelated to previous requests and the server has no chance to recognize clients and does therefore not know their role. </p>



<p>This problem can be solved with sessions and cookies and means that session management must be implemented in the application. The application creates a session and stores session data such as the role of a requestor in this session. The session has a unique ID and the app saves only this ID in a cookie. The cookie is transferred to the browser and stored locally there. From now on, the browser always sends this cookie with the HTTP request and thus identifies itself to the application. The application can check the role of the requestor in the stored session data and control the appropriate access.</p>



<h3 class="wp-block-heading">Basic setup of the server</h3>



<p>First we need a working Server OS. I run Linux Ubuntu in production and have written an article about the <a href="https://digitaldocblog.com/singleblog?article=10" title="Basic Setup for Node-Js Apps running on Ubuntu Linux on Digitaldocblog Website owned by Patrick Rottländer ">basic setup of a production Linux server</a> on my blog site <a href="https://digitaldocblog.com/home?currpage=1" title="Digitaldocblog Website owned by Patrick Rottlaender">Digitaldocblog</a>. Since I am going to store the sessions in a MongoDB, MongoDB must be installed on the Linux server. I use <em>MongoDB Community Edition</em> but you can also install or upgrade to the <em>MongoDB Enterprise</em> Server version. In the lower part of the article you find the instructions how to install and setup your <em>MongoDB Community Edition</em> on your Linux System. In case you want to read the original documentation go on the MongoDB site and read how to install the <a href="https://docs.mongodb.com/manual/administration/install-community/" title="MongoDB Community Edition Documentation">MongoDB Community Edition</a> for your OS.  </p>



<p>In my express application I use a number of external modules or dependencies that have to be installed for the application in order for the application to run. In the repository of the <a href="https://github.com/prottlaender/bookingsystem" title="Node-Js Booking-System Code on GitHub Account of Patrick Rottlaender">bookingsystem</a>on my <a href="https://github.com/prottlaender" title="GitHub Account of Patrick Rottlaender">GitHub account</a> you find the <a href="https://github.com/prottlaender/bookingsystem/blob/master/package.json" title="package.json file of Booking System on GitHub Account of Patrick Rottlaender">package.json</a> file which contains all the necessary dependencies. In principle, it is sufficient if you put this <em>package.json</em> file in your application main directory and install all dependencies with <code>npm install</code>. </p>



<p>Alternatively, of course, all modules can also be installed individually with </p>



<p><code>npm install &lt;module&gt; --save</code></p>



<h3 class="wp-block-heading">Session Management</h3>



<p>I discuss in the first part different code snippets in my application main file <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file of Booking System on GitHub Account of Patrick Rottlaender">booking.js</a>. The goal here is that you understand how session management is basically implemented.</p>



<pre class="wp-block-code"><code>// booking.js

// Load express module and create app
const express = require('express');
const app = express();
// Trust the first Proxy
app.set('trust proxy', 1);
// Load HTTP response header security module
const helmet = require('helmet');
// use secure HTTP headers using helmet with every request
app.use(
  helmet({
      frameguard: {
        action: "deny",
      },
      referrerPolicy: {
        policy: "no-referrer",
    },
    })
  );
// Load envy module to manage environment variables
const envy = require('envy');
const env = envy();

// Set environment variables
const port = env.port
const host = env.host
const mongodbpath = env.mongodbpath
const sessionsecret = env.sessionsecret
const sessioncookiename = env.sessioncookiename
const sessioncookiecollection = env.sessioncookiecollection

// Load server side session and cookie module
const session = require('express-session');
// Load mongodb session storage module
const connectMdbSession = require('connect-mongodb-session');
// Create MongoDB session store object
const MongoDBStore = connectMdbSession(session)
// Create new session store in mongodb
const store = new MongoDBStore({
  uri: mongodbpath,
  collection: sessioncookiecollection
});
// Catch errors in case session store creation fails
store.on('error', function(error) {
  console.log(`error store session in session store: ${error.message}`);
});
// Use session to create session and session cookie
app.use(session({
  secret: sessionsecret,
  name: sessioncookiename,
  store: store,
  resave: false,
  saveUninitialized: false,
  // set cookie to 1 week maxAge
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7,
    sameSite: true
  },
}));

... //further code not taken into account at this point
</code></pre>



<p>I create a server application using the <a href="https://www.npmjs.com/package/express" title="Express-Js Web-Application Framework for node-js">Express-js&nbsp;</a> Web Application Framework. Therefore I load the Express-js  module with the <code>require()</code> function and store the <code>express()</code> function in the constant <em>app</em>. Because my app is running behind a reverse proxy server I set the app to trust the first proxy server. Then I load the <a href="https://www.npmjs.com/package/helmet" title="Helmet Package for node-js">helmet module</a> to use secure response headers in my app. I configure that all browsers should deny iFrames and that my app will set no referrer in the response header. </p>



<p>I use the <a href="https://www.npmjs.com/package/envy" title="Envy module for node-js">envy module</a> in my application to manage environment variables. Therefore I load the module with <code>require()</code> and store the <code>envy()</code> function in the constant <em>env</em>. With envy you can define your environment variables in your <em>.env</em> and <em>.env.example</em> files. These files must be stored in the application main directory as explained in the envy documentation. </p>



<p>Since my booking app is a real web application running on a web server in production I can not discuss the real environment variables because of security reasons. Therefore let us see how this work and make an example <em>.env</em> file. </p>



<pre class="wp-block-code"><code>// .env

port=myport
host=myhost
mongodbpath=myexamplemongodbpath
sessionsecret=myexamplesecret
sessioncookiename=booking
sessioncookiecollection=col_sessions

</code></pre>



<p>These variables have different values in my <em>.env</em> file. In the <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a>file above I define the constant <em>env</em> for the envy function with <code>env = envy()</code> . Then I have access to the environment variables defined in my <em>.env</em> file with <em>env.&lt;variable&gt;</em>. I define constants for each variable and assign the variable from the .env file with <code>env.&lt;variable&gt;</code>. These constants can now be used as values in the code. </p>



<p>I load the <a href="https://www.npmjs.com/package/express-session" title="Node-Js Express-Session Module">express-session</a> module and the <a href="https://www.npmjs.com/package/connect-mongodb-session" title="Node-Js Connect-MongoDB-Session Module">connect-mongodb-session</a> module with the <code>require()</code> function. The session module stored in the constant <em>session</em> takes over the entire control of the session and cookie management. </p>



<p>The <em>connect-mongodb-session</em> stored in the constant <em>connectMdbSession</em> module is basically responsible for storing the session in the database. That is why we pass <em>session</em> as a parameter in the code and assign the constant <em>MongoDBstore</em>.</p>



<p><code>const MongoDBstore = connectMdbSession(session)</code> </p>



<p>With <code>new MongoDBStore</code> I create a new store object. Here I pass the <em>uri</em> of the mongodb path and the <em>collection</em> where sessions should be stored. </p>



<pre class="wp-block-code"><code>// booking.js
...

const store = new MongoDBStore({
  uri: mongodbpath,
  collection: sessioncookiecollection
});

...

</code></pre>



<p>The store object initialized in this way contains all necessary parameters to successfully store a session object in my MongoDB database.</p>



<p>After we have defined the storage of the session object, we take care of the session object itself. </p>



<p>With <code>app.use(session( {... cookie: {...} }))</code> I create a session object with various options. The session object will be created with each request and also contains a cookie object. I pass the values for <code>cookie: {...}</code> and then other options like<code>secret: sessionsecret</code>, the session object name with <code>name: sessioncookiename</code> as well as the location where the session object should be stored with <code>store: store</code>. Furthermore the session object has the option <code>saveUninitialized: false</code> and <code>resave: false</code> . </p>



<p>When the <em>saveUninitialized</em> option is set to <em>false</em> the session object is <em>not stored</em> into the store as long as the session is <strong>un-initialized</strong>. The option <code>resave: false</code> enforce that a session will <em>not be saved back</em> to the store even if the session is <strong>initialized</strong>.  So we must understand what <em>initialized</em> and <em>un-initialized</em> mean. This must be explained.</p>



<p>A browser send a request to the app. More precisely, the browser sends the request to a defined endpoint in the app. An endpoint defines a path within the app that reacts to HTTP requests and executes code. Depending on the HTTP method GET or POST, the endpoint expects that the requestor requires a document back (GET) or that the requestor wants to send data to the app (POST).</p>



<p>In the example below the browser should send a GET request to GET <em>home</em> endpoint. The endpoint render the HTML template <em>index</em> and send the HTML back to the browser. Then the request is finished. So this process, which starts with the <em>request</em> and ends with the <em>response</em> is the <em>runtime of the request</em>. </p>



<p>In the code snippet below you see 2 GET endpoints in the <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a> file one for the <em>home</em> route and another one for the <em>register</em> route.  </p>



<pre class="wp-block-code"><code>// booking.js

... //further code not taken into account at this point

// GET home route only for anonym users. Authenticated users redirected to dashboard
app.get('/', redirectDashboard, (req, res) =&gt; {
	
  console.log(req.url);
  console.log(req.session.id);
  console.log(req.session);

  res.render('index', {
      title: 'User Login Page',
    });

});

// GET register route only for anonym users. Authenticated users redirected to dashboard
app.get('/register', redirectDashboard, (req, res) =&gt; {
  
  console.log(req.url);
  console.log(req.session.id);
  console.log(req.session);

  res.render('register', {
      title: 'User Registration Page',
    });
});

... //further code not taken into account at this point


</code></pre>



<p>The code with <code>app.use (session({ ... }))</code> in my <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a> file ensures that a session object is always generated with each request. As long as a session object is not changed during the runtime of a request a separate session is created for each request and has its own session ID. The option <code>saveUninitialized: false</code> ensure that the session object will not be stored into the database. Each session object created in this way is <strong>un-initialized</strong>. </p>



<p>You can see the following output on the console for the <em>home</em> route and for the <em>register</em> route when we log the <em>path</em>, the <em>session-ID</em> and the <em>session object</em> on the console for each route.</p>



<pre class="wp-block-code"><code>/
BmbE8RVoTRcPP9nUnBm5JLE1w1mQiNyt
Session {
  cookie: {
    path: '/',
    _expires: 2021-04-24T04:27:04.265Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    sameSite: true
  }
}

/register
awlPO-KpyVM51Gp6UAoeXGGmRWo-QFtP
Session {
  cookie: {
    path: '/',
    _expires: 2021-04-24T05:54:57.439Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    sameSite: true
  }
}
  
</code></pre>



<p>The code of my app changes a session object during the runtime of a request by adding a data object when a user has successfully logged in. I will explain the code in detail in the next chapter but at the moment it is enough to know that. Therefore we play through the login of a user as follows.</p>



<p>The browser send a GET request to the <em>home</em> route as explained above, then the <em>index</em> template is rendered and the HTML page with the login form is sent back to the browser. During the runtime of this GET request a session object is created but the session object has not changed. We have already seen this above.</p>



<p>Then the user enters <em>email</em> and <em>password</em> in the login form and click submit. With this submit the browser send a POST request to the POST endpoint <em>/loginusers</em> and again a session object is generated for this POST request. During the runtime of the POST request, the code checks whether the transferred credentials are correct. If the credentials are correct, a data object with user data is generated and attached to the session object. Here the session object is changed during the runtime of the POST request. The existing session created with the POST request is now <strong>initialized</strong> at that moment. Because of the option <code>saveUninitialized: false</code> this session object is stored into the database store. When we look into the database store using the tool <a href="https://www.mongodb.com/products/compass" title="MongoDB Compass Management Console ">MongoDB Compass</a> we see that the entire session object has been saved into the <em>col<em>sessions</em></em> collection including the data object containing the required data of the user.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img fetchpriority="high" decoding="async" width="2460" height="1126" src="https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object.png" alt="Session Object saved in the *col_sessions* " class="wp-image-136" srcset="https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object.png 2460w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-300x137.png 300w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1024x469.png 1024w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-768x352.png 768w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1536x703.png 1536w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-2048x937.png 2048w" sizes="(max-width: 2460px) 100vw, 2460px" /><figcaption>Session Object saved in the *col_sessions* </figcaption></figure>
</div>


<p>After the session initialization the code called by the POST endpoint redirect the request and send a new GET request to the <em>/dashboard</em> route. The code with <code>app.use(session({ ... }))</code>  is called again but now there is an initialized session existing in the store. Because of the option <code>resave: false</code> the existing session object will not be updated and dragged along unchanged with every further request.</p>



<p>You see this in the output on the console when we log the <em>path</em>, the <em>session-ID</em> and the <em>session object</em> on the console for each route. The first output on the console is created when the GET request is sent to the <em>home</em> route. Then, the second output, after the user clicked submit the POST route <em>/loginusers</em> is called and a new session object is created. You see this from the different session IDs. During the runtime of this POST request the data object is added to the session object which initializes the session. Then, the third output, the GET route <em>/dashboard</em> is called and we see the same session object ID but the session object now contain the data object with the user data.</p>



<pre class="wp-block-code"><code>/
TEAZITdX7nLWBDc8uOk2HhXIiMZO7W-4
Session {
  cookie: {
    path: '/',
    _expires: 2021-05-02T07:21:13.236Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    sameSite: true
  }
}

/loginusers
gVlKut3bdEMiDHnK455FGjCi6YbPTBuZ
Session {
  cookie: {
    path: '/',
    _expires: 2021-05-02T07:21:35.202Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    sameSite: true
  }
}

/dashboard
gVlKut3bdEMiDHnK455FGjCi6YbPTBuZ
Session {
  cookie: {
    path: '/',
    _expires: 2021-05-02T07:21:35.468Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    secure: null,
    domain: null,
    sameSite: true
  },
  data: {
    userId: 5f716b7439777365c18639f1,
    status: 'active',
    name: 'Oskar David',
    lastname: 'Rottländer',
    email: 'oskar@test.com',
    role: 'player',
    age: 17,
    cat: 'youth'
  }
}

</code></pre>



<p>In summary, session management works as follows: A session object will be created with each request and the session object is only saved in the database when the user is logged in (<em>saveUninitialized: false</em>). As long as the user is logged in, the session object is not changed and the data of the session object in the database are not updated (<em>resave: false</em>).</p>



<p><strong>But what happens to the cookie ?</strong> This will be explained in the next chapter.</p>



<h3 class="wp-block-heading">User login</h3>



<p>When the session has been initialized the cookie containing the session ID is stored in the browser of the requestor. With every request the browser provide the cookie to authenticate the requestor. To authenticate the requestor the code <code>app.use(session({...}))</code>  is called and compare the session ID sent by the browser with the session IDs stored in the session store. If a session ID matches, the session object including the data object is attached to the request object to give the app access to the data object. Within the app we now have access to any attribute of the data object with <em>req.session.data.&lt;attribute&gt;</em>. Therefore we can now implement role based authorization by accessing the role of the requestor with <em>req.session.data.role</em> and use this information in conditions in the code to control access depending on the role of the requestor. </p>



<p>But lets start from the beginning with the login of the requestor or user as I call the requestor from now on. In order for a user to be able to login, he or she must first call the <strong>login page</strong> which can be displayed by calling up the home endpoint. </p>



<pre class="wp-block-code"><code>// booking.js

... // Code not discussed here

// Redirect GET requests from authenticated users to dashboard
const redirectDashboard = (req, res, next) =&gt; {
  if (req.session.data) {
    res.redirect('/dashboard')

  } else {
    next()

  }
}

... // Code not discussed here

// GET home route only for anonym users. Authenticated users redirected to dashboard

app.get('/', redirectDashboard, (req, res) =&gt; {

  res.render('index', {
      title: 'User Login Page',
    });

});

... // Code not discussed here

</code></pre>



<p>As you see above in the code I have first defined the middleware function <em>redirectDashboard</em>. This middleware ensure that only users who are not logged in see the login page. If we look at the code of the middleware function we can see that <em>req.session.data</em> is used in an if-condition to check whether a data object is attached to the current session object. In case the <strong>if-condition is true</strong>, the user is logged in and the request is redirected to the dashboard, but in case the <strong>if-condition is false</strong>, the user is not logged in and the <em>next()</em> function is called. </p>



<p>The GET endpoint has the <em>routingPath</em> to the home route. When a user visits the homepage of my booking application, the GET HTTP request ask for the home <em>routingPath</em>. The middleware function <em>redirectDashboard</em> is put in front of the <em>routingHandler</em> function. If the user is not logged in the <em>routingHandler</em> function render the HTML template <a href="https://github.com/prottlaender/bookingsystem/blob/master/views/index.pug" title="index.pug file">index.pug</a>and send the HTML back to the user or more precisely to the user&#8217;s browser. </p>



<p>So far so good. We now imagine a not logged in user who sees the index page in front of him or her now wants to login using his or her <em>email</em> and <em>password</em>.</p>



<p>As described above, the index page is nothing more than a login form for entering an email address and a password. When we look at the <a href="https://github.com/prottlaender/bookingsystem/blob/master/views/index.pug" title="index.pug file">index.pug</a> file we see that the form action attribute define that the form data <code>email</code> and <code>password</code> will be sent to the form handler <code>/loginusers</code> using the POST method when the Submit button is clicked.</p>



<pre class="wp-block-code"><code>...

form#loginForm.col.s12(
		method='post', 
		action='/loginusers'
		)

		input.validate(
			type='email', 
			name='email', 
			autocomplete='username' 
			required
			)
		...

		input.validate(
			type='password', 
			name='password', 
			autocomplete='current-password' 
			required
			)
		...

button.btn.waves-effect.waves-light(
		type='submit', 
		form='loginForm'
		)
...

</code></pre>



<p><strong>Note</strong>: To understand the <em>autocomplete</em> attributes of the input tags I recommend reading the documentation of the <a href="https://www.chromium.org/developers/design-documents/form-styles-that-chromium-understands" title="The Chromium Project">Chromium Project</a>. Most browsers have password management functionalities and automatically fill in the credentials after you provide a master password to unlock your local password store. By using these autocomplete attributes in login forms but also in user registration forms or change password forms you help browsers by using these <em>autocomplete</em> functions to better identify these forms.</p>



<p>When the user has entered his or her <em>email</em> and <em>password</em> in the HTML form and clicked the Submit button, the <strong>request body</strong> contain the <em>Form Data</em> attributes <em>email</em> and <em>password</em>. Then a POST HTTP request is sent via HTTPS to the POST endpoint <code>/loginusers</code> defined in my <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a> file (see above). </p>



<p>In the picture below you can see the output of the network analysis in the developer tool of the chrome browser. Here you can see that the <em>Form Data</em> are not encrypted on <strong>browser side</strong> but you also see that the POST request URL <code>/loginusers</code> is HTTPS. This mean that when the browser sent the POST request to the server these data are encrypted with SSL/TLS in transit from the browser to the server.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" width="2002" height="612" src="https://digitaldocblog.com/wp-content/uploads/2022/08/050-POST-route-request-with-form-data.png" alt="*Form Data* not encrypted on browser side" class="wp-image-137" srcset="https://digitaldocblog.com/wp-content/uploads/2022/08/050-POST-route-request-with-form-data.png 2002w, https://digitaldocblog.com/wp-content/uploads/2022/08/050-POST-route-request-with-form-data-300x92.png 300w, https://digitaldocblog.com/wp-content/uploads/2022/08/050-POST-route-request-with-form-data-1024x313.png 1024w, https://digitaldocblog.com/wp-content/uploads/2022/08/050-POST-route-request-with-form-data-768x235.png 768w, https://digitaldocblog.com/wp-content/uploads/2022/08/050-POST-route-request-with-form-data-1536x470.png 1536w" sizes="(max-width: 2002px) 100vw, 2002px" /><figcaption>*Form Data* not encrypted on browser side</figcaption></figure>
</div>


<p>On the <strong>server side</strong> we have the web application behind a proxy server listening to HTTP requests addressed to the POST endpoint <code>/loginusers</code>.  This POST endpoint is an anonym POST Route which means that the <em>routingHandler</em> controller function is restricted to not logged-in users only. This makes sense because a login function must not be used by already logged in users. So already logged in users can not send data to this POST endpoint. This check is controlled by the middleware function <em>verifyAnonym</em> which is put in front of the <em>routingHandler</em>.  </p>



<p>So lets look at the relevant code snippets in <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a>.</p>



<pre class="wp-block-code"><code>// booking.js

...

// Load db controllers and db models
const userController = require('./database/controllers/userC');

...

// Verify POST requests only for anonym users
const verifyAnonym = (req, res, next) =&gt; {

  if (req.session.data) {
    var message = 'You are not authorized to perform this request because you are already logged-in !';
    res.status(400).redirect('/400badRequest?message='+message);

  } else {
    next()

  }
}

...

// Anonym POST Route
// Login user available for anonym only
app.post('/loginusers', verifyAnonym, userController.loginUser)

...

// GET bad request route render 400badRequest
app.get('/400badRequest', (req, res) =&gt; {
 
  res.status(400).render('400badRequest', {
    title: 'Bad Request',
    code: 400,
    status: 'Bad Request',
    message: req.query.message,
  })
})

...

</code></pre>



<p>At the beginning of the code I refer the constant <em>userController</em> to the user controller file <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/controllers/userC.js" title="userC.js file">userC.js</a> using the <code>require</code> method. In <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/controllers/userC.js" title="userC.js file">userC.js</a> all user functions are defined to control user related operations.</p>



<p><strong>Note</strong>: When you look into the <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/controllers/userC.js" title="userC.js file">userC.js</a> file you see that we export modules using <code>module.exports = {...}</code>. Using this directive we export in fact an object with various attributes and the values of these attributes are functions. So with  <code>module.exports = { loginUser: function(...) ...}</code> we export the object including the attribute <em>loginUser</em> which contains a function as value. So when we refer the constant  <em>userController</em> using the <code>require()</code> function in the <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a> file we store the complete exported object with all its attributes to the <em>userController</em> constant. Now we have access to any attribute of the exported object from <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/controllers/userC.js" title="userC.js file">userC.js</a> file with <em>userController.&lt;attribute&gt;</em>. Because the attributes are in fact functions we call these functions with this statement.  </p>



<p>In the <em>verifyAnonym</em> function <em>req.session.data</em> is used in the if-condition to check whether a data object is attached to the current session object. In case the <strong>if-condition is true</strong>, the user is already logged-in and is redirected to the Bad Request GET endpoint <code>/400badRequest</code> which is the standard route in my application to show the user that something went wrong. The user can see what went wrong from a message that has been attached to the request using the request parameter <code>?message=+message</code>. In case <strong>the if-condition is false</strong>, the user is not logged-in and the <em>next()</em> function forwards the request to the <em>routingHandler</em> controller function that call the <code>loginUser</code> function using <em>userController.loginUser</em>.  This function has access to the attributes <em>email</em> and <em>password</em> of the <strong>request body</strong> with <em>req.body.email</em> and <em>req.body.password</em>. </p>



<p>So lets look at the relevant code snippets in <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/controllers/userC.js" title="userC.js file">userC.js</a> file.</p>



<pre class="wp-block-code"><code>// database/controllers/userC.js

// load the bcryptjs module
const bcrypt = require('bcryptjs');
// define hash saltrounds for password hashing
const saltRounds = 10;
// load the relevant Prototype Objects (exported from the models)
...

const User = require('../models/userM');

...

loginUser: function (req, res) {

    const inputemail = req.body.email
    const email = inputemail.toLowerCase()

    console.log(req.url);
    console.log(req.session.id);
    console.log(req.session);

    try {

      User.findOne({ email: email }, async function(error, user) {
        if (!user) {
          var message = 'User not found. Login not possible';
          res.status(400).redirect('/400badRequest?message='+message);

        } else {
          if (user._status !== 'active') {
            var message = 'Login not possible. Await User to be activated';
            res.status(400).redirect('/400badRequest?message='+message);

          } else {
              if (bcrypt.compareSync(req.body.password, user.password)) {

                var yearInMs = 3.15576e+10;
                var currentDate = new Date ()
                var currentDateMs = currentDate.getTime()
                var birthDateMs = user.birthdate.getTime()
                var age = Math.floor((currentDateMs - birthDateMs) / yearInMs)

                if (age &lt; 18) {
                  var cat = 'youth'
                } else {
                  var cat = 'adult'
                };

                var userData = {
                  userId: user._id,
                  status: user._status,
                  name: user.name,
                  lastname: user.lastname,
                  email: user.email,
                  role: user.role,
                  age: age,
                  cat: cat,
                }

                req.session.data = userData

                res.status(200).redirect('/dashboard')

              } else {
                var message = 'Login not possible. Wrong User password';
                res.status(400).redirect('/400badRequest?message='+message);
              }
          }
        }
      })

    } catch (error) {
      // if user query fail call default error function
      next(error)

    }
  // End Module
  },

...

</code></pre>



<p>In order to authenticate a user, the <em>loginUser</em> function must find a user in the user database with the same email address as the one that was sent by the browser and attached to the request body by the app. If a user was found with the email, the function must check whether the transmitted password matches the password that is stored in the database for this user. If the email and password match the user is authenticated and the login is successful, if not, the login fails. </p>



<p>Passwords are never saved in plain text. Therefore I use the <a href="https://www.npmjs.com/package/bcryptjs" title="Bcrypt-Js module for node-js">bcryptjs module</a> to hash passwords. The bcryptjs module is loaded into the code with the <code>require()</code> function and assigned to the constant <em>bcrypt</em>. We set the constant <em>saltRounds</em> to the value of 10. This is the so called cost factor in the bcrypt hashing function and controls how much time bcrypt need to calculate a single bcrypt hash. Increasing the cost factor by 1 doubles the time and the more time bycrypt need to hash the more difficult it is to brute force stored passwords.</p>



<p>Then I load the user model from <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/models/userM.js" title="userM.js file">userM.js</a> using the <code>require()</code> function and assign the constant <em>User</em>. Here at this point I have to explain the background. To do this, we also need a look at the <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/models/userM.js" title="userM.js file">userM.js</a> file. </p>



<p><strong>Note</strong>: I use MongoDB as the database and Mongoose to model the data. If you look in the file <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/models/userM.js" title="userM.js file">userM.js</a> you see that a user object is created with the function <em>new Schema()</em> and saved in the variable <em>userSchema</em>. This <em>userSchema</em> object describes a user with all its attributes. At the end of the file, the <em>mongoose.model()</em> function is used to reference the <em>userSchema</em> to the collection <em>col<em>users</em></em> in my MongoDB. This reference is assigned to the variable <em>User</em> and exported using the function <em>module.exports()</em>. With <em>User</em> I have access to the user model meaning to all user objects and attributes in my database that are stored in the <em>col<em>users</em></em> collection. So that I can use this access in the code of my <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/controllers/userC.js" title="userC.js file">userC.js</a> file I load <a href="https://github.com/prottlaender/bookingsystem/blob/master/database/models/userM.js" title="userM.js file">userM.js</a> with the <code>require()</code> function and assign the constant <em>User</em>. I can now use Mongoose functions for example to query user data from my <em>col<em>users</em></em> collection. This is exactly what we do with <em>User.findOne()</em> when we try to find a user with a certain email.</p>



<p>The actual <strong>user authentication</strong> now takes place in the <em>userFindOne()</em> function. </p>



<p>When we run <em>User.findOne()</em> we check the criteria that do not lead to a successful authentication. </p>



<ol class="wp-block-list"><li><strong>No user found</strong>: We are looking for a user object that matches the email that has been submitted. If no user object is found with that email or the user found is not active, the request is redirected to the 400badRequest route. If we have found an active user, the submitted password string is hashed with bcrypt and compared with the saved password. </li><li><strong>Wrong password</strong>: If the password comparison is not successful, the submitted password was wrong and the request is also redirected to the 400badRequest route. <br></li></ol>



<p><strong>Note</strong>: <em>User.findOne()</em> has a query object <code>{email: email}</code> and a callback function <code>async function(error, user {...})</code> as parameters. When the async function find a user with the email in the database, this async function returns a user object with all the user attributes and store this object into the <em>user</em> parameter. Within the scope of the async function I have now access to the user attributes using <em>user.&lt;attribute&gt;</em>.</p>



<p>Only in case the user with the email is found and the submitted password is correct the authentication is successful.</p>



<p>If the user is successfully authenticated, the category of the user is calculated based on the current date and the user&#8217;s birth date. Then a <em>userData</em> object is created in which various user attributes are stored. The data of the <em>userData</em> object are then attached to the session. More precisely, the object <em>data</em> is attached to the session with <em>req.session.data</em> and the value <em>userData</em> is assigned. Now the session is initialized and the session object is stored in the <em>col<em>sessions</em></em> collection of the MongoDB.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" width="2460" height="1126" src="https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1.png" alt="Initialized session and session object stored in the col_sessions" class="wp-image-135" srcset="https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1.png 2460w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1-300x137.png 300w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1-1024x469.png 1024w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1-768x352.png 768w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1-1536x703.png 1536w, https://digitaldocblog.com/wp-content/uploads/2022/08/070-DB-session-object-1-2048x937.png 2048w" sizes="(max-width: 2460px) 100vw, 2460px" /><figcaption>Initialized session and session object stored in the col_sessions</figcaption></figure>
</div>


<p>Then the <strong>response</strong> is sent back to the browser. </p>



<p>In this response, the browser is instructed to call up a GET request to the GET endpoint <code>/dashboard</code>. The response is sent using <code>res.status(200).redirect('/dashboard')</code>. In the Response Header you see that the cookie with the name <em>booking</em> is set in the users browser using the <code>set-cookie</code> directive. The cookie only contain the session ID which has been signed and encrypted with the <em>secret</em> we provided in  <code>app.use(session( {... cookie: {...} }))</code>. </p>


<div class="wp-block-image">
<figure class="aligncenter"><img loading="lazy" decoding="async" width="1759" height="557" src="https://digitaldocblog.com/wp-content/uploads/2022/08/060-POST-route-request-with-form-data-set-cookie.png" alt="Response Header with cookie named *booking*" class="wp-image-138" srcset="https://digitaldocblog.com/wp-content/uploads/2022/08/060-POST-route-request-with-form-data-set-cookie.png 1759w, https://digitaldocblog.com/wp-content/uploads/2022/08/060-POST-route-request-with-form-data-set-cookie-300x95.png 300w, https://digitaldocblog.com/wp-content/uploads/2022/08/060-POST-route-request-with-form-data-set-cookie-1024x324.png 1024w, https://digitaldocblog.com/wp-content/uploads/2022/08/060-POST-route-request-with-form-data-set-cookie-768x243.png 768w, https://digitaldocblog.com/wp-content/uploads/2022/08/060-POST-route-request-with-form-data-set-cookie-1536x486.png 1536w" sizes="auto, (max-width: 1759px) 100vw, 1759px" /><figcaption>Response Header with cookie named *booking*</figcaption></figure>
</div>


<p>Then the browser send the GET request to the endpoint <code>/dashboard</code>. Lets have a look into the <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a> file again.</p>



<pre class="wp-block-code"><code>// booking.js 

...

// Redirect GET requests from not authenticated users to login
const redirectLogin = (req, res, next) =&gt; {
  if (!req.session.data) {
    res.redirect('/')

  } else {
    next()

  }
}

...

// GET dashboard route only for authenticated users. Anonym users redirected to home
app.get('/dashboard', redirectLogin, async (req, res) =&gt; {

  // Check admin authorization and render admin_dashboard
  if (req.session.data.role == 'admin') {

    const user_query = User.find( {} ).sort({lastname: 1, name: 1});
    var users = await user_query.exec();

    const training_query = Training.find( {} ).sort({date: 'desc'});
    var trainings = await training_query.exec();

    const location_query = Location.find( {} ).sort({location: 'desc'});
    var locations = await location_query.exec();

    const booking_query = Booking.find( {} ).sort({_booktrainingdate: 'desc'});
    var bookings = await booking_query.exec();

    const invoice_query = Invoice.find( {} ).sort({invoicedate: 'desc'});
    var invoices = await invoice_query.exec();

    res.status(200).render('admin_dashboard', {
      title: 'Admin Dashboard Page',
      name: req.session.data.name,
      lastname: req.session.data.lastname,
      role: req.session.data.role,
      data_users: users,
      data_trainings: trainings,
      data_locations: locations,
      data_bookings: bookings,
      data_invoices: invoices,

      });

  // Check player authorization and render player_dashboard
  } else if (req.session.data.role == 'player') {

    var currentDate = new Date();
    console.log('current date: ' +currentDate);

    const availabletraining_query = Training.find( { _status: 'active', date: { $gte: currentDate } } ).sort({ date: 'desc' });
    var availabletrainings = await availabletraining_query.exec();

    const booking_query = Booking.find( { _bookuseremail: req.session.data.email, _bookparticipation: { $ne: 'invoice' } } ).sort({ _booktrainingdate: 'desc' });
    var bookings = await booking_query.exec();

    const myuser_query = User.findOne( { email: req.session.data.email } );
    var myuser = await myuser_query.exec();

    const invoice_query = Invoice.find( {invoiceemail: req.session.data.email} ).sort({invoicedate: 'desc'});
    var invoices = await invoice_query .exec();

    res.status(200).render('player_dashboard', {
      title: 'Player Dashboard Page',
      name: req.session.data.name,
      lastname: req.session.data.lastname,
      role: req.session.data.role,
      email: req.session.data.email,
      data_availabletrainings: availabletrainings,
      data_bookings: bookings,
      data_myuser: myuser,
      data_myinvoices: invoices,
      });

  // Check coach authorization and render coach_dashboard
  } else if (req.session.data.role == 'coach') {
   
    var currentDate = new Date().setHours(00, 00, 00);
    console.log('currentDate: ' +currentDate);

    const training_query = Training.find( { _status: 'active', date: { $gte: currentDate } } ).sort({ date: 'asc' });
    var trainings = await training_query.exec();

    res.status(200).render('coach_dashboard', {
      title: 'Coach Dashboard Page',
      name: req.session.data.name,
      lastname: req.session.data.lastname,
      role: req.session.data.role,
      data_trainings: trainings,
      });

  } else {
    // if user not authorized as admin, player or coach end request and send response
    var message = 'You are not authorized. Access prohibited';
    res.status(400).redirect('/400badRequest?message='+message);
  }

});

...

</code></pre>



<p>As you see above in the code we have first defined the middleware function <em>redirectLogin</em>. This middleware ensure that only users who are logged in see the dashboard page. In case the <strong>if-condition is true</strong>, the user is not logged in and the request is redirected to the home route, but in case the <strong>if-condition is false</strong>, the user is logged in and the <em>next()</em> function is called. </p>



<p>The GET HTTP request ask for the dashboard <em>routingPath</em>. The middleware function <em>&nbsp;redirectLogin</em> is put in front of the <em>routingHandler</em> function. If the user is not logged in the <em>&nbsp;redirectLogin</em> middleware redirect the request to the home route. In case the user is logged-in the <em>routingHandler</em> function is called using the request object and the response object as parameters.</p>



<pre class="wp-block-code"><code>app.get('/dashboard', redirectLogin, async (req, res) =&gt; {...})
</code></pre>



<p>If we look at the Request Header of this new GET request in the browser we can see that the cookie is dragged along unchanged with the GET request to the endpoint <code>/dashboard</code>. This happens from now on with every request until the session expires or until the user logout. </p>


<div class="wp-block-image">
<figure class="aligncenter"><img loading="lazy" decoding="async" width="1751" height="590" src="https://digitaldocblog.com/wp-content/uploads/2022/08/080-GET-route-request-dashboard-with-cookie.png" alt="Cookie dragged along with GET request " class="wp-image-139" srcset="https://digitaldocblog.com/wp-content/uploads/2022/08/080-GET-route-request-dashboard-with-cookie.png 1751w, https://digitaldocblog.com/wp-content/uploads/2022/08/080-GET-route-request-dashboard-with-cookie-300x101.png 300w, https://digitaldocblog.com/wp-content/uploads/2022/08/080-GET-route-request-dashboard-with-cookie-1024x345.png 1024w, https://digitaldocblog.com/wp-content/uploads/2022/08/080-GET-route-request-dashboard-with-cookie-768x259.png 768w, https://digitaldocblog.com/wp-content/uploads/2022/08/080-GET-route-request-dashboard-with-cookie-1536x518.png 1536w" sizes="auto, (max-width: 1751px) 100vw, 1751px" /><figcaption>Cookie dragged along with GET request </figcaption></figure>
</div>


<p>And now within the <em>routingHandler</em> function we do the <strong>user authorization</strong> check. The if condition check the users role using <em>req.session.data.role</em>. Depending on the role of the user different <em>&lt;role&gt;<em>dashboard</em></em> HTML templates are rendered and for each role different HTML is sent back to the user&#8217;s browser. Various queries are executed beforehand because we need role specific data within each <em>&lt;role&gt;<em>dashboard</em></em> HTML template. The return values ​​of the different queries <code>find()</code> and <code>findOne()</code> are only executed in case one of the if conditions become true. Then in each case the return values of the queries are stored in variables. In case all if conditions are false, meaning we cannot find a user with a role like <em>admin</em>, <em>player</em> or <em>coach</em> in the database for some reason the request is redirected to the Bad Request GET endpoint <code>/400badRequest</code> using the message as request parameter that this user is not authorized.</p>



<p>Within each if condition and for each role <em>admin</em>, <em>player</em> or <em>coach</em>, we create the response object by first setting the HTTP status to the value of 200 and then using the render method to render the respective HTML template.</p>



<pre class="wp-block-code"><code>res.status(200).render('&lt;role&gt;_dashboard', {...})
</code></pre>



<p>Within the render method, we now have the option of transferring a data object with different attributes to the HTML template. Later we can access these data in the respective HTML template and use it within the HTML template. How this works is not part of this article. But of course you can take a closer look at the templates <a href="https://github.com/prottlaender/bookingsystem/blob/master/views/admin_dashboard.pug" title="admin_dashboard.pug file">admin dashboard</a>, <a href="https://github.com/prottlaender/bookingsystem/blob/master/views/player_dashboard.pug" title="player_dashboard.pug file">player dashboard</a>and <a href="https://github.com/prottlaender/bookingsystem/blob/master/views/coach_dashboard.pug" title="coach_dashboard.pug file">coach dashboard</a>on my <a href="https://github.com/prottlaender" title="GitHub Account of Patrick Rottlaender">GitHub repository</a> and you will immediately see how this works.</p>



<h3 class="wp-block-heading">Create Authorizations</h3>



<p>As I have already shown in the upper part, I work with middleware functions to control access to GET and POST endpoints in my app. Therefore these middleware functions are the Authorizations and you can find them in the code of my <a href="https://github.com/prottlaender/bookingsystem/blob/master/booking.js" title="booking.js file">booking.js</a> file.</p>



<pre class="wp-block-code"><code>// booking.js

...

// Authorizations
// Redirect GET requests from not authenticated users to login
const redirectLogin = (req, res, next) =&gt; {
  if (!req.session.data) {
    res.redirect('/')

  } else {
    next()

  }
}

// Redirect GET requests from authenticated users to dashboard
const redirectDashboard = (req, res, next) =&gt; {
  if (req.session.data) {
    res.redirect('/dashboard')

  } else {
    next()

  }
}

// Authorize POST requests only for not authenticated users
const verifyAnonym = (req, res, next) =&gt; {
  if (!req.session.data) {
    next()

  } else {
    var message = 'You are already logged-in. You are not authorized to perform this request !';
    res.status(400).redirect('/400badRequest?message='+message);

  }
}

// Authorize POST requests only for anonym and admin users
const verifyAnonymAndAdmin = (req, res, next) =&gt; {
  if (!req.session.data) {
    next()

  } else {

    if (req.session.data.role == 'admin') {
      next()

    } else {
      var message = 'You are no Admin. You are not authorized to perform this request !';
      res.status(400).redirect('/400badRequest?message='+message);

    }

  }
}

// Authorize POST requests only for admin and player users
const verifyAdminAndPlayer = (req, res, next) =&gt; {
  if (req.session.data) {
    if (req.session.data.role == 'admin') {
      next()

    } else if (req.session.data.role == 'player') {
      next()

    } else {
      var message = 'You are no Admin, no Player. You are not authorized to perform this request !';
      res.status(400).redirect('/400badRequest?message='+message);
    }

  } else {
    var message = 'You are not logged-in. You are not authorized to perform this request !';
    res.status(400).redirect('/400badRequest?message='+message);
  }

}

// Authorize POST requests only for admin users
const verifyAdmin = (req, res, next) =&gt; {
  if (req.session.data) {
    if (req.session.data.role == 'admin') {
      next()

    } else {
      var message = 'You are no Admin. You are not authorized to perform this request !';
      res.status(400).redirect('/400badRequest?message='+message);
    }

  } else {
    var message = 'You are not logged-in. You are not authorized to perform this request !';
    res.status(400).redirect('/400badRequest?message='+message);

  }
}

// Authorize POST requests only for player users
const verifyPlayer = (req, res, next) =&gt; {
  if (req.session.data) {
    if (req.session.data.role == 'player') {
      next()

    } else {
      var message = 'You are no Player. You are not authorized to perform this request !';
      res.status(400).redirect('/400badRequest?message='+message);
    }

  } else {
    var message = 'You are not logged-in. You are not authorized to perform this request !';
    res.status(400).redirect('/400badRequest?message='+message);

  }
}

// Authorize POST requests only for coach users
const verifyCoach = (req, res, next) =&gt; {
  if (req.session.data) {
    if (req.session.data.role == 'coach') {
      next()

    } else {
      var message = 'You are no Coach. You are not authorized to perform this request !';
      res.status(400).redirect('/400badRequest?message='+message);

    }

  } else {
    var message = 'You are not logged-in. You are not authorized to perform this request !';
    res.status(400).redirect('/400badRequest?message='+message);

  }
}

...

</code></pre>



<p>As I have already explained above I use <strong>redirect functions</strong> as a middleware to control access to the <strong>GET endpoints</strong> <em>home</em>, <em>register</em> and <em>dashboard</em>. These middleware functions basically control access based on whether a user is logged-in or not. The redirect function <em>redirectDashboard</em> allow only not logged-in users access to the <em>home</em> endpoint and to the <em>register</em> endpoint, while users who are already logged-in have no access and would be redirected directly to the <em>dashboard</em> route if they try to access here. The <em>redirectLogin</em> middleware function allow only logged-in users access to the <em>dashboard</em> route while not logged-in users are redirected to the login or better to the <em>home</em> endpoint.</p>



<p>In addition to  <em>redirect functions</em> I use <strong>verify functions</strong> as a middleware to control access to the <strong>POST endpoints</strong>. With the help of POST requests, data are sent via POST endpoints to the app. That is why it is particularly important to control who is allowed to send data and who is not. I use basically 5 types of POST endpoints.</p>



<p><strong>Anonym POST endpoint</strong>. I only have one endpoint here. The <em>loginusers</em> endpoint can only be called by not logged-in users. Therefore the <em>verifyAnonym&nbsp;</em> middleware is set before the <em>routingHandler</em> function to verify if the user is not logged-in. </p>



<pre class="wp-block-code"><code>// booking.js
...

// Anonym POST endpoint
// Login user available for anonym only
app.post('/loginusers', verifyAnonym, userController.loginUser)

...

</code></pre>



<p><strong>Shared POST endpoints</strong>. The <em>createusers</em> endpoint can be called by not logged-in users and Admin users. The <em>&nbsp;verifyAnonymAndAdmin&nbsp;</em> middleware is set before the <em>routingHandler</em> function to verify if the user is not logged-in or if the user that is logged-in has the role <em>admin</em>.  The <em>&nbsp;updateuseremail</em> and <em>setnewuserpassword</em> endpoints can be called only by Admin and Player users. Therefore the <em>&nbsp;verifyAdminAndPlayer&nbsp;</em> middleware is set before the <em>routingHandler</em> function to verify if the user is logged-in and if the users role is <em>admin</em> or <em>player</em>. </p>



<pre class="wp-block-code"><code>// booking.js
...

// Shared POST endpoints
// Create Users available for anonym and admin
app.post('/createusers', verifyAnonymAndAdmin, birthdateFormatValidation, userController.createUser)

// Update User-Email available for admin and player
app.post('/updateuseremail', verifyAdminAndPlayer, userController.updateUserEmail)

// Update User-Password available for admin and player
app.post('/setnewuserpassword', verifyAdminAndPlayer, userController.setNewUserPassword)

...

</code></pre>



<p><strong>Admin POST endpoints</strong>.  I have 19 endpoints here and each of these endpoint can only be called by Admin users. The <em>&nbsp;verifyAdmin</em> middleware is set before the <em>routingHandler</em> function to verify if the user is logged-in and if the users role is <em>admin</em>. </p>



<pre class="wp-block-code"><code>// booking.js
...

// Admin POST endpoints
// Admin User Management
app.post('/callupdateusers', verifyAdmin, userController.callUpdateUsers)

app.post('/updateuser', verifyAdmin, birthdateFormatValidation, userController.updateUser)

app.post('/terminateusers', verifyAdmin, userController.terminateUser)

app.post('/activateusers', verifyAdmin, userController.activateUser)

app.post('/removeusers', verifyAdmin, userController.removeUser)

// Admin Update Training
app.post('/callupdatetrainings', verifyAdmin, trainingController.callUpdateTrainings)

app.post('/updatetraining', verifyAdmin, trainingController.updateTraining)

// Admin Location Management
app.post('/createlocations', verifyAdmin, locationController.createLocation)

app.post('/callupdatelocations', verifyAdmin, locationController.callUpdateLocations)

app.post('/updatelocation', verifyAdmin, locationController.updateLocation)

app.post('/callcreatetrainings', verifyAdmin, trainingController.callCreateTrainings)

app.post('/createtraining', verifyAdmin, trainingController.createTraining)

// Admin Invoice Management
app.post('/createinvoice', verifyAdmin, invoiceController.createInvoiceUser)

app.post('/callcancelinvoice', verifyAdmin, invoiceController.callCancelInvoice)

app.post('/cancelinvoice', verifyAdmin, invoiceController.cancelInvoice)

app.post('/callpayinvoice', verifyAdmin, invoiceController.callPayInvoice)

app.post('/payinvoice', verifyAdmin, invoiceController.payInvoice)

app.post('/callrepayinvoice', verifyAdmin, invoiceController.callRePayInvoice)

app.post('/repayinvoice', verifyAdmin, invoiceController.rePayInvoice)

...

</code></pre>



<p><strong>Player POST endpoints</strong>.  I have 7 endpoints here and each of these endpoint can only be called by Player users. The <em>&nbsp;verifyPlayer</em> middleware is set before the <em>routingHandler</em> function to verify if the user is logged-in and if the users role is <em>player</em>. </p>



<pre class="wp-block-code"><code>// booking.js
...

// Player POST endpoints
// Player Booking Management
app.post('/callbooktrainings', verifyPlayer, bookingController.callBookTrainings)

app.post('/booktrainings', verifyPlayer, bookingController.bookTraining)

app.post('/bookingreactivate', verifyPlayer, bookingController.bookingReactivate)

app.post('/callcancelbookings', verifyPlayer, bookingController.callCancelBooking)

app.post('/cancelbookings', verifyPlayer, bookingController.cancelBooking)

// Player User Management
app.post('/callupdatemyuserdata', verifyPlayer, userController.callUpdateMyUserData)

app.post('/updatemyuserdata', verifyPlayer, birthdateFormatValidation, userController.updateMyUserData)

...

</code></pre>



<p><strong>Coach POST endpoints</strong>.  I have 2 endpoints here and each of these endpoint can only be called by Coach users. The <em>&nbsp;verifyCoach</em> middleware is set before the <em>routingHandler</em> function to verify if the user is logged-in and if the users role is <em>coach</em>. </p>



<pre class="wp-block-code"><code>// booking.js
...

// Coach POST endpoints
// Coach Confirmation Management
app.post('/callparticipants', verifyCoach, bookingController.callParticipants)

app.post('/callconfirmpatricipants', verifyCoach, bookingController.callConfirmPatricipants)

...

</code></pre>



<h3 class="wp-block-heading">User logout</h3>



<p>The user initiates a <strong>logout</strong> himself by clicking on the logout link in the navigation of the application. This sends a GET request to the <code>/logout</code> endpoint of the application. In this routing definition, the session is first deleted from the database using <code>req.session.destroy()</code> and then the cookie is removed from the browser and the user is redirected to the <em>200success site</em> using <code>res.status(200).clearCookie('booking').redirect()</code>.</p>



<pre class="wp-block-code"><code>// booking.js

...

// GET logout route only for authenticated users. Anonym users redirected to home
app.get('/logout', redirectLogin, (req, res) =&gt; {
  req.session.destroy(function(err) {
    if (err) {
      res.send('An err occured: ' +err.message);
    } else {
      var message = 'You have been successfully logged out';
      res.status(200).clearCookie('booking').redirect('/200success?message='+message)
    }
  });
})

...

</code></pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Setup Ubuntu Linux ready for Node Apps</title>
		<link>https://digitaldocblog.com/web-development/setup-ubuntu-linux-ready-for-node-apps/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 26 Feb 2021 10:47:00 +0000</pubDate>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Server]]></category>
		<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[NginX]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=122</guid>

					<description><![CDATA[We have a new server in front of us and are now starting from the beginning with the preparation of the system to operate nodejs and node express applications. SSH&#8230;]]></description>
										<content:encoded><![CDATA[
<p>We have a new server in front of us and are now starting from the beginning with the preparation of the system to operate nodejs  and node express applications. </p>



<h2 class="wp-block-heading">SSH public key authentication for the root user</h2>



<p>First we create the ssh keys on the local machine. </p>



<pre class="wp-block-code"><code>PatrickMBNeu:~ patrick$ ssh-keygen -t rsa -b 4096 -C "your_email@domain.com"
Enter file in which to save the key (/home/patrick/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
PatrickMBNeu:~ patrick$ ls -l .ssh/id_*
-rw-------@ 1 patrick  staff  3434  4 Feb 14:58 .ssh/id_rsa
-rw-r--r--  1 patrick  staff   750  4 Feb 14:58 .ssh/id_rsa.pub
PatrickMBNeu:~ patrick$ 
</code></pre>



<p>We log in to the server with the <code>root</code>  user via ssh and are in the root user&#8217;s home directory and create the <code>.ssh</code>  directory and the <code>authorized_keys</code> file. The we log out from the server and install the public key from the local machine on the server. </p>



<pre class="wp-block-code"><code>PatrickMBNeu:~ patrick$ ssh root@85.134.111.90
root@85.134.111.90's password: 
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage
Last login: Fri Feb 19 07:10:43 2021 from 112.11.237.18
root@h2866085:~# ls -al
insgesamt 28
drwx------  3 root root 4096 Feb 19 07:10 .
drwxr-xr-x 23 root root 4096 Feb 19 06:41 ..
-rw-------  1 root root   12 Feb 19 07:10 .bash_history
-rw-r--r--  1 root root 3106 Aug 14  2019 .bashrc
drwx------  2 root root 4096 Feb 19 07:09 .cache
-rw-r--r--  1 root root  148 Aug 13  2020 .profile
-rw-r--r--  1 root root   20 Feb 19 06:37 .screenrc
root@h2866085:~# mkdir .ssh
root@h2866085:~# ls -al
insgesamt 32
drwx------  4 root root 4096 Feb 19 07:20 .
drwxr-xr-x 23 root root 4096 Feb 19 06:41 ..
-rw-------  1 root root   12 Feb 19 07:10 .bash_history
-rw-r--r--  1 root root 3106 Aug 14  2019 .bashrc
drwx------  2 root root 4096 Feb 19 07:09 .cache
-rw-r--r--  1 root root  148 Aug 13  2020 .profile
-rw-r--r--  1 root root   20 Feb 19 06:37 .screenrc
drwxr-xr-x  2 root root 4096 Feb 19 07:20 .ssh
root@h2866085:~# chmod 700 .ssh
root@h2866085:~# ls -al
insgesamt 32
drwx------  4 root root 4096 Feb 19 07:20 .
drwxr-xr-x 23 root root 4096 Feb 19 06:41 ..
-rw-------  1 root root   12 Feb 19 07:10 .bash_history
-rw-r--r--  1 root root 3106 Aug 14  2019 .bashrc
drwx------  2 root root 4096 Feb 19 07:09 .cache
-rw-r--r--  1 root root  148 Aug 13  2020 .profile
-rw-r--r--  1 root root   20 Feb 19 06:37 .screenrc
drwx------  2 root root 4096 Feb 19 07:20 .ssh
root@h2866085:~# cd .ssh
root@h2866085:~/.ssh# touch authorized_keys
root@h2866085:~/.ssh# ls -al
insgesamt 8
drwx------ 2 root root 4096 Feb 19 07:21 .
drwx------ 4 root root 4096 Feb 19 07:20 ..
-rw-r--r-- 1 root root    0 Feb 19 07:21 authorized_keys
root@h2866085:~/.ssh# chmod 600 authorized_keys
root@h2866085:~/.ssh# ls -al
insgesamt 8
drwx------ 2 root root 4096 Feb 19 07:21 .
drwx------ 4 root root 4096 Feb 19 07:20 ..
-rw------- 1 root root    0 Feb 19 07:21 authorized_keys
root@h2866085:~/.ssh# exit
Abgemeldet
Connection to 85.214.161.41 closed.

PatrickMBNeu:~ patrick$
PatrickMBNeu:~ patrick$ cat ~/.ssh/id_rsa.pub | ssh root@85.214.161.41 "cat &gt;&gt; ~/.ssh/authorized_keys"
PatrickMBNeu:~ patrick$ ssh root@85.134.111.90
root@85.214.161.41's password: 
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage
Last login: Fri Feb 19 07:18:57 2021 from 185.17.207.18

root@h2866085:~# cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCfV32OLcC90/0CE0nDsSRZwO5XtyRRBWkgKhkd+wlIad09Vi6URGO3XkUhac2bKWe6t9DP3GWSk23ruMj8M6UV9W1Fb7ZfFW3SXhz5+pRB1v0Uy5PDdxLH1foSz0hpbubCQ0AbEWWRNfMqKC6l2tFWrOfl5AXlbmZsHTH1Th9FSoBhqs8ZH33Oovs+lchzbpmObjUNzr0Y/ZWaNjNlAxvFtt8fMHxqEz3tw7ASub2eaVcGSiNioV3GKwlzbho62AF6b+KGbQkH92P5j4+KnDQpY92Ejd55c4kfq7DcG0pXLC2e77Ci/XnpROzllcOlSjmR5fsAIuWMw7dQyePCar2seVx7WBo0/Z/jnvF0exDJprtxPLlCbFRwj1nVMlKpUsqbE8mZs0L5k7Zh2GLkGJQekYR1X7zDthJHPMLeoepKw20onuCoTkquirwYhy4xCndjZ3VYk0033Rgu13ETrCB+eXc7UrbyyJJyTTs77BQZ/deTLZcXARYU96wQoQGzlevYjyWNhn6WEjkoBc2dcIHzV0Fp3enhLhptG6imHGsvAm+1uNkXbg46hYL4WZdJxkGXOoRo+oT/deRNvzMjDgL2SMUOgSzj7U+Krw0bUCY2LpkWp0lNAuT+YsF2O/k/TEVFBfKthrJd9f/PynTR+IFiRHK7jayhBQXIWSsqI9AlJw== p.rottlaender@icloud.com
root@h2866085:~# 
</code></pre>



<h2 class="wp-block-heading">Ubuntu Version check</h2>



<p>Another action we take is to check which OS version and kernel version we are dealing with. This provides important information when we install software later. Often we have to download special software releases for the Linux version used. Type any of the following commands to find OS Name and OS Version running on your Linux server.</p>



<pre class="wp-block-code"><code>root@h2866085:~$ cat /etc/os-release

NAME="Ubuntu"
VERSION="18.04.5 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.5 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

root@h2866085:~$ lsb_release -a

No LSB modules are available.
Distributor ID:    Ubuntu
Description:    Ubuntu 18.04.5 LTS
Release:    18.04
Codename:    bionic

root@h2866085:~$
</code></pre>



<p>To print the Linux kernel version running on your server type the following command. I am running Linux kernel version 4.15.</p>



<pre class="wp-block-code"><code>root@h2866085:~$ uname -r
4.15.0
root@h2866085:~$
</code></pre>



<h2 class="wp-block-heading">Create a user</h2>



<p>Of course, we don&#8217;t want to log in to the system with the root user all the time. It is therefore advisable to create another user with whom we can then log in and work.</p>



<p>A user can be created in Ubuntu Linux with the command <code>useradd</code> or <code>adduser</code>. I use the <code>adduser</code> command because with this perl script, in addition to creating the user in <code>/etc/passwd</code> and creating a dedicated user group in <code>/etc/group</code>, the home directory in <code>/home</code> is also created for that user and default files are copied from <code>/etc/skel</code> if necessary.</p>



<p>As root run the command <code>adduser mynewuser</code>.</p>



<pre class="wp-block-code"><code>root@h2866085:~$ adduser mynewuser

Benutzer »mynewuser« wird hinzugefügt …
Neue Gruppe »mynewuser« (1001) wird hinzugefügt …
Neuer Benutzer »mynewuser« (1001) mit Gruppe »mynewuser« wird hinzugefügt …
Persönliche Ordner »/home/mynewuser« wird erstellt …
Dateien werden von »/etc/skel« kopiert …
Geben Sie ein neues UNIX-Passwort ein: 
Geben Sie das neue UNIX-Passwort erneut ein: 
passwd: password updated successfully
Changing the user information for mynewuser
Enter the new value, or press ENTER for the default
    Full Name &#91;]: Tech User
    Room Number &#91;]: 
    Work Phone &#91;]: 
    Home Phone &#91;]: 
    Other &#91;]: This user is only for tech 
Ist diese Information richtig? &#91;J/N] J

root@h2866085:~$
</code></pre>



<p>This create the user <code>mynewuser</code>. In <code>/etc/passwd</code> you see that the user has been created with userID (1000) and a groupID (1000). In <code>/etc/group</code> you find the new group <code>mynewuser</code>. When you check the home directory you find the new home directory in <code>/home/mynewuser</code>. </p>



<pre class="wp-block-code"><code>root@h2866085:~$ grep mynewuser /etc/passwd
mynewuser:x:1000:1000::/home/mynewuser:/bin/bash
root@h2866085:~$ cat /etc/group
....
....
mynewuser:x:1000:
...
root@h2866085:~$ ls -l /home
drwxr-xr-x 2 mynewuser mynewuser 4096 Jan 23 05:31 mynewuser
root@h2866085:~$
</code></pre>



<p>The last entry in the <code>/etc/passwd</code> specifies the shell of the new user. Here the newly created user has the Bash shell. In general a Unix shell is a command processor running in a command line window. The user types commands and these commands will be executed and cause actions. For more details you can read the wiki article about <a href="https://en.wikipedia.org/wiki/Unix_shell">Unix Shells</a>.<br></p>



<p>Because there are some different shells available there might be the need to change the user&#8217;s shell which basically mean that you change the variety of available commands on your command line. To change the shell of a user type  <code>usermod --shell &lt;/path/toShell&gt; &lt;mynewuser&gt;</code>. To see which shells you can use pls. check the <code>/etc/shells</code> directory. </p>



<pre class="wp-block-code"><code>root@h2866085:~$ ls -l /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/dash
/bin/bash
/bin/rbash
/usr/bin/screen
/bin/tcsh
/usr/bin/tcsh
root@h2866085:~$ usermod --shell /bin/sh mynewuser
root@h2866085:~$ grep mynewuser /etc/passwd
mynewuser:x:1001:1001:Tech User,,,,This user is only for tech:/home/mynewuser:/bin/sh
</code></pre>



<h2 class="wp-block-heading">Sudo configuration</h2>



<p>This newly created user can create files in his home directory and access those files. However, it cannot copy files to directories owned by root. To demonstrate this, I log in to the system with the newly generated user. I create a file in the home directory and then I try to copy this file into a directory owned by root. The error message is that I am not authorized. To do this copy you must be root. </p>



<p>A user can still execute commands as root. That&#8217;s why there is sudo. So when I try to execute the command with sudo I get the message that the user is not in the sudoers-file.</p>



<pre class="wp-block-code"><code>Patricks-MacBook-Pro:~$ ssh mynewuser@85.214.161.41
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage
Last login: Fri Feb  5 08:57:52 2021 from 87.161.105.46
mynewuser@h2866085:~$  touch testfile
mynewuser@h2866085:~$ ls -l
insgesamt 4
-rw-rw-r-- 1 mynewuser mynewuser 24 Jan 23 06:20 testfile
mynewuser@h2866085:~$ cp testfile /etc/nginx/sites-available/testfile
cp: reguläre Datei '/etc/nginx/sites-available/testfile' kann nicht angelegt werden: Keine Berechtigung
mynewuser@h2866085:~$ sudo cp testfile /etc/nginx/sites-available/testfile
&#91;sudo] Passwort für mynewuser: 
mynewuser ist nicht in der sudoers-Datei. Dieser Vorfall wird gemeldet.
mynewuser@h2866085:~$
</code></pre>



<p>Sudo allows the <code>root</code> user of the system to give other users on the system (or groups) the ability to run some (or all) commands as <code>root</code>. The sudo configuration is detailed in <code>/etc/sudoers</code> file. </p>



<p>In my sudo configuration file it is already preconfigured that all users in the sudo group can execute all commands as <code>root</code>.  Please note the corresponding entry <code>%sudo ALL=(ALL:ALL) ALL</code> in the <code>/etc/sudoers</code> configuration file below. </p>



<p>I want that the the user <code>mynewuser</code> should be able to execute all commands as <code>root</code>. Therefore <code>mynewuser</code> must be added to the <code>sudo</code> group. </p>



<p>To make <code>mynewuser</code> a member of the <code>sudo</code> group I use the command <code>usermod</code>.  Therefore I log in with <code>root</code> using the <code>su root</code> command. Then I run <code>usermod</code> with <code>-a</code> and <code>-G</code> option, which basically says to append a user to a Group. </p>



<p>Finally I check with <code>cat /etc/group</code> that the sudo group contain the <code>mynewuser</code> and logoff from the root account using <code>exit</code>.</p>



<pre class="wp-block-code"><code>mynewuser@h2866085:~$ su root
Passwort: 
root@h2866085:/home/mynewuser# 
root@h2866085:/home/mynewuser# cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo    ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

root@h2866085:/home/mynewuser# usermod -a -G sudo mynewuser
root@h2866085:/home/patrick# cat /etc/group
root:x:0:
daemon:x:1:
bin:x:2:
...
sudo:x:27:mynewuser
....
root@h2866085:/home/patrick# exit
mynewuser@h2866085:~$
</code></pre>



<h2 class="wp-block-heading">Advanced Package Tool on Ubuntu Linux</h2>



<p>But before we start with software installations I need to give you some background info about Ubuntu or Debian package management. </p>



<p>Whenever you want to install software on your Ubuntu system, you can use the Advanced Package Tool or APT for short. Users interact with APT using the <code>apt</code> command. APT download the software package from a package source and then install it. </p>



<p>The software package can only be installed if the package source is known to the APT system. Therefore package sources are listed in the file <code>/etc/apt/sources.list</code> or in further files with the extension <code>.list</code> in the directory  <code>/etc/apt/sources.list.d</code>. </p>



<p>When you call <code>apt install &lt;package-name&gt;</code> on your console APT first check the package sources listed in your <code>/etc/apt/sources.list</code> file. When the system find the package on one of these package sources APT will install the software from there. </p>



<p>When the software is not available on any package sources listed in <code>/etc/apt/sources.list</code> APT check the package sources listed in the <code>.list</code>  files in your <code>/etc/apt/sources.list.d</code> directory. </p>



<p>When APT does not find the package on any package sources the software package cannot be installed until the package source is entered either in <code>/etc/apt/sources.list</code> or in a separate <code>.list</code> file in the <code>/etc/apt/sources.list.d</code> directory.</p>



<p>The entries in <code>.list</code> files regardless of whether they are in <code>/etc/apt/sources.list</code> or  <code>/etc/apt/sources.list.d/*.list</code> are structured identically. The structure of the <code>.list</code> files is divided into 4 sections. </p>



<pre class="wp-block-code"><code>Example:
deb    ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic     main restricted universe
&lt;type&gt; &lt;URI&gt;                                       &lt;archive&gt;  &lt;component&gt;
</code></pre>



<p>The above listed package source is an ftp server that contain binary packages for the Ubuntu Bionic Distribution (bionic). The Binary Packages include packages that meet the Ubuntu licensing requirements and are supported by the Ubuntu team (main), software packages that the Ubuntu developers support because of their importance, but which are not under Ubuntu licensing (restricted) and a wide range of free software (no licensing restrictions) that is not officially supported by Ubuntu (universe). </p>



<p>Universe software is maintained by the <a href="https://wiki.ubuntu.com/MOTU">Masters of the Universe</a> (MOTU Developers).  If a MOTU Developer want a software to be included in the Ubuntu package sources, this Developer must suggest the package for the Universe. MOTUs also maintain Multiverse software. Multiverse software is also managed by the MOTUs but the difference is that Multiverse software is not free Software. Multiverse software is subject to licensing restrictions. More details can be read in the <a href="https://ubuntu.com/server/docs/package-management">Ubuntu Package Management Documentation</a> on the Ubuntu Website.<br></p>



<p>The <code>.list</code> file can be crated manually using an editor like <code>nano</code> or with the following command. Here in this example to create a mongoDB source file.</p>



<pre class="wp-block-code"><code>echo "deb &#91; arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
</code></pre>



<p>In order to check a package source for authenticity, the GPG key of the package source provided by the manufacturer must also be downloaded and added to the Ubuntu APT keyring using the <code>apt-key add</code> command. Here in this example to add the key to verify the mongoDB source. </p>



<pre class="wp-block-code"><code>wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
</code></pre>



<p>With <code>wget</code> I download the public key from the mongodb.org server and pipe it into the <code>apt-key add</code> command which finally add the key to the keyring.</p>



<p>Alternatively you can use the <code>add-apt-repository</code> utility or script to automate package source entries in your <code>/etc/apt/sources.list</code> file. From Debian 8 on  <code>add-apt-repository</code> is part of the Debian Package <code>software-properties-common</code> which must be installed in case you want to use this utility for your package source management.</p>



<pre class="wp-block-code"><code>apt-get update
apt-get install software-properties-common
</code></pre>



<p>Using <code>add-apt-repository</code> the package source will be appended to the <code>/etc/apt/sources.list</code>file. No separate file will be created in <code>/etc/apt/sources.list.d</code> directory. Here is the example how to add the package source for the mongoDB. </p>



<pre class="wp-block-code"><code>sudo add-apt-repository 'deb &#91;arch=amd64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse'
</code></pre>



<p>The utility <code>add-apt-repository</code> can also be used to install software from Personal Package Archives (PPA). PPAs are a special service for MOTU Developers (<a href="https://wiki.ubuntu.com/MOTU">Masters of the Universe</a>) to provide Ubuntu packages that are built and published with <a href="https://launchpad.net">Launchpad</a>. When you use <code>add-apt-repository</code> to install a PPA a new <code>.list</code> file will be created in your <code>/etc/apt/sources.list.d</code> directory. </p>



<pre class="wp-block-code"><code>add-apt-repository ppa:user/ppa-name
</code></pre>



<p>When you use <code>add-apt-repository</code> the PPA&#8217;s key is automatically fetched and added to the keyring. You can read more about PPA packaging on the <a href="https://help.launchpad.net/Packaging/PPA">launchpad help page</a>.</p>



<p>You should not use PPA software in production environments. The reason is that PPA software is often not maintained regularly by the MOTUs on launchpad. In general MOTUs publish their first versions on launchpad and then integrate them into the main Ubuntu Universe or Multiverse sources. So read the documentation and if possible try to install your production packages from main sources. You can see this in the following example when I install nodejs and npm from a main source. </p>



<h2 class="wp-block-heading">Nodejs and NPM Installation</h2>



<p>To run a node application you definitely need the node platform nodejs and the node package manager npm. </p>



<p>Go to the <a href="https://nodejs.org/en/download/">nodejs.org download page</a> to find out the latest version of node to install. I recommend to install the latest LTS version (<a href="https://nodejs.org/en/about/releases/">Long Term Support</a>) which is at the time of writing this document node version 14.15.5 including npm in version 6.14.11. </p>



<p>When you scroll down on the nodejs.org download page you see the install options. I prefer to install <a href="https://nodejs.org/en/download/package-manager/">nodejs via package manager</a>. Here you select your distribution so I select Debian and Ubuntu based Linux distributions. The nodejs binaries are available on <a href="https://github.com/nodesource/distributions/blob/master/README.md">GitHub nodesource repository</a>.  I choose Debian and Ubuntu based distributions (deb) <a href="https://github.com/nodesource/distributions/blob/master/README.md#debmanual">manual installation</a>.<br></p>



<p>Since I did not installed nodejs via PPA before I can skip the first step described here in the documentation. So I start with the import of the package signing key to ensure that apt can verify the new node source.</p>



<pre class="wp-block-code"><code>$ wget --quiet -O - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
</code></pre>



<p>The key ID at the time of writing this document is <code>1655A0AB68576280</code>.</p>



<p>You can check the imported key using the apt-key command.</p>



<pre class="wp-block-code"><code>$ sudo apt-key fingerprint ABF5BD827BD9BF62
</code></pre>



<p>The output should be.</p>



<pre class="wp-block-code"><code>pub   rsa4096 2014-06-13 &#91;SC]
      9FD3 B784 BC1C 6FC3 1A8A  0A1C 1655 A0AB 6857 6280
uid        &#91; unbekannt] NodeSource &lt;gpg@nodesource.com&gt;
sub   rsa4096 2014-06-13 &#91;E]
</code></pre>



<p>Then I create the <code>nodesource.list</code> file in my  <code>/etc/apt/sources.list.d</code> directory to make the nodejs package source known to apt. I create 2 entries in that file one for the nodejs debian binaries (deb) and one for the nodejs sources (deb-src).</p>



<pre class="wp-block-code"><code># Replace $VERSION with Node.js Version you want to install: i.e. node_14.x
# $VERSION=node_14.x
# Replace $DISTRO with the output of the command lsb_release -s -c
# $DISTRO=bionic
$ echo "deb https://deb.nodesource.com/$VERSION $DISTRO main" | sudo tee /etc/apt/sources.list.d/nodesource.list
$ echo "deb-src https://deb.nodesource.com/$VERSION $DISTRO main" | sudo tee -a /etc/apt/sources.list.d/nodesource.list
</code></pre>



<p>Then I update the source package list and install.</p>



<pre class="wp-block-code"><code>$ sudo apt-get update
$ sudo apt-get install nodejs
</code></pre>



<p>Here is my manual installation.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/apt$ ls -l sources.list.d
insgesamt 0
patrick@h2866085:/etc/apt$ apt-key list
/etc/apt/trusted.gpg.d/ubuntu-keyring-2012-archive.gpg
------------------------------------------------------
pub   rsa4096 2012-05-11 &#91;SC]
      790B C727 7767 219C 42C8  6F93 3B4F E6AC C0B2 1F32
uid        &#91; unbekannt] Ubuntu Archive Automatic Signing Key (2012) &lt;ftpmaster@ubuntu.com&gt;

/etc/apt/trusted.gpg.d/ubuntu-keyring-2012-cdimage.gpg
------------------------------------------------------
pub   rsa4096 2012-05-11 &#91;SC]
      8439 38DF 228D 22F7 B374  2BC0 D94A A3F0 EFE2 1092
uid        &#91; unbekannt] Ubuntu CD Image Automatic Signing Key (2012) &lt;cdimage@ubuntu.com&gt;

/etc/apt/trusted.gpg.d/ubuntu-keyring-2018-archive.gpg
------------------------------------------------------
pub   rsa4096 2018-09-17 &#91;SC]
      F6EC B376 2474 EDA9 D21B  7022 8719 20D1 991B C93C
uid        &#91; unbekannt] Ubuntu Archive Automatic Signing Key (2018) &lt;ftpmaster@ubuntu.com&gt;

patrick@h2866085:~$ sudo wget --quiet -O - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -
&#91;sudo] Passwort für patrick: 
OK
patrick@h2866085:~$ apt-key list
/etc/apt/trusted.gpg
--------------------
pub   rsa4096 2014-06-13 &#91;SC]
      9FD3 B784 BC1C 6FC3 1A8A  0A1C 1655 A0AB 6857 6280
uid        &#91; unbekannt] NodeSource &lt;gpg@nodesource.com&gt;
sub   rsa4096 2014-06-13 &#91;E]

/etc/apt/trusted.gpg.d/ubuntu-keyring-2012-archive.gpg
------------------------------------------------------
pub   rsa4096 2012-05-11 &#91;SC]
      790B C727 7767 219C 42C8  6F93 3B4F E6AC C0B2 1F32
uid        &#91; unbekannt] Ubuntu Archive Automatic Signing Key (2012) &lt;ftpmaster@ubuntu.com&gt;

/etc/apt/trusted.gpg.d/ubuntu-keyring-2012-cdimage.gpg
------------------------------------------------------
pub   rsa4096 2012-05-11 &#91;SC]
      8439 38DF 228D 22F7 B374  2BC0 D94A A3F0 EFE2 1092
uid        &#91; unbekannt] Ubuntu CD Image Automatic Signing Key (2012) &lt;cdimage@ubuntu.com&gt;

/etc/apt/trusted.gpg.d/ubuntu-keyring-2018-archive.gpg
------------------------------------------------------
pub   rsa4096 2018-09-17 &#91;SC]
      F6EC B376 2474 EDA9 D21B  7022 8719 20D1 991B C93C
uid        &#91; unbekannt] Ubuntu Archive Automatic Signing Key (2018) &lt;ftpmaster@ubuntu.com&gt;

patrick@h2866085:~$ sudo apt-key fingerprint 1655A0AB68576280
pub   rsa4096 2014-06-13 &#91;SC]
      9FD3 B784 BC1C 6FC3 1A8A  0A1C 1655 A0AB 6857 6280
uid        &#91; unbekannt] NodeSource &lt;gpg@nodesource.com&gt;
sub   rsa4096 2014-06-13 &#91;E]

patrick@h2866085:~$ lsb_release -s -c
bionic
patrick@h2866085:~$ sudo echo "deb https://deb.nodesource.com/node_14.x bionic main" | sudo tee /etc/apt/sources.list.d/nodesource.list
deb https://deb.nodesource.com/node_14.x bionic main
patrick@h2866085:~$ sudo echo "deb-src https://deb.nodesource.com/node_14.x bionic main" | sudo tee -a /etc/apt/sources.list.d/nodesource.list
deb-src https://deb.nodesource.com/node_14.x bionic main
patrick@h2866085:~$ ls -l /etc/apt/sources.list.d
insgesamt 4
-rw-r--r-- 1 root root 110 Feb 20 08:14 nodesource.list
patrick@h2866085:~$ sudo cat /etc/apt/sources.list.d/nodesource.list
deb https://deb.nodesource.com/node_14.x bionic main
deb-src https://deb.nodesource.com/node_14.x bionic main
patrick@h2866085:~$ sudo apt-get update
OK:1 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic InRelease
Holen:2 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-updates InRelease &#91;88,7 kB]
Holen:3 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-security InRelease &#91;88,7 kB]
Holen:4 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic/main Translation-de &#91;454 kB]
Holen:5 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic/restricted Translation-de &#91;2.268 B]
Holen:6 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic/universe Translation-de &#91;2.272 kB]                       
Holen:7 https://deb.nodesource.com/node_14.x bionic InRelease &#91;4.584 B]                                                  
Holen:8 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-updates/universe Sources &#91;446 kB]
Holen:9 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-updates/main amd64 Packages &#91;1.885 kB]
Holen:10 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-updates/universe amd64 Packages &#91;1.718 kB]
Holen:11 https://deb.nodesource.com/node_14.x bionic/main amd64 Packages &#91;764 B]
Holen:12 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-updates/universe Translation-en &#91;363 kB]
Holen:13 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-security/universe Sources &#91;277 kB]
Holen:14 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-security/universe amd64 Packages &#91;1.109 kB]
Holen:15 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-security/universe Translation-en &#91;248 kB]
Es wurden 8.957 kB in 3 s geholt (3.459 kB/s).                    
Paketlisten werden gelesen... Fertig
patrick@h2866085:~$ sudo apt-get install nodejs
patrick@h2866085:~$ node -v
v14.15.5
patrick@h2866085:~$ npm -v
6.14.11
patrick@h2866085:~$ 
</code></pre>



<p>Basically we installed npm in a bundle together with nodejs using the  <code>apt</code> package manager. But npm itself is also an additional package manager. We now have <code>apt</code> and <code>npm</code> as package managers on our system. </p>



<p>We need npm to have an additional source for software available on <a href="https://www.npmjs.com/">npmjs.com</a>.  We will for example install PM2 via npm (see next chapter) but but in particular we need npm to add local software packages or dependencies to our node application projects. So when we want to develop a node app based on the expressjs framework we will install express locally in our project directory. But this will be part of a separate tutorial. </p>



<p>When you ask npm to find outdated packages you can run the <code>npm outdated</code> command (using the -g option to show only global packages). </p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ npm outdated -g --depth=0
Package  Current   Wanted  Latest  Location
npm      6.14.11  6.14.11   7.5.4  global
</code></pre>



<p>As you see from an npm point of view the latest version of npm is 7.5.4. But npm know that we installed npm together as a bundle with nodejs via <code>apt</code> and in the apt package sources we say that our wanted version is 14.15.5 (see above). This is a bit confusing but basically <code>npm outdated</code> tell us that that there is a higher npm version available (latest) but on our system we are up to date as the current version and the one we defined in our package sources (wanted) are equal. </p>



<p>We can update npm together only together with the nodejs update which must be initiated with <code>apt-update</code>. And here you see the packages are all up to date.</p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ sudo apt update
OK:1 https://deb.nodesource.com/node_14.x bionic InRelease
OK:2 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic InRelease
OK:3 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-updates InRelease
OK:4 ftp://ftp.stratoserver.net/pub/linux/ubuntu bionic-security InRelease
Paketlisten werden gelesen... Fertig
Abhängigkeitsbaum wird aufgebaut.       
Statusinformationen werden eingelesen.... Fertig
Alle Pakete sind aktuell.
patrick@h2866085:~$  
</code></pre>



<h2 class="wp-block-heading">PM2 Installation with NPM</h2>



<p>Go to <a href="https://www.npmjs.com/">npmjs.com</a> and search for PM2 Process Manager. You find the <a href="https://www.npmjs.com/package/pm2">PM2 package</a> on npmjs.com. Follow the install instructions.</p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ sudo npm install pm2 -g
patrick@h2866085:~$ pm2 -v
                        -------------

__/\\\\\\\\\\\\\____/\\\\____________/\\\\____/\\\\\\\\\_____
 _\/\\\/////////\\\_\/\\\\\\________/\\\\\\__/\\\///////\\\___
  _\/\\\_______\/\\\_\/\\\//\\\____/\\\//\\\_\///______\//\\\__
   _\/\\\\\\\\\\\\\/__\/\\\\///\\\/\\\/_\/\\\___________/\\\/___
    _\/\\\/////////____\/\\\__\///\\\/___\/\\\________/\\\//_____
     _\/\\\_____________\/\\\____\///_____\/\\\_____/\\\//________
      _\/\\\_____________\/\\\_____________\/\\\___/\\\/___________
       _\/\\\_____________\/\\\_____________\/\\\__/\\\\\\\\\\\\\\\_
        _\///______________\///______________\///__\///////////////__

                          Runtime Edition

        PM2 is a Production Process Manager for Node.js applications
                     with a built-in Load Balancer.

                Start and Daemonize any application:
                $ pm2 start app.js

                Load Balance 4 instances of api.js:
                $ pm2 start api.js -i 4

                Monitor in production:
                $ pm2 monitor

                Make pm2 auto-boot at server restart:
                $ pm2 startup

                To go further checkout:
                http:&#47;&#47;pm2.io/
                        -------------
&#91;PM2] Spawning PM2 daemon with pm2_home=/home/patrick/.pm2
&#91;PM2] PM2 Successfully daemonized
4.5.4
patrick@h2866085:~$ 
</code></pre>



<h2 class="wp-block-heading">Nano Installation with apt</h2>



<p>Nano is part of the Ubuntu 18.04 bionic main packages that are provided via the standard ftp package sources from my provider at stratoserver.net. These standard ftp package sources are in my <code>/etc/apt/sources.list</code> file and can be installed with <code>apt</code>. </p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ sudo apt install nano
patrick@h2866085:~$
</code></pre>



<h2 class="wp-block-heading">Nginx Installation with apt</h2>



<p>Also Nginx is a package that is available under the standard Ubuntu main sources. Nginx is part of the Ubuntu 18.04 bionic main packages provided via the standard ftp package sources from my provider at stratoserver.net. Nginx can be installed from these sources using the <code>apt</code> command. </p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ sudo apt install nginx
patrick@h2866085:~$
</code></pre>



<p>After the installation is complete the Nginx configuration files are in <code>/etc/nginx</code> directory.<br></p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ ls -l /etc/nginx
insgesamt 64
drwxr-xr-x 2 root root 4096 Jan 10  2020 conf.d
-rw-r--r-- 1 root root 1077 Apr  6  2018 fastcgi.conf
-rw-r--r-- 1 root root 1007 Apr  6  2018 fastcgi_params
-rw-r--r-- 1 root root 2837 Apr  6  2018 koi-utf
-rw-r--r-- 1 root root 2223 Apr  6  2018 koi-win
-rw-r--r-- 1 root root 3957 Apr  6  2018 mime.types
drwxr-xr-x 2 root root 4096 Jan 10  2020 modules-available
drwxr-xr-x 2 root root 4096 Feb 20 12:46 modules-enabled
-rw-r--r-- 1 root root 1482 Apr  6  2018 nginx.conf
-rw-r--r-- 1 root root  180 Apr  6  2018 proxy_params
-rw-r--r-- 1 root root  636 Apr  6  2018 scgi_params
drwxr-xr-x 2 root root 4096 Feb 20 12:46 sites-available
drwxr-xr-x 2 root root 4096 Feb 20 12:46 sites-enabled
drwxr-xr-x 2 root root 4096 Feb 20 12:46 snippets
-rw-r--r-- 1 root root  664 Apr  6  2018 uwsgi_params
-rw-r--r-- 1 root root 3071 Apr  6  2018 win-utf
patrick@h2866085:~$ 
</code></pre>



<p>Then I edit the <code>/etc/nginx.conf</code> as follows.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx$ sudo cat nginx.conf
##
# nginx.conf
##

user www-data; 
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
worker_connections 768;
}

http {

##
# Basic Settings
##

sendfile on;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 2048;

include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Timeout Settings
##
keepalive_timeout  30s; 
keepalive_requests 30;
send_timeout       30s;
##
# SSL Settings
##

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;

##
# Gzip Settings
##

gzip on;
gzip_vary on;
gzip_comp_level 2;
gzip_min_length  1000;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_disable "MSIE &#91;4-6] \."; 
##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

patrick@h2866085:/etc/nginx$
</code></pre>



<p>In the directory <code>/etc/nginx/sites-available</code> you find the sever configuration files and in <code>/etc/nginx/sites-enabled</code> you find the sym links to the sever configuration files that are enabled on your nginx server. </p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx$ ls -l sites-available
insgesamt 4
-rw-r--r-- 1 root root 2416 Apr  6  2018 default
patrick@h2866085:/etc/nginx$ ls -l sites-enabled
insgesamt 0
lrwxrwxrwx 1 root root 34 Feb 20 12:46 default -&gt; /etc/nginx/sites-available/default
patrick@h2866085:/etc/nginx$ 
</code></pre>



<p>First we deactivate the default site by removing the default symlink in <code>/etc/nginx/sites-enabled</code>. </p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx$ cd sites-enabled
patrick@h2866085:/etc/nginx/sites-enabled$ ls -l
insgesamt 0
lrwxrwxrwx 1 root root 34 Feb 20 12:46 default -&gt; /etc/nginx/sites-available/default
patrick@h2866085:/etc/nginx/sites-enabled$ sudo unlink default
&#91;sudo] Passwort für patrick: 
patrick@h2866085:/etc/nginx/sites-enabled$ ls -l
insgesamt 0
patrick@h2866085:/etc/nginx/sites-enabled$ 
</code></pre>



<p>I want to use my nginx server as reverse proxy server for node application servers running on the localhost. Therefore I create a new file <code>prod-reverse-proxy</code> in the directory <code>sites-available</code> .</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx/sites-enabled$ cd ..
patrick@h2866085:/etc/nginx$ 
patrick@h2866085:/etc/nginx$ cd sites-available
patrick@h2866085:/etc/nginx/sites-available$ ls -l
insgesamt 4
-rw-r--r-- 1 root root 2416 Apr  6  2018 default
patrick@h2866085:/etc/nginx/sites-available$ sudo touch prod-reverse-proxy
patrick@h2866085:/etc/nginx/sites-available$ ls -l
insgesamt 4
-rw-r--r-- 1 root root 2416 Apr  6  2018 default
-rw-r--r-- 1 root root    0 Feb 21 08:31 prod-reverse-proxy
patrick@h2866085:/etc/nginx/sites-available$ 
</code></pre>



<p>Then I put the following content in the file <code>prod-reverse-proxy</code> and link this file into <code>/etc/nginx/sites-enabled</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx/sites-available$ sudo nano prod-reverse-proxy
server {
        listen 80;
        listen &#91;::]:80;
        server_name digitaldocblog.com www.digitaldocblog.com;

        access_log /var/log/nginx/prod-reverse-access.log;
        error_log /var/log/nginx/prod-reverse-error.log;

        location / {

	proxy_set_header HOST $host;
</code></pre>



<p>proxy_set_header X-Forwarded-Proto $scheme;</p>



<p>proxy_set_header X-Real-IP $remote_addr;</p>



<p>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;</p>



<p></p>



<pre class="wp-block-code"><code>	proxy_pass http://127.0.0.1:3000;


  }
}
patrick@h2866085:/etc/nginx/sites-available$ sudo ln -s /etc/nginx/sites-available/prod-reverse-proxy /etc/nginx/sites-enabled/prod-reverse-proxy
patrick@h2866085:/etc/nginx/sites-available$ cd ..
patrick@h2866085:/etc/nginx$ ls -l sites-enabled
insgesamt 0
lrwxrwxrwx 1 root root 50 Feb 21 08:37 prod-reverse-proxy -&gt; /etc/nginx/sites-available/prod-reverse-proxy
patrick@h2866085:/etc/nginx$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
patrick@h2866085:/etc/nginx$ 
</code></pre>



<p>The production proxy server is running under the domain server names <strong>digitaldocblog.com</strong> and <strong>www.digitaldocblog.com</strong> and is listening on <strong>localhost port 80</strong>. This production proxy server pass all HTTP traffic from port 80 to a server running on localhost port 3000 (127.0.0.1:3000). Nginx configuration test was tested successful after using <code>nginx -t</code>. </p>



<p>The following commands can be used to check, start and stop the nginx server.</p>



<pre class="wp-block-code"><code>sudo systemctl status nginx

sudo systemctl start nginx 

sudo systemctl stop nginx 

sudo systemctl restart nginx
</code></pre>



<p>I restart the nginx server and then check the status. The basic configuration is now complete.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx$ sudo systemctl restart nginx
patrick@h2866085:/etc/nginx$ sudo systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2021-02-21 08:53:31 CET; 9s ago
     Docs: man:nginx(8)
  Process: 29759 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 29761 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 29760 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 29762 (nginx)
    Tasks: 5 (limit: 60)
   CGroup: /system.slice/nginx.service
           ├─29762 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           ├─29763 nginx: worker process
           ├─29764 nginx: worker process
           ├─29765 nginx: worker process
           └─29766 nginx: worker process

Feb 21 08:53:31 h2866085.stratoserver.net systemd&#91;1]: Starting A high performance web server and a reverse proxy server...
Feb 21 08:53:31 h2866085.stratoserver.net systemd&#91;1]: Started A high performance web server and a reverse proxy server.
patrick@h2866085:/etc/nginx$ 
</code></pre>



<h2 class="wp-block-heading">Letsencrypt SSL Certificate</h2>



<p>To run your server with HTTPS you must install a certificate from an official Centification Authority (CA). <a href="https://letsencrypt.org/">Letsencrypt</a> is such a CA where you can get free certificates. Letsencrypt recommends the use of <a href="https://certbot.eff.org/">certbot</a> for easy creation and management of domain certificates.</p>



<p>On the certbot site you can select the webserver and your operating system. I choose nginx and Ubuntu 18.04 LTS bionic and get to a website with the <a href="https://certbot.eff.org/lets-encrypt/ubuntubionic-nginx">install instructions</a>. Since I am not interested in installing certbot with snap, I choose alternate installation instructions and get to the website with the install instructions of the <a href="https://certbot.eff.org/docs/install.html#operating-system-packages">operating system packages</a>.</p>



<p>I must Install certbot and the certbot nginx plugin with <code>apt</code>.</p>



<pre class="wp-block-code"><code>$ sudo apt update
$ sudo apt-get install certbot
$ sudo apt-get install python-certbot-nginx
</code></pre>



<p>Then I run <code>certbot</code> <code>--``nginx</code> to request the letsencrypt certificate for my domain and domain servers.</p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ sudo certbot --nginx
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): p.rottlaender@icloud.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https:&#47;&#47;acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: digitaldocblog.com
2: www.digitaldocblog.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for digitaldocblog.com
http-01 challenge for www.digitaldocblog.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/prod-reverse-proxy
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/prod-reverse-proxy

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number &#91;1-2] then &#91;enter] (press 'c' to cancel): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/prod-reverse-proxy
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/prod-reverse-proxy

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://digitaldocblog.com and
https://www.digitaldocblog.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=digitaldocblog.com
https://www.ssllabs.com/ssltest/analyze.html?d=www.digitaldocblog.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/digitaldocblog.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/digitaldocblog.com/privkey.pem
   Your cert will expire on 2021-05-24. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

patrick@h2866085:~$ 
</code></pre>



<p>Then I check the new directory and the files in <code>/etc/letsencrypt</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/letsencrypt$ sudo ls -l live
insgesamt 4
drwxr-xr-x 2 root root 4096 Feb 23 06:33 digitaldocblog.com
patrick@h2866085:/etc/letsencrypt$ sudo ls -l live/digitaldocblog.com
insgesamt 4
lrwxrwxrwx 1 root root  42 Feb 23 06:33 cert.pem -&gt; ../../archive/digitaldocblog.com/cert1.pem
lrwxrwxrwx 1 root root  43 Feb 23 06:33 chain.pem -&gt; ../../archive/digitaldocblog.com/chain1.pem
lrwxrwxrwx 1 root root  47 Feb 23 06:33 fullchain.pem -&gt; ../../archive/digitaldocblog.com/fullchain1.pem
lrwxrwxrwx 1 root root  45 Feb 23 06:33 privkey.pem -&gt; ../../archive/digitaldocblog.com/privkey1.pem
-rw-r--r-- 1 root root 682 Feb 23 06:33 README
patrick@h2866085:/etc/letsencrypt$ 
</code></pre>



<p>I also check the file <code>prod-reverse-proxy</code> in the directory <code>/etc/nginx/sites-available</code> and see that the file has been updated by certbot. There is a new server section defined (first) an this server is now listening to port 443 ssl and the links to the ssl certificates has been added. The original server section (second) has been changed so that all traffic for hosts <strong>digitaldocblog.com</strong> and <strong>www.digitaldocblog.com</strong> will be redirected to the https version of the site (<code>return 301 https://$host$request_uri&#x1f609;</code> and requests to port 80 will be answered with 404 site not found. </p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ cd /etc/nginx/sites-available
patrick@h2866085:/etc/nginx/sites-available$ ls -l
insgesamt 12
-rw-r--r-- 1 root root 2416 Apr  6  2018 default
-rw-r--r-- 1 root root 1089 Feb 23 06:34 prod-reverse-proxy

patrick@h2866085:/etc/nginx/sites-available$ sudo cat prod-reverse-proxy
server {
server_name digitaldocblog.com www.digitaldocblog.com;

        access_log /var/log/nginx/prod-reverse-access.log;
        error_log /var/log/nginx/prod-reverse-error.log;

        location / {

	proxy_set_header HOST $host;
</code></pre>



<p>proxy_set_header X-Forwarded-Proto $scheme;</p>



<p>proxy_set_header X-Real-IP $remote_addr;</p>



<p>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;</p>



<pre class="wp-block-code"><code>	proxy_pass http://127.0.0.1:3000;


  }
    listen &#91;::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/digitaldocblog.com/fullchain.pem; # managed by Certbot
      ssl_certificate_key /etc/letsencrypt/live/digitaldocblog.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {

    if ($host = www.digitaldocblog.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = digitaldocblog.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen &#91;::]:80;
        server_name digitaldocblog.com www.digitaldocblog.com;
        return 404; # managed by Certbot
}

patrick@h2866085:/etc/nginx/sites-available$ 
</code></pre>



<p>To renew all certificates I must run the following command.</p>



<pre class="wp-block-code"><code>$ certbot renew
</code></pre>



<p>To renew all certificates automatically I attach the following line to my system crontab. </p>



<pre class="wp-block-code"><code>40 6 * * * root /usr/bin/certbot renew &gt; certrenew_log
</code></pre>



<p>The <code>certbot renew</code> command in this example run daily at 6:40 am (in the morning) as <code>root</code> and log the output in the logfile <code>certrenew_log</code> in the home directory of <code>root</code>. The command checks to see if the certificate on the server will expire within the next 30 days, and renews it if so.</p>



<p>Therefore you must edit the <code>/etc/crontab</code> file as follows. </p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc$ sudo nano crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
15 * * * * root cd / &amp;&amp; run-parts --report /etc/cron.hourly
28 0 * * * root test -x /usr/sbin/anacron || ( cd / &amp;&amp; run-parts --report /etc/cron.daily )
9 5 * * 7 root test -x /usr/sbin/anacron || ( cd / &amp;&amp; run-parts --report /etc/cron.weekly )
52 0 20 * * root test -x /usr/sbin/anacron || ( cd / &amp;&amp; run-parts --report /etc/cron.monthly )

40 6 * * * root /usr/bin/certbot renew &gt; certrenew_log
#
patrick@h2866085:/etc$
</code></pre>



<h2 class="wp-block-heading">Separate Letsencrypt SSL Certificate for another proxy server</h2>



<p>I currently have 2 server files in my <code>/etc/nginx/sites-available</code> directory. </p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx/sites-available$ ls -l
insgesamt 8
-rw-r--r-- 1 root root 2416 Apr  6  2018 default
-rw-r--r-- 1 root root 1089 Feb 23 06:34 prod-reverse-proxy
patrick@h2866085:/etc/nginx/sites-available$ 
</code></pre>



<p>The file <code>default</code> is disabled. </p>



<p>The file  <code>prod-reverse-proxy</code> is enabled. The server run as reverse proxy server for the hostnames <strong>digitaldocblog.com</strong> and <strong>www.digitaldocblog.com</strong> already using SSL (see above).</p>



<p>For my hostname <code>dev.digitaldocblog.com</code>, which is a valid subdomain of domain <code>digitaldocblog.com</code> I create a separate proxy server file <code>dev-reverse-proxy</code> in the directory <code>/etc/nginx/sites-available</code>, link this file in ****<code>/etc/nginx/sites-enabled</code>, test the nginx configuration and restart nginx.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx/sites-available$ sudo touch dev-reverse-proxy
patrick@h2866085:/etc/nginx/sites-available$ ls -al
insgesamt 16
drwxr-xr-x 2 root root 4096 Feb 23 13:42 .
drwxr-xr-x 8 root root 4096 Feb 23 06:34 ..
-rw-r--r-- 1 root root 2416 Apr  6  2018 default
-rw-r--r-- 1 root root    0 Feb 23 13:42 dev-reverse-proxy
-rw-r--r-- 1 root root 1089 Feb 23 06:34 prod-reverse-proxy
patrick@h2866085:/etc/nginx/sites-available$ sudo nano dev-reverse-proxy
server {
    listen 80;
    server_name dev.digitaldocblog.com;

        access_log /var/log/nginx/dev-reverse-access.log;
        error_log /var/log/nginx/dev-reverse-error.log;

        location / {

	proxy_set_header HOST $host;
</code></pre>



<p>proxy_set_header X-Forwarded-Proto $scheme;</p>



<p>proxy_set_header X-Real-IP $remote_addr;</p>



<p>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;</p>



<pre class="wp-block-code"><code>            	proxy_pass http://127.0.0.1:3030;
  }

}
patrick@h2866085:/etc/nginx/sites-available$ cd ..
patrick@h2866085:/etc/nginx$ sudo ln -s /etc/nginx/sites-available/dev-reverse-proxy /etc/nginx/sites-enabled
patrick@h2866085:/etc/nginx$ ls -l sites-enabled
insgesamt 0
lrwxrwxrwx 1 root root 44 Feb 23 13:51 dev-reverse-proxy -&gt; /etc/nginx/sites-available/dev-reverse-proxy
lrwxrwxrwx 1 root root 45 Feb 22 19:33 prod-reverse-proxy -&gt; /etc/nginx/sites-available/prod-reverse-proxy
patrick@h2866085:/etc/nginx$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
patrick@h2866085:/etc/nginx$ sudo systemctl restart nginx
patrick@h2866085:/etc/nginx$
</code></pre>



<p>Then I run <code>certbot --nginx</code> to request a seperate letsencrypt SSL certificate only for the subdomain <code>dev.digitaldocblog.com</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/nginx$ sudo certbot --nginx
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx

Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: digitaldocblog.com
2: dev.digitaldocblog.com
3: www.digitaldocblog.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel): 2
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for dev.digitaldocblog.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/dev-reverse-proxy

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number &#91;1-2] then &#91;enter] (press 'c' to cancel): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/dev-reverse-proxy

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://dev.digitaldocblog.com

You should test your configuration at:
https:&#47;&#47;www.ssllabs.com/ssltest/analyze.html?d=dev.digitaldocblog.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/dev.digitaldocblog.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/dev.digitaldocblog.com/privkey.pem
   Your cert will expire on 2021-05-24. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

patrick@h2866085:/etc/nginx$
</code></pre>



<p>Then I check the new directory and the files in <code>/etc/letsencrypt</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc/letsencrypt$ pwd
/etc/letsencrypt
patrick@h2866085:/etc/letsencrypt$ sudo ls -l live
&#91;sudo] Passwort für patrick: 
insgesamt 8
drwxr-xr-x 2 root root 4096 Feb 23 13:54 dev.digitaldocblog.com
drwxr-xr-x 2 root root 4096 Feb 23 06:33 digitaldocblog.com
patrick@h2866085:/etc/letsencrypt$ sudo ls -l live/dev.digitaldocblog.com
insgesamt 4
lrwxrwxrwx 1 root root  46 Feb 23 13:54 cert.pem -&gt; ../../archive/dev.digitaldocblog.com/cert1.pem
lrwxrwxrwx 1 root root  47 Feb 23 13:54 chain.pem -&gt; ../../archive/dev.digitaldocblog.com/chain1.pem
lrwxrwxrwx 1 root root  51 Feb 23 13:54 fullchain.pem -&gt; ../../archive/dev.digitaldocblog.com/fullchain1.pem
lrwxrwxrwx 1 root root  49 Feb 23 13:54 privkey.pem -&gt; ../../archive/dev.digitaldocblog.com/privkey1.pem
-rw-r--r-- 1 root root 682 Feb 23 13:54 README
patrick@h2866085:/etc/letsencrypt$ 
</code></pre>



<h2 class="wp-block-heading">Directory Setup for node applications</h2>



<p>I run my node applications on my server in <code>/var/www/node</code> directory. The node directory is owned by <code>root</code>.</p>



<p>All files of my <strong>Node Dev Applications</strong> will be copied to <code>/var/www/node/dev</code> using the user <code>patrick</code>. This directory is owned by <code>patrick</code> . According to the configuration in <code>dev-reverse-proxy</code> all http requests coming in for server name <code>dev.digitaldocblog.com</code> will be passed to localhost 127.0.0.1 server port 3030. All dev applications must listen on localhost <code>127.0.0.1 server port 3030</code>.</p>



<p>All files of my <strong>Node Prod Application</strong> will be copied to <code>/var/www/node/prod</code> also using the user <code>patrick</code>. The prod directory is also owned by the user <code>patrick</code>. According to configuration in <code>prod-reverse-proxy</code> all http requests coming in for server names <code>digitaldocblog.com</code> and <code>www.digitaldocblog.com</code> will be passed to localhost 127.0.0.1 server port 3000. Prod application must listen on localhost <code>127.0.0.1 server port 3000</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc$ cd /var
patrick@h2866085:/var$ ls
backups  cache  lib  local  lock  log  mail  opt  run  spool  tmp  www
patrick@h2866085:/var$ cd www
patrick@h2866085:/var/www$ ls -l
insgesamt 4
drwxr-xr-x 2 root root 4096 Feb 20 12:46 html
patrick@h2866085:/var/www$ sudo mkdir node
patrick@h2866085:/var/www$ ls -l
insgesamt 8
drwxr-xr-x 2 root root 4096 Feb 20 12:46 html
drwxr-xr-x 2 root root 4096 Feb 23 08:53 node
patrick@h2866085:/var/www$ cd node
patrick@h2866085:/var/www/node$ ls -l
insgesamt 0
patrick@h2866085:/var/www/node$ sudo mkdir prod
patrick@h2866085:/var/www/node$ sudo mkdir dev
patrick@h2866085:/var/www/node$ ls -l
insgesamt 8
drwxr-xr-x 2 root root 4096 Feb 23 08:56 dev
drwxr-xr-x 2 root root 4096 Feb 23 08:56 prod
patrick@h2866085:/var/www/node$ sudo chown patrick:patrick dev
patrick@h2866085:/var/www/node$ sudo chown patrick:patrick prod
patrick@h2866085:/var/www/node$ ls -al
insgesamt 16
drwxr-xr-x 4 root    root    4096 Feb 23 08:56 .
drwxr-xr-x 4 root    root    4096 Feb 23 08:53 ..
drwxr-xr-x 2 patrick patrick 4096 Feb 23 08:56 dev
drwxr-xr-x 2 patrick patrick 4096 Feb 23 08:56 prod
patrick@h2866085:/var/www/node$
</code></pre>



<h2 class="wp-block-heading">MongoDB Community Server Installation</h2>



<p>Most node applications also interact with a database. My preferred database is MongoDB. Go on the <a href="https://www.mongodb.com">MongoDB website</a> and read more about the free <a href="https://www.mongodb.com/try/download/community">MongoDB Community Server</a>. To read how to install the mongoDB in your environment go to the <a href="https://docs.mongodb.com/manual/">MongoDB Documentation Site</a>. </p>



<p>I select the <a href="https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/">installation instructions</a> of the MongoDB Community Server for my Ubuntu Linux 18.04 bionic LTS system.<br></p>



<p>Then I Import the public key used by the package management system to verify the package source.</p>



<pre class="wp-block-code"><code>$ wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
</code></pre>



<p>Then I create the list file <code>/etc/apt/sources.list.d/mongodb-org-4.4.list</code> for my version of Ubuntu.</p>



<pre class="wp-block-code"><code>$ echo "deb &#91; arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
</code></pre>



<p>I reload the local package database with <code>apt-get update</code> and install a specific release including all relevant component packages with <code>apt-get install</code> such as</p>



<ul class="wp-block-list"><li>server</li><li>shell</li><li>mongos</li><li>tools<br><br><br>$ sudo apt-get update<br>$ sudo apt-get install -y mongodb-org=4.4.4 mongodb-org-server=4.4.4 mongodb-org-shell=4.4.4 mongodb-org-mongos=4.4.4 mongodb-org-tools=4.4.4<br></li></ul>



<p>Mongodb can be started, restarted etc. with the following commands.</p>



<pre class="wp-block-code"><code>:$ sudo service mongod status

:$ sudo service mongod start

:$ sudo service mongod stop

:$ sudo service mongod restart
</code></pre>



<p>After the installation the mongoDB server must be started.</p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ sudo service mongod status
● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: https://docs.mongodb.org/manual

patrick@h2866085:~$ sudo service mongod start
patrick@h2866085:~$ sudo service mongod status
● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: active (running) since Tue 2021-02-23 08:49:14 CET; 3s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 27830 (mongod)
   CGroup: /system.slice/mongod.service
           └─27830 /usr/bin/mongod --config /etc/mongod.conf

Feb 23 08:49:14 h2866085.stratoserver.net systemd&#91;1]: Started MongoDB Database Server.
patrick@h2866085:~$
</code></pre>



<p>Then I create the admin user <code>myUserAdmin</code> against the admin db.</p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ mongo
MongoDB shell version v4.4.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("8df6776d-4228-43f5-9222-65893d6f146c") }
MongoDB server version: 4.4.4
---
The server generated these startup warnings when booting: 
        2021-02-23T08:49:15.047+01:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2021-02-23T08:49:15.718+01:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2021-02-23T08:49:15.718+01:00: You are running in OpenVZ which can cause issues on versions of RHEL older than RHEL6
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
&gt; use admin
switched to db admin
&gt; db
admin
&gt; db.createUser({ user: "myUserAdmin", pwd: "yourAdminPassword", roles: &#91;{ role: "userAdminAnyDatabase", db: "admin" }, {"role" : "readWriteAnyDatabase", "db" : "admin"}] })
Successfully added user: {
"user" : "myUserAdmin",
"roles" : &#91;
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
]
}
&gt; db.auth("myUserAdmin", "yourAdminPassword")
1
&gt; show users
{
"_id" : "admin.myUserAdmin",
"userId" : UUID("6b32b520-090b-411b-9569-4ecc70109707"),
"user" : "myUserAdmin",
"db" : "admin",
"roles" : &#91;
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : &#91;
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
&gt; exit
bye
patrick@h2866085:~$
</code></pre>



<p>Then I open <code>/etc/mongod.conf</code> file in my editor an add the following lines to the file if it does not already exist <code>security: authorization: enabled</code>.</p>



<pre class="wp-block-code"><code>#security:
security:
  authorization: enabled
</code></pre>



<p>Then I restart the mongoDB service.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc$ sudo service mongod restart
</code></pre>



<p>I create a new database <code>dev-bookingsystem</code> and the Db-User <code>myUserDevBookingsystem</code> as the Db-owner.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc$ mongo
MongoDB shell version v4.4.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("48d8e3cb-8076-47cb-8166-8e48cfae3d9a") }
MongoDB server version: 4.4.4
&gt; use admin
switched to db admin
&gt; db.auth("myUserAdmin", "yourAdminPassword")
1
&gt; use dev-bookingsystem
switched to db dev-bookingsystem
&gt; db.createUser({ user: "myUserDevBookingsystem", pwd: "yourDbUserPassword", roles: &#91;{ role: "dbOwner", db: "dev-bookingsystem" }] })
Successfully added user: {
"user" : "myUserDevBookingsystem",
"roles" : &#91;
{
"role" : "dbOwner",
"db" : "dev-bookingsystem"
}
]
}
&gt; db
dev-bookingsystem
&gt; exit
bye
</code></pre>



<p>Then I create a default collection in <code>dev-bookingsystem</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/etc$ mongo
MongoDB shell version v4.4.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d3494272-8651-4c7e-a781-231f48a60ec4") }
MongoDB server version: 4.4.4
&gt; use admin
switched to db admin
&gt; db.auth("myUserAdmin", "yourAdminPassword")
1
&gt; show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
&gt; use dev-bookingsystem
switched to db dev-bookingsystem
&gt; db.runCommand( { create: "col_default" } )
{ "ok" : 1 }
&gt; show collections
col_default
&gt; show dbs
admin              0.000GB
config             0.000GB
dev-bookingsystem  0.000GB
local              0.000GB
&gt; db
dev-bookingsystem
&gt; exit
bye
patrick@h2866085:/etc$
</code></pre>



<p>I do the same thing for my production database <code>prod-digitaldocblog</code>.</p>



<pre class="wp-block-code"><code>patrick@h2866085:~$ mongo
MongoDB shell version v4.4.4
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2402f47f-d1dd-4399-931e-b327ea1cf4b4") }
MongoDB server version: 4.4.4
&gt; use admin
switched to db admin
&gt; db.auth("myUserAdmin", "yourAdminPassword")
1
&gt; show dbs
admin              0.000GB
config             0.000GB
dev-bookingsystem  0.000GB
local              0.000GB
&gt; use prod-digitaldocblog
switched to db prod-digitaldocblog
&gt; db.createUser({ user: "myUserProdDigitaldocblog", pwd: "yourDbUserPassword", roles: &#91;{ role: "dbOwner", db: "prod-digitaldocblog" }] })
Successfully added user: {
"user" : "myUserProdDigitaldocblog",
"roles" : &#91;
{
"role" : "dbOwner",
"db" : "prod-digitaldocblog"
}
]
}
&gt; db
prod-digitaldocblog
&gt; show dbs
admin              0.000GB
config             0.000GB
dev-bookingsystem  0.000GB
local              0.000GB
&gt; db
prod-digitaldocblog
&gt; db.runCommand( { create: "col_default" } )
{ "ok" : 1 }
&gt; show collections
col_default
&gt; show dbs
admin                0.000GB
config               0.000GB
dev-bookingsystem    0.000GB
local                0.000GB
prod-digitaldocblog  0.000GB
&gt; exit
bye
patrick@h2866085:~$
</code></pre>



<p>Now I can connect each app with their database with the following string.</p>



<pre class="wp-block-code"><code>mongodb://&lt;youruser&gt;:&lt;yourpassword&gt;@localhost/&lt;yourdatabase&gt;
</code></pre>



<h2 class="wp-block-heading">Deploy the production node app</h2>



<p>To deploy my node app into production I first copy the <code>package.json</code> file into the <code>/var/www/node/prod</code> directory and run <code>npm install</code> to install all dependencies. The directory <code>node_modules</code> now exists in my <code>/var/www/node/prod</code> directory.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/var/www/node/prod$ ls -l
insgesamt 116
-rw-r--r--   1 patrick patrick   615 Jan 18 14:36 package.json
patrick@h2866085: npm install
patrick@h2866085:/var/www/node/prod$ ls -l
insgesamt 116
drwxrwxr-x 220 patrick patrick 12288 Feb 23 13:15 node_modules
-rw-r--r--   1 patrick patrick   615 Jan 18 14:36 package.json
-rw-rw-r--   1 patrick patrick 67705 Feb 23 13:15 package-lock.json
patrick@h2866085:
</code></pre>



<p>Then I copy all the application files on the server into the directory ****<code>/var/www/node/prod</code> .</p>



<pre class="wp-block-code"><code>patrick@h2866085:/var/www/node/prod$ ls -al
insgesamt 132
drwxr-xr-x  10 patrick patrick  4096 Feb 23 13:17 .
drwxr-xr-x   4 root    root     4096 Feb 23 08:56 ..
drwxr-xr-x   3 patrick patrick  4096 Feb 23 13:16 app
drwxr-xr-x   2 patrick patrick  4096 Feb 23 13:16 config
-rw-------   1 patrick patrick   167 Feb 19  2020 .env
-rw-r--r--   1 patrick patrick    33 Feb 19  2020 .env.example
drwxr-xr-x   2 patrick patrick  4096 Feb 23 13:16 middleware
drwxr-xr-x   2 patrick patrick  4096 Feb 23 13:16 modules
drwxrwxr-x 220 patrick patrick 12288 Feb 23 13:15 node_modules
-rw-r--r--   1 patrick patrick   615 Jan 18 14:36 package.json
-rw-rw-r--   1 patrick patrick 67705 Feb 23 13:15 package-lock.json
-rw-r--r--   1 patrick patrick  1281 Mai 17  2020 prod.digitaldocblog.js
drwxr-xr-x   2 patrick patrick  4096 Feb 23 13:17 routes
drwxr-xr-x   7 patrick patrick  4096 Feb 23 13:17 static
drwxr-xr-x   2 patrick patrick  4096 Feb 23 13:17 views
patrick@h2866085:/var/www/node/prod$ nano .env
</code></pre>



<p>I edit my environment variables in the <code>.env</code> file. Here I configure in particular the server port and the database connection string.<br></p>



<pre class="wp-block-code"><code>patrick@h2866085:/var/www/node/prod$ cat .env
port= 3000
host=127.0.0.1
mongodbpath=mongodb://&lt;youruser&gt;:&lt;yourpassword&gt;@localhost/&lt;yourdatabase&gt;
jwtkey=&lt;yourjwtkey&gt;
patrick@h2866085:/var/www/node/prod$
</code></pre>



<p>Finally I start the production application with PM2.</p>



<pre class="wp-block-code"><code>patrick@h2866085:/var/www/node/prod$ pm2 start prod.digitaldocblog.js
</code></pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>A not so simple booking system for sports clubs (Version 1.0)</title>
		<link>https://digitaldocblog.com/webdesign/a-not-so-simple-booking-system-for-sports-clubs-version-10/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 30 Jan 2021 09:00:00 +0000</pubDate>
				<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webdesign]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Blog-Application]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Java Script]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=120</guid>

					<description><![CDATA[Some sport clubs offer trainings to their members and must ask for money to participate. At least that&#8217;s how it is with my son&#8217;s ice hockey club. This causes an&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Some sport clubs offer trainings to their members and must ask for money to participate. At least that&#8217;s how it is with my son&#8217;s ice hockey club. This causes an administrative effort, since both the training on the one hand and the bookings and invoicing on the other hand have to be managed. </p>



<p>The ice hockey club where my son plays has so far administered this with high manual effort. The players can register themselves on a website and after the training has taken place the amounts are added together for each player and published in another list as a request for payment. In advance, of course, the lists for each training must be created, one list for each training that takes place at a certain point in time.</p>



<p>My goal was to write a software that regulates everything that is related to the administration of the training courses and the bookings automatically as far as possible.</p>



<h1 class="wp-block-heading">Preliminary technical considerations</h1>



<p>From my point of view, it makes sense to develop a web-application that can be accessed with a standard web-browser. I use the possibilities to optimize such a web-application for mobile devices. The application has been developed according to the mobile first principle. This means that in addition to standard use on a PC or laptop, it is technically possible to use the web application on smartphones and tablets with the standard browser installed there. As a technical platform, I use server-side JavaScript for the application backend. Specifically, I use Node-JS and Express-JS to program the application logic. MongoDB is used as the database. The front end design is developed with Materialize CSS Framework.</p>



<p>You are welcome to view and download my code on my <a href="https://github.com/prottlaender/bookingsystem">GitHub repository.</a> Of course, I am happy to receive your comments.</p>



<h1 class="wp-block-heading">Authorization Concept</h1>



<p>Of course, an application like this should also have a corresponding authorization or role concept. This means that the application is used by users with different roles. Depending on the respective role, the user is presented with a range of functions that is specialized for him. I implement 3 different roles.</p>



<ul class="wp-block-list"><li>There is an <strong>Administrator</strong>. The administrator takes care of the user and training management and the billing of trainings for the users.</li><li>There is a <strong>Player</strong>. The player can select trainings and book trainings accordingly. He sees his bills as well as outstanding payments and can use this information to instruct payments or transfers.</li><li>Then there is also a <strong>Coach</strong>. The coach operates on site at the time the training takes place. He confirms the participants in a training session using a list that is displayed to him. Alternatively, the participants can be recorded in the system at a later point in time. For example the coach write down a list of participants by hand and record the participants in the system based on that list at home.<br></li></ul>



<p>The application can only be used if the user is authenticated and authorized. So a user has to register. Users who are already registered can log in to the application on the login site.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611476166686_000-000-Login.png" alt="Login Site"/><figcaption>Login Site</figcaption></figure>



<p>Unregistered users go to the registration site and carry out a self-registration there. After registering, the user is not logged in immediately. </p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611476271090_000-001-Registration.png" alt="Registration Site"/><figcaption>Registration Site</figcaption></figure>



<p>Any self-registration must first be approved by activating the new user account in the system. Only then the user can log in to the system. This is an administrator&#8217;s job and will be described below.</p>



<h1 class="wp-block-heading">Limitations in this version</h1>



<p>This version has the following limitations. I will use this list of limitations as a store of ideas for the further development of the system. Maybe there are more limitations and the list gets longer. Any comment is welcome. Just send me an email. </p>



<p><strong>Multi-Role Concept</strong></p>



<p>In this version of the system, only one role per user is possible. This means that i.e. an administrator cannot be a player or a coach at the same time. This multi-role concept is an extension that I will implement in a later release.</p>



<p><strong>Confirm participants without booking</strong></p>



<p>As described below, the coach can confirm the participation of players in a training session. Here the coach can select from a list of players who have booked the training. Because it is possible for the player to book a training first, then cancel this booking but still appear for the training, canceled bookings are also displayed to the coach here. In this version, the coach cannot confirm the participation of players who have no booking at all. He would not find them on the list. Such a recording of participants without booking is a process that will be taken into account in a later version of the system.</p>



<h1 class="wp-block-heading">General function of the application</h1>



<p>In general, with the application, data is recorded by the actors and once recorded data can be changed again by the actors. For example, an administrator can create users in the system. The user data recorded in this way receive various attributes like name and address or birthdate. These data can be changed later by the administrator or by the user itself, for example when the address changed because the user has moved to another city.</p>



<p>The first entry of data is always done by the administrator. An exception is the self registration process as described briefly above using the registration form. The administrator initially records data using a form. This form is directly displayed in a modal after the function has been activated in the top navigation. A modal is an overlay pop up which is presented to the user after a click and is used for the interaction between the user and the application. </p>



<p><strong>Create modals</strong></p>



<p>Create modals are activated via the top navigation without having previously marked a data record with the checkbox. Create modals are used to capture new data and store them into the database. They contain a form for entering data and a close, reset and submit button at the bottom right. The modal can be closed with the close button and all data entered so far remain available until the browser is refreshed. The reset button deletes all data entered in the form. If the Submit button is clicked, the data entered will be saved.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611985593825_000-010-Create-Modal.png" alt="Create Modal"/><figcaption>Create Modal</figcaption></figure>



<p><strong>Confirm modals</strong></p>



<p>Confirm modals are activated via the top navigation after having previously marked a data record with the checkbox. Confirm modals are used to change existing data and store these changes into the database. They contain data in a from from the data record that was previously marked with the checkbox and a close and a submit button at the bottom right. The modal can be closed with the close button and all data entered so far remain available until the browser is refreshed. If the Submit button is clicked, the data of the marked dataset is loaded from the database and displayed on a call site.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611985619675_000-020-Confirm-Modal.png" alt="Confirm Modal"/><figcaption>Confirm Modal</figcaption></figure>



<p><strong>Call Sites</strong></p>



<p>Call sites contain a form with unchangeable and changeable data fields from the data record which was previously marked with the checkbox. In the top navigation there is a single link that leads the user back to the dashboard. Changes are not saved. </p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611986396085_000-030-Call-Site-1.png" alt="Call Site - 1"/><figcaption>Call Site &#8211; 1</figcaption></figure>



<p>At the bottom right of the call site, the user can click the Back Button to return to the dashboard without saving any changes. With Confirm, the changes entered by the user are saved in the database. The data fields that cannot be changed are only displayed to the user for information purposes, the data fields that can be changed can be overwritten. After the changes have been recorded, the user clicks Confirm to confirm his changes and to save the changes in the database.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611986415718_000-030-Call-Site-2.png" alt="Call Site - 2"/><figcaption>Call Site &#8211; 2</figcaption></figure>



<p><strong>Bad Request Sites</strong></p>



<p>The application checks all user data entries and monitors its functionality itself. Whenever the user has entered incorrect data or the application produces an error for some other reason (e.g. a data record is not found), the user is informed of this with a Bad Request Site. The Bad Request Site only contains the error message and a Back Button with which the user comes directly back to the dashboard.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611986987173_000-040-Bad-request.png" alt="Bad Request Site"/><figcaption>Bad Request Site</figcaption></figure>



<p><strong>Success Sites</strong></p>



<p>Each successful operation is confirmed with a success site. The Success Site also contains the success message and a Back Button with which the user comes directly back to the dashboard.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611987149138_000-050-Success.png" alt="Success Site"/><figcaption>Success Site</figcaption></figure>



<h1 class="wp-block-heading">Administrator</h1>



<p>The administrator is the user with the greatest range of functions. If an administrator has logged in to the application with his user ID (email) and password, he is given access to the admin dashboard. </p>



<p>The <strong>admin-dashboard</strong> shows 5 tables:</p>



<ul class="wp-block-list"><li>Users</li><li>Bookings</li><li>Trainings</li><li>Locations</li><li>Invoices<br></li></ul>



<p>Each table can be viewed by clicking on the tabs in the admin dashboard. You can see which table is currently selected by the fact that the corresponding tab has a light gray background and a blue line is displayed at the bottom of the tab. In this example, the Locations table has been clicked.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611474588299_001-000-Admin-Dashboard.png" alt="Admin Dashboard"/><figcaption>Admin Dashboard</figcaption></figure>



<p>Each line of the tables show a data record. A data record can be selected if there is a checkbox on the left. </p>



<p>The user table shows all users in the system with their most important attributes. The booking table shows the administrator all training bookings in the system and their status. The bookings cannot be edited by the administrator. The trainings, locations and the invoices tables show all trainings, locations and all invoices that the administrator has entered in the system so far.</p>



<p>At the top there is a navigation bar with links and dropdown menus with all the important functions for the administrator.</p>



<h2 class="wp-block-heading">User Management</h2>



<p>User Management is a dropdown menu in the top navigation bar. Here the administrator has the possibility to use the following user management functions. </p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611474452484_001-001-Usermanagement.png" alt="Admin Usermanagement Fuctionalities"/><figcaption>Admin Usermanagement Fuctionalities</figcaption></figure>



<p><strong>Create User</strong></p>



<p>To create a new user, the administrator clicks on the create user function via the dropdown menu. A modal opens that shows the administrator a form to capture all relevant user data. The administrator records all relevant data and assigns a role (admin, player or coach) and an initial password, which can later be changed by the user himself. The email address of the user serves as the UserID and may only appear once in the system. By clicking on Submit on the lower right edge of the modal, the data are written to the database. The new user is created and the user status is awaitapproval (user must be activated by the administrator).</p>



<p><strong>Update User</strong></p>



<p>To update a user, the administrator clicks on the checkbox of a user in the user table and then activates the update user function via the dropdown menu. A modal opens that shows the administrator the email address of the selected user. By clicking on Submit on the lower right edge of the modal, the user&#8217;s data is loaded from the database and displayed on a Confirm Update User call site. The administrator can edit some fields such as name, street or date of birth. By clicking on Confirm at the bottom right of the Confirm Update User call site, the changes are written to the database.</p>



<p><strong>Update Email</strong></p>



<p>To update a users email, the administrator clicks on the checkbox of a user in the user table and then activates the update email function via the dropdown menu. A modal opens that shows the administrator the current email address of the selected user. The administrator can enter the user&#8217;s new email address in another field. By clicking on Submit on the lower right edge of the modal, the user&#8217;s new email address is written to the database. Changing the email address means that the user can only log into the system with the new email address. If the user has already booked a training, the email address stored on the booking is updated with the new email address.</p>



<p><strong>Update Status</strong></p>



<p>To update a users status, the administrator clicks on the checkbox of a user in the user table and then activates the update users status function via the dropdown menu. A modal opens that shows the administrator the current email address of the selected user. On the lower right edge of the modal, the Administrator can click on the Activate, Terminate or on the Remove Button. By clicking on Activate the user can be activated. When the administrator click on the Terminate button users can be terminated where the user balance is not greater 0. By clicking on Remove only terminated users can be completely removed from the database.</p>



<p><strong>Update Password</strong></p>



<p>To set a new user password, the administrator clicks on the checkbox of a user in the user table and then activates the update password function via the dropdown menu. A modal opens that shows the administrator the current email address of the selected user. The administrator must enter the new user password in one field and then repeat this new password in a further field. The new user password must be at least 7 characters long. There are no further requirements for the complexity of the password. If both entered passwords are identical, the new user password is written to the database. The user must log in to the system with the new user password.</p>



<h2 class="wp-block-heading">Update Trainings</h2>



<p>To update the data for an existing training, the administrator clicks on the Training tab to display the table with all the available trainings in the admin dashboard. Then the administrator selects the checkbox of the training that is to be updated and clicks the update training button in the navigation bar above. A modal opens that shows the selected training ID, the location and the date of the selected training. At the lower right edge of the modal, the administrator clicks on the Submit button to call the Create Training call site.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611475407416_001-002-Update-Trainings.png" alt="Update Training Modal"/><figcaption>Update Training Modal</figcaption></figure>



<p>This Create Training call site opens and show the data of the selected training course. If the administrator clicks on Dashboard in the top navigation, the administrator go directly back to the dashboard and no changes are saved to the database. </p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611476882326_001-003-Create-Training-Call-Site.png" alt="Create Training Call Site - No Changes possible"/><figcaption>Create Training Call Site &#8211; No Changes possible</figcaption></figure>



<p>The call site shows a form with data that cannot be changed but are displayed to the administrator for information. The call site shows also data that can be changed by the administrator. These data can be overwritten with the respective change.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611477505500_001-004-Create-Training-Call-Site.png" alt="Create Training Call Site - Changes possible"/><figcaption>Create Training Call Site &#8211; Changes possible</figcaption></figure>



<p>At the bottom of the Create Training call site there is a Back and a Confirm button. If the administrator clicks on Back, he goes back to the admin dashboard without saving any changes. If the administrator clicks on Confirm, the changes are saved in the database.</p>



<h2 class="wp-block-heading">Location Management</h2>



<p>Location Management is again a dropdown menu in the top navigation of the admin dashboard. The create and update locations functions are available here and the create training functionality.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611478385524_001-010-Locationmanagement.png" alt="Location Management and Location Table in the Admin Dashboard"/><figcaption>Location Management and Location Table in the Admin Dashboard</figcaption></figure>



<p>A location is a place where different trainings can take place at different times. In addition to the location name and the address, the price that has to be paid for a training session in this location is also linked to the location. The prices differ in adult and youth prices. </p>



<p><strong>Create Location</strong></p>



<p>To create a new Location, the administrator clicks on the create Location function via the dropdown menu. A modal opens that shows the administrator a form to capture all relevant Location data. The administrator records all relevant data. By clicking on Submit on the lower right edge of the modal, the data are written to the database. The new Location is created.</p>



<p><strong>Update Location</strong></p>



<p>To update a Location, the administrator clicks on the checkbox of a Location in the Location table and then activates the update Location function via the dropdown menu. A modal opens that shows the administrator the Location ID, Location Name and the City of the selected Location. At the lower right edge of the modal, the administrator clicks on the Submit button to call the Update Location call site. The call site shows data fields that can be changed by the administrator. The currently saved data is displayed and can be overwritten with the respective change. The Location ID is also displayed but cannot be overwritten. At the bottom of the call site there is a Back and a Confirm button. If the administrator clicks on Back, he goes back to the admin dashboard without saving any changes. If the administrator clicks on Confirm, the changes are saved in the database.</p>



<p><strong>Create Training</strong></p>



<p>To crate a Training, the administrator clicks on the checkbox of a Location in the Location table and then activates the create Training function via the dropdown menu. A modal opens that shows the administrator the Location ID, Location Name and the City of the selected Location. At the lower right edge of the modal, the administrator clicks on the Submit button to call the create Trainings call site. The Location data of the selected Location is displayed on the call Site but can not be overwritten. The call site also contains fields that can be written with training data i.e time start, time end and the date of the training session. At the bottom of the call site form there is a Back and a Confirm button. If the administrator clicks on Back, he goes back to the admin dashboard without saving any changes. If the administrator clicks on Confirm, the Training data are saved in the database. The Training is then created for the selected Location and the status is in-active. The administrator must then activate the training via the update trainings function. </p>



<h2 class="wp-block-heading">Invoice Management</h2>



<p>Invoice Management is a dropdown menu in the top navigation of the admin dashboard. The create and cancel Invoice are available here, but also the function to create a payment for an Invoice and the creation of a Re- Payment in the event that a user has paid too much and thus his balance becomes negative.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611555517464_001-020-Invoicemanagement.png" alt="Invoice Management"/><figcaption>Invoice Management</figcaption></figure>



<p><strong>Create Invoice for User</strong></p>



<p>To create a new invoice for a user, the administrator clicks on the checkbox of a user in the user table and then activates the create invoice for user function via the dropdown menu. A modal opens and shows the administrator the email address of the user who was selected and who will be the invoice recipient. At the lower right edge of the modal, the administrator clicks on the Submit button to create the new invoice for that user. All training sessions (bookings) in the past that have not yet been billed will be billed in this newly created invoice. The invoice status is open, the invoice date is the current date. Every booking that is billed in an invoice receives the status invoice. The administrator can view the newly created invoice in the invoice table in the admin dashboard.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611638396475_001-021-Invoice-table.png" alt="Invoice Table in the Admin Dasboard"/><figcaption>Invoice Table in the Admin Dasboard</figcaption></figure>



<p><strong>Cancel Invoice</strong></p>



<p>To cancel an invoice, the administrator clicks on the checkbox of the invoice in the invoice table and then activates the cancel invoice function via the dropdown menu. A modal opens that shows the administrator the invoice ID, invoice Date and the user email address. The invoice status must be open and no payment may have been recorded so far (amount paid must be 0). At the lower right edge of the modal, the administrator clicks on the Submit button to call the cancel invoice call site. The invoice data of the selected invoice is displayed on the call site but these data can not be overwritten. At the bottom of the call site there is a Back and a Confirm button. If the administrator clicks on Back, he goes back to the admin dashboard without canceling the invoice. If the administrator clicks on Confirm, the invoice will be canceled. This also means that every booking that has been billed in the canceled invoice receives the status booked again. </p>



<p><strong>Create Payment</strong></p>



<p>To create a payment, the administrator clicks on the checkbox of the invoice in the invoice table and then activates the create payment, function via the dropdown menu. If the invoice status is open a modal opens that shows the administrator the invoice ID, invoice Date and the user email address. At the lower right edge of the modal, the administrator clicks on the Submit button to call the pay invoice call site. The invoice data of the selected invoice is displayed on the call site but these data can not be overwritten. There is also a field in which the administrator can enter the amount paid. At the bottom of the call site there is a Back and a Confirm button. If the administrator clicks on Back, he goes back to the admin dashboard without creating the payment. If the administrator clicks on Confirm, the payment will be created. The amount paid for the invoice is a value that is written on every invoice. When the invoice has been created, the amount paid is equal to 0. After a payment has been recorded, the amount paid is added. The invoice balance is also a value that is on every invoice. If the invoice has been created, the invoice balance is equal to the invoice amount. After a payment has been recorded, the amount paid is subtracted from the invoice balance. When the invoice balance is less than or equal to 0 the amount for the invoice has been paid in full and the invoice status changes from open to paid. In case the invoice balance is greater 0 the invoice has been paid partly and the status remains open. </p>



<p><strong>Create Re- Payment</strong></p>



<p>To create a re-payment, the administrator clicks on the checkbox of the invoice in the invoice table and then activates the create re-payment, function via the dropdown menu. A modal opens that shows the administrator the invoice ID, invoice Date and the user email address. The invoice status must be paid and the invoice balance must be less than 0 because only then there is an overpayment and a re-payment can be initiated. At the lower right edge of the modal, the administrator clicks on the Submit button to call the re-pay invoice call site. The invoice data of the selected invoice is displayed on the call site but these data can not be overwritten. There is also a field in which the administrator can enter the amount re-paid. At the bottom of the call site there is a Back and a Confirm button. If the administrator clicks on Back, he goes back to the admin dashboard without creating the re-payment. If the administrator clicks on Confirm, the re-payment will be created.  After the re-payment has been created, the amount paid on the invoice is reduced by the re-payment amount and the re-payment amount is added to the invoice balance which is less than 0 before the re-payment. When the invoice balance after the re-payment is still less than or equal to 0 the invoice status remains paid. In case the invoice balance become greater 0 the invoice status changes from paid to open (very unrealistic use case).</p>



<h1 class="wp-block-heading">Player</h1>



<p>If a player has logged in to the application with his user ID (email) and password, he is given access to the player dashboard. </p>



<p>The <strong>player-dashboard</strong> shows 4 tables:</p>



<ul class="wp-block-list"><li>Available Trainings</li><li>My Bookings</li><li>My Invoices</li><li>My Data<br></li></ul>



<p>Each table can be viewed by clicking on the tabs in the player dashboard. You can see which table is currently selected by the fact that the corresponding tab has a light gray background and a blue line is displayed at the bottom of the tab.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611649669440_002-000-Player-Dahboard.png" alt="Player Dashboard"/><figcaption>Player Dashboard</figcaption></figure>



<p>Each line of the tables show a data record. A data record can be selected if there is a checkbox on the left. The Available Trainings table shows all bookable trainings with their most important attributes. The My Bookings and My Invoices tables shows the user all the current training bookings and invoices including their status. The My Data table show all personal data of the user stored in the system.</p>



<p>At the top there is a navigation bar with dropdown menus with all the important functions.</p>



<h2 class="wp-block-heading">My Bookings Management</h2>



<p>My Booking Management is a dropdown menu in the top navigation of the user dashboard. The create and cancel bookings functions are available here.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611722508091_002-020-My-Bookings-Mgmt.png" alt="My Bookings Management"/><figcaption>My Bookings Management</figcaption></figure>



<p><strong>Book Training</strong></p>



<p>To create a new booking in a certain training location a user the user clicks on the checkbox of a training in the available trainings table and then activates the book training function via the dropdown menu. A modal opens and shows the user the training ID, the location name and the training date of the training that was selected. At the lower right edge of the modal, the user clicks on the Submit button to call the book trainings call site. The booking data of the selected training is displayed on the call site but these data can not be overwritten. Depending on the category of the logged in user (adult or youth), the youth price or the adult price is displayed here on the call site. At the bottom of the call site there is a Back and a Confirm button. If the user clicks on Back, he goes back to the user dashboard without booking the training. If the user clicks on Confirm, the training will be booked and the data stored in the database. In addition, the user balance is increased by the price of the booked training.</p>



<p><strong>Cancel Booking</strong></p>



<p>To cancel an existing booking a user clicks on the checkbox of a booking in the my bookings table and then activates the cancel booking function via the dropdown menu. A modal opens and shows the user the training ID, the location name and the training date of the booking that was selected. At the lower right edge of the modal, the user clicks on the Submit button to call the cancel bookings call site. The booking data of the selected booking is displayed on the call site but these data can not be overwritten. At the bottom of the call site there is a Back and a Confirm button. If the user clicks on Back, he goes back to the user dashboard without canceling the booking. If the user clicks on Confirm, the booking will be canceled and the data are stored to the database. The status of the booking changes from booked to canceled and the user balance is reduced by the booking price.</p>



<h2 class="wp-block-heading">My Data Management</h2>



<p>My Data Management is a dropdown menu in the top navigation of the user dashboard. The update my data, change Email and change password functions are available here.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611722534154_002-030-My-Data-Mgmt.png" alt="My Data Management"/><figcaption>My Data Management</figcaption></figure>



<p><strong>Update my Data</strong></p>



<p>To update my Data, the user activates the update my data function via the dropdown menu. A modal opens that shows the users email address. At the lower right edge of the modal, the user clicks on the Submit button to call the Update My Data call site. The current user data of the user is displayed on the call site. Some data fields can be changed by the user. At the bottom of the call site there is a Back and a Confirm button. If the user clicks on Back, he goes back to the user dashboard without any changes. If the user clicks on Confirm, the data are stored to the database. In case the user did some changes the user data are updated. </p>



<p><strong>Change Email</strong></p>



<p>To change the email, the user activates the update change email function via the dropdown menu. A modal opens that shows the users current email address and a field to enter the new email address. By clicking on Submit on the lower right edge of the modal, the user&#8217;s new email address is written to the database. The user will then be logged off automatically and must log in using the new email address.  If the user has already booked trainings the email address stored on the bookings is updated with the new email address.</p>



<p><strong>Change Password</strong></p>



<p>To change the password, the user activates the change password function via the dropdown menu. A modal opens that shows the 3 fields: Current Password, New Password and Repeat New Password. The user must enter the current password in the current password field and then enter the new password twice. The new user password must be at least 7 characters long. There are no further requirements for the complexity of the password. If the current password is correct and the new password match the repeated password the new password is written to the database. The user remains logged in but has to log in with the new password the next time.</p>



<h1 class="wp-block-heading">Coach</h1>



<p>If a coach has logged in to the application with his user ID (email) and password, he is given access to the coach dashboard. </p>



<p>The <strong>coach-dashboard</strong> shows only one table with active trainings from today or in the future.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611727409524_003-000-Coach-Dahboard.png" alt=""/></figure>



<p>We are assuming that the coach will conduct a training session on January 30th and would like to confirm the presence of the players. The coach selects the today&#8217;s training (30.01.2021) on his coach dashboard and clicks on select training in the top navigation. The modal select training opens and shows a few details on the selected training such as training ID, location name and the training date.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611895665987_003-010-Select-Training.png" alt="Select Training Modal"/><figcaption>Select Training Modal</figcaption></figure>



<p>At the lower right edge of the modal, the coach can confirm with Submit that he will lead this training and now wants to confirm the participants of this training. After clicking on submit, the coach comes to the confirm participants call site and is shown all the players who have booked this training (here also player will be listed who have canceled their booking). This mean all bookings for this training session will be listed where the booking status is booked or canceled.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611895979277_003-020-Call-Participants.png" alt="Confirm Participants"/><figcaption>Confirm Participants</figcaption></figure>



<p>With the checkbox next to each player, the coach can now select the training participants. Here the coach can explicitly click on several (not just one). After all participants have been selected, the coach clicks on confirm participants in the top navigation and a modal opens that shows how many participants were selected by the coach for this training.</p>



<figure class="wp-block-image"><img decoding="async" src="https://paper-attachments.dropbox.com/s_0F8819BAE5224982CCCDCFC6F09C768579694B457B2BA217E6878D242017908C_1611896360934_003-030-Confirm-Participants.png" alt="Confirm Participants"/><figcaption>Confirm Participants</figcaption></figure>



<p>At the lower right edge of the modal, the coach can confirm with Submit that he now wants to confirm the participants of this training. After clicking on submit, the confirm participants process ends. The corresponding booking of the player receives the status participated.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Node.js series Part 4. Express Website with authentication and authorization in a Mac Production Environment</title>
		<link>https://digitaldocblog.com/mac/nodejs-series-part-4-express-website-with-authentication-and-authorization-in-a-mac-production-environment/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 18 Jun 2020 07:00:00 +0000</pubDate>
				<category><![CDATA[Mac OS]]></category>
		<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webdesign]]></category>
		<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Blog-Application]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<category><![CDATA[Role Based Access Control]]></category>
		<category><![CDATA[Web-Application]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=117</guid>

					<description><![CDATA[In a real production environment the app runs as a service in the background and this service is managed by a process manager. And the app should run behind a&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In a real production environment the app runs as a service in the background and this service is managed by a process manager. And the app should run behind a reverse proxy server. This reverse proxy server manage the TLS encryption, receives the requests from the client and route any request to the app running in the background. So the connection from the client to the reverse proxy server is TLS encrypted. Therefore the data transferred between client and the reverse proxy are secured. </p>



<p>How to setup such a <strong>production environment</strong> will be shown in the <strong>first chapter</strong> of this documentation. </p>



<p>The express app itself also contains some <strong>security features</strong>. The app contains a session based user authentication and HTTP headers which help to further secure the app. This is explained of the <strong>second chapter</strong> of this documentation.</p>



<p>Finally the express app should use the <strong>template engine PUG</strong> to render the HTML for us. This is describes of the <strong>third chapter</strong> of this documentation. </p>



<h3 class="wp-block-heading">1. Setup the production environment</h3>



<h4 class="wp-block-heading">Installation of mongodb</h4>



<p>The command <code>brew tap</code> without any arguments lists the GitHub repositories that are currently linked to your Homebrew installation. </p>



<pre class="wp-block-code"><code>Patricks-MBP:~ patrick$ brew tap
homebrew/cask
homebrew/core
homebrew/services
</code></pre>



<p>The formula mongodb has been removed from homebrew-core. But fortunately the MongoDB Team is maintaining a custom <a href="https://github.com/mongodb/homebrew-brew">Homebrew tap on GitHub</a>. Read the instructions in the README.md file. </p>



<p>Add the custom tap in the Mac OS terminal and install mongodb.</p>



<pre class="wp-block-code"><code>Patricks-MBP:~ patrick$ brew tap mongodb/brew

Patricks-MBP:~ patrick$ brew tap
homebrew/cask
homebrew/core
homebrew/services
mongodb/brew

Patricks-MBP:~ patrick$ brew install mongodb-community@4.2

</code></pre>



<p>After the installation the relevant paths are.</p>



<pre class="wp-block-code"><code>the configuration file (/usr/local/etc/mongod.conf)
the log directory path (/usr/local/var/log/mongodb)
the data directory path (/usr/local/var/mongodb)

</code></pre>



<p>Check the services with homebrew</p>



<pre class="wp-block-code"><code>brew services list

Name              Status  User    Plist
mongodb-community started patrick /Users/patrick/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
  
</code></pre>



<p>Start and stop mongodb.</p>



<pre class="wp-block-code"><code>brew services start mongodb-community

brew services stop mongodb-community

</code></pre>



<h4 class="wp-block-heading">Setup mongodb for the project</h4>



<p>Setup an admin user</p>



<pre class="wp-block-code"><code>:# mongo

&gt; use admin
switched to db admin

&gt; db
admin

&gt; db.createUser({ user: "adminUser", pwd: "adminpassword", roles: &#91;{ role: "userAdminAnyDatabase", db: "admin" }, {"role" : "readWriteAnyDatabase", "db" : "admin"}] })

&gt; db.auth("adminUser", "adminpassword")
1

&gt; show users
{
    "_id" : "admin.adminUser",
    "userId" : UUID("5cbe2fc4-1e54-4c2d-89d1-317340429571"),
    "user" : "adminUser",
    "db" : "admin",
    "roles" : &#91;
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        },
        {
            "role" : "readWriteAnyDatabase",
            "db" : "admin"
        }
    ],
    "mechanisms" : &#91;
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}

&gt; exit

</code></pre>



<p>Enable authentication with <code>security: authorization: enabled</code></p>



<pre class="wp-block-code"><code>#&gt; nano /usr/local/etc/mongod.conf

systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  port: 27017
  bindIp: 127.0.0.1
security:
  authorization: enabled


</code></pre>



<p>Login and authenticate with admin</p>



<pre class="wp-block-code"><code>#&gt; mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b3e7f48a-a05c-4894-87db-996cb34eb1fb") }
MongoDB server version: 4.2.3

&gt; show dbs
&gt; db
test
&gt; use admin
switched to db admin
&gt; db
admin
&gt; show dbs
&gt; db.auth("adminUser", "adminpassword")
1
&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB

&gt; 

</code></pre>



<p>If you login you dont see any databases when you call <code>show dbs</code>. The default database you are connected to is <code>test</code>. </p>



<p>Then you connect to admin database. For admin you setup the admin user with the roles <code>userAdminAnyDatabase</code> and <code>readWriteAnyDatabase</code>. With these permissions the admin user can manage users for any database and has read and write access to any database. </p>



<p>So wehen you logon to admin database with the admin user you are able to see all databases with <code>show dbs</code>. </p>



<p>Mongodb comes with 3 standard dbs pre installed:</p>



<ul class="wp-block-list"><li>admin </li><li>config</li><li>local<br></li></ul>



<p>Create a new database for our express-security app (authenticated as admin user &#8211; see above)</p>



<pre class="wp-block-code"><code>&gt; use express-security
switched to db express-security
&gt; db
express-security
&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB
&gt; 

</code></pre>



<p>The DB which you&#8217;ve created is not listed here. We need to insert at least one collection into it for displaying that database in the list. </p>



<pre class="wp-block-code"><code>&gt; db
express-security

&gt; db.createCollection("col_default")
{ "ok" : 1 }

&gt; show dbs
admin               0.000GB
config              0.000GB
express-security    0.000GB
local               0.000GB

&gt; exit

</code></pre>



<p>Create an owner user for express-security database using the admin user</p>



<pre class="wp-block-code"><code>#&gt; mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("79f79b63-9d08-489f-9e6c-bfc10d8cc09e") }
MongoDB server version: 4.2.3

&gt; db
test

&gt; show dbs

&gt; use admin
switched to db admin

&gt; db.auth("adminUser", "adminpassword")
1

&gt; db
admin

&gt; show dbs
admin               0.000GB
config              0.000GB
express-security    0.000GB
local               0.000GB

&gt; use express-security
switched to db express-security

&gt; db.createUser({ user: "owner_express-security", pwd: "passowrd", roles: &#91;{ role: "dbOwner", db: "express-security" }] })
Successfully added user: {
	"user" : "owner_express-security",
	"roles" : &#91;
		{
			"role" : "dbOwner",
			"db" : "express-security"
		}
	]
}

&gt; db
express-security

&gt; show users
{
	"_id" : "express-security.owner_express-security",
	"userId" : UUID("7a0bafb2-d2ed-4d18-9aba-e2f15a503ec5"),
	"user" : "owner_express-security",
	"db" : "express-security",
	"roles" : &#91;
		{
			"role" : "dbOwner",
			"db" : "express-security"
		}
	],
	"mechanisms" : &#91;
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

&gt; exit 
</code></pre>



<p>Connection string to connect to express-security db using the owner_express-security user:</p>



<pre class="wp-block-code"><code>mongodb://owner_express-security:password@localhost/express-security
</code></pre>



<h4 class="wp-block-heading">Installation of PM2</h4>



<p>PM2 is a process manager for Node.js applications. It can daemonize applications to run them as a service in the background.</p>



<p>I install pm2 as a global npm package on my Mac.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:~ patrick$ npm install pm2 -g
</code></pre>



<p>Then navigate to your project directory.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:~ patrick$ cd Software/dev/node/articles/2020-05-15-express-security/express-security

Patricks-Macbook Pro:~ patrick$ ls -l 
total 112
drwxr-xr-x    5 patrick  staff    160 30 Mai 05:28 database
drwxr-xr-x  115 patrick  staff   3680 30 Mai 19:35 node_modules
-rw-r--r--    1 patrick  staff  34366 30 Mai 19:35 package-lock.json
-rw-r--r--    1 patrick  staff    339 30 Mai 19:35 package.json
-rw-r--r--@   1 patrick  staff  12343 30 Jun 05:00 secserver.js
drwxr-xr-x    3 patrick  staff     96 30 Mai 05:03 static

Patricks-Macbook Pro:express-security patrick$ 

</code></pre>



<p>Start your app using pm2</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:express-security patrick$ pm2 start secserver.js

Patricks-Macbook Pro:~ patrick$ pm2 list
┌─────┬──────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name         │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├─────┼──────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0   │ secserver    │ default     │ 1.0.0   │ fork    │ 640      │ 16h    │ 0    │ online    │ 0%       │ 48.6mb   │ patrick  │ disabled │
└─────┴──────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

Patricks-Macbook Pro:~ patrick$ 

</code></pre>



<p>Other comands to control the process manager. </p>



<pre class="wp-block-code"><code>pm2 start secserver.js

pm2 start &lt;id&gt;

pm2 list

pm2 stop &lt;id&gt;

pm2 restart &lt;id&gt;

pm2 show &lt;id&gt;

</code></pre>



<h4 class="wp-block-heading">Installation of nginx</h4>



<p><a href="https://nginx.org/en/">nginx</a> is an open source HTTP and an HTTP Reverse Proxy Server (also mail proxy and load balancer etc.). I install nginx on my Mac with Homebrew. </p>



<pre class="wp-block-code"><code>brew install nginx

</code></pre>



<p>You can list the brew services with the following command.</p>



<pre class="wp-block-code"><code>Patricks-MBP:digitaldocblog-V3 patrick$ brew services list

Name              Status  User    Plist
mongodb-community started patrick /Users/patrick/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
nginx             started patrick /Users/patrick/Library/LaunchAgents/homebrew.mxcl.nginx.plist
Patricks-MBP:digitaldocblog-V3 patrick$
</code></pre>



<p>You can start and stop the brew services as follows.</p>



<pre class="wp-block-code"><code>brew install nginx

brew services start nginx

brew services stop nginx

</code></pre>



<h4 class="wp-block-heading">Setup nginx with TLS/SSL</h4>



<p>SSL/TLS works by using the combination of a public certificate and a private key. </p>



<p>The <strong>SSL key (private key)</strong> is kept secret on the server. It is used to encrypt content sent to clients. </p>



<p>The <strong>SSL certificate</strong> is publicly shared with anyone requesting the content. It can be used to decrypt the content signed by the associated SSL key.</p>



<p><strong>create private key</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security patrick$ cd /usr/local/etc/nginx

Patricks-MBP:nginx patrick$ ls -l
total 144
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf.default
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params.default
-rw-r--r--  1 patrick  admin  2837  5 Apr 13:18 koi-utf
-rw-r--r--  1 patrick  admin  2223  5 Apr 13:18 koi-win
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types.default
-rw-r--r--  1 patrick  admin  3106 15 Mai 05:19 nginx.conf
-rw-r--r--  1 patrick  admin  2680  5 Apr 13:18 nginx.conf.default
-rw-r--r--  1 patrick  admin  3091 21 Jan 05:40 nginx.conf.working
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params.default
drwxr-xr-x  3 patrick  admin    96 21 Jan 06:02 servers
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params.default
-rw-r--r--  1 patrick  admin  3610  5 Apr 13:18 win-utf

Patricks-MBP:nginx patrick$ mkdir ssl

Patricks-MBP:nginx patrick$ ls -l
total 152
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf.default
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params.default
-rw-r--r--  1 patrick  admin  2837  5 Apr 13:18 koi-utf
-rw-r--r--  1 patrick  admin  2223  5 Apr 13:18 koi-win
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types.default
-rw-r--r--@ 1 patrick  admin   373 18 Mai 05:38 nginx.conf
-rw-r--r--  1 patrick  admin  2680  5 Apr 13:18 nginx.conf.default
-rw-r--r--  1 patrick  admin  3091 21 Jan 05:40 nginx.conf.working
-rw-r--r--@ 1 patrick  admin  1390 17 Mai 05:19 nginx_old.conf
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params.default
drwxr-xr-x  5 patrick  admin   160 18 Mai 05:20 servers
drwxr-xr-x  4 patrick  admin   128 16 Mai 05:41 ssl
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params.default
-rw-r--r--  1 patrick  admin  3610  5 Apr 13:18 win-utf

Patricks-MBP:nginx patrick$ cd ssl

Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl genrsa -out privateKey.pem 4096

Patricks-MBP:ssl patrick$ ls -l
total 16
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem

</code></pre>



<p><strong>create certificate signing request (CSR)</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl req -new -key privateKey.pem -out csr.pem

Patricks-MBP:ssl patrick$ ls -l
total 16
-rw-r--r--  1 patrick  admin  1740 16 Mai 05:23 csr.pem
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem

</code></pre>



<p>In case I would like to request an official certificate I must send this csr to the certificate authority. This authority would then create an <strong>authority signed certificate</strong> from the CSR and send it back to me.</p>



<p>This step is done by ourselves and this is the reason why we create a <strong>self signed certificate</strong>. This self signed certificate is not a official certificae and not trusted by any browser. It is not useful to use a self signed certificate in production because it produces error messages in the browsers. But for local development a self signed certificate is ok. </p>



<p>So create the self signed certificale. The csr file can then be removed. </p>



<p><strong>create the self signed certificate</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl x509 -in csr.pem -out selfsignedcertificate.pem -req -signkey privateKey.pem -days 365

Patricks-MBP:ssl patrick$ ls -l
total 24
-rw-r--r--  1 patrick  admin  1740 16 Mai 05:23 csr.pem
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem
-rw-r--r--  1 patrick  admin  1980 16 Mai 05:39 selfsignedcertificate.pem

Patricks-MBP:ssl patrick$ rm csr.pem

Patricks-MBP:ssl patrick$ ls -l
total 24
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem
-rw-r--r--  1 patrick  admin  1980 16 Mai 05:39 selfsignedcertificate.pem
 
</code></pre>



<p><strong>show certificate details</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl x509 -in selfsignedcertificate.pem -text -noout

</code></pre>



<h4 class="wp-block-heading">Configure nginx Servers with SSL</h4>



<p>In our configuration we enforce ssl. Therefore we create a <strong>default Webserver</strong> listening on Port 80 with the server name  <code>servtest.rottlaender.lan</code>. </p>



<p>Any request to <code>servtest.rottlaender.lan:80</code> is redirected to my <strong>Reverse Proxy Server</strong> which is listening on <code>servtest.rottlaender.lan:443</code>.<br></p>



<p>The <strong>default Webserver</strong> is configured in <code>/usr/local/etc/nginx/nginx.conf</code>.</p>



<pre class="wp-block-code"><code># /usr/local/etc/nginx/nginx.conf
# default Webserver

worker_processes  1;
error_log  /usr/local/etc/nginx/logs/error.log;

events {
    worker_connections  1024;
}

http {
    include       		mime.types;
    default_type  		application/octet-stream;
    sendfile        	on;
    keepalive_timeout  	65;

    access_log  /usr/local/etc/nginx/logs/access.log;

    # default Webserver redirect from port 80 to port 443 ssl
    
    server {
      	listen 80;
    	listen &#91;::]:80;
    	server_name servtest.rottlaender.lan;
    	return 301 https://$host$request_uri;
    }
    
    include servers/*;
    
}
</code></pre>



<p>The <strong>Reverse Proxy Server</strong> is configured in <code>/usr/local/etc/nginx/servers/reverse</code>.</p>



<pre class="wp-block-code"><code>// /usr/local/etc/nginx/servers/reverse
// reverse Proxy Server

server {

    listen      443 ssl;
    server_name servtest.rottlaender.lan;

    ssl_certificate      ssl/selfsignedcertificate.pem;
    ssl_certificate_key  ssl/privateKey.pem;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

    location / {
       proxy_pass http://localhost:3300;
       proxy_set_header X-Forwarded-For $remote_addr;
    }
}

</code></pre>



<p>The server name servtest.rottlaender.lan is linked in /private/etc/hosts to the ip 192.168.178.20 which is the ip of my computer in my local network.</p>



<pre class="wp-block-code"><code>Patricks-MBP:digitaldocblog-V3 patrick$ cat /private/etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1			localhost
255.255.255.255		broadcasthost
::1             	localhost
192.168.178.20 		servtest.rottlaender.lan
</code></pre>



<h3 class="wp-block-heading">2. Express Secure App (Security Features HTML version)</h3>



<p>This is a very simple application but show the basic security features you should use when you run a node app in a production environment. </p>



<p>The app is a website with a simple layout and navigation. </p>



<p>The Home page contain static information and can be accessed by everyone. </p>



<p>On the register page, users can find a form to register. The user data entered here are saved in the database and the user is logged in at the same time. Known users can log in with their email and password after successful registration on the login page. The login and register page can only be accessed if the user is not logged in. If a user is logged in and tries to access the login or register, he will be redirected to the dashboard page.</p>



<p>The dashboard is a personalized area of the website. This area can only be accessed if the user is logged in. If a user is not logged in, he will be redirected to the login page.</p>



<p>Logout is not really a page but a link that contains a logout function. Users who are logged in can log out using this link. Users who are not already logged in will be redirected to the login page.</p>



<h4 class="wp-block-heading">Download the code from GitHub</h4>



<p>Pls. <a href="https://github.com/prottlaender/node-part-4-express-security-with-db-html">go to my GitHub site</a> and clone the code. Here you find a some inline documentation in the code. The details are explained in this chapter. </p>



<h4 class="wp-block-heading">Create your app home directory express-security</h4>



<p>My app home directory is different to the one that is available after you cloned the code from GitHub. </p>



<pre class="wp-block-code"><code>Patricks-MBP:2020-05-15-express-security patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security

Patricks-MBP:2020-05-15-express-security patrick$ mv node-part-5-express-security-with-db-pug express-security

Patricks-MBP:2020-05-15-express-security patrick$ cd express-security

Patricks-MBP:express-security patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security/express-security
</code></pre>



<h4 class="wp-block-heading">Manage environment variables</h4>



<p>To manage environment variables for my app I use <code>envy</code>. First you need the files <code>.env</code> and <code>.env.example</code> in the root of your project directory. In <code>.env.example</code> you create a list of all potential environment variables without any values and in <code>.env</code> you use the defined variables and assign the values to them. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security patrick$ ls -al
total 152
drwxr-xr-x   14 patrick  staff    448 23 Jun 05:29 .
drwxr-xr-x    4 patrick  staff    128 26 Mai 05:40 ..
-rw-------    1 patrick  staff    181 23 Jun 05:59 .env
-rw-r--r--    1 patrick  staff     53 23 Jun 05:59 .env.example
....

Patricks-MBP:express-security patrick$ cat .env.example
port=
mongodbpath=
sessionsecret=
sessioncookiename=

Patricks-MBP:express-security patrick$ cat .env
port=&lt;YOUR_PORT&gt;
mongodbpath=&lt;YOUR_CONNECTION_STRING&gt;
sessionsecret=&lt;YOUR_SESSION_SECRET&gt;
sessioncookiename=&lt;YOUR_SESSION_COOKIE_NAME&gt;

Patricks-MBP:express-security patrick$ 

</code></pre>



<p>Envy must be installed as dependency and required in the main application file <em>secserver.js</em>. Then you can set the environment variables as follows. </p>



<pre class="wp-block-code"><code>// secserver.js

....

// envy module to manage environment variables
const envy = require('envy');

// set the environment variables
const env = envy()
const port = env.port
const mongodbpath = env.mongodbpath
const sessionsecret = env.sessionsecret
const sessioncookiename = env.sessioncookiename
....
</code></pre>



<h4 class="wp-block-heading">Start the MongoDB Server</h4>



<p>To run the db server we install <code>mongoose</code> as dependency and require it in the db.js configuration file. The database connection will be initiated with <code>mongoose.connect</code> and the StartMongoServer function will be exported to be called in the main application file <em>secserver.js</em>.</p>



<pre class="wp-block-code"><code>const envy = require('envy')
const env = envy()

const mongodbpath = env.mongodbpath

const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);

const StartMongoServer = async function() {
  try {

    await mongoose.connect(mongodbpath)
    .then(function() {
      console.log(`Mongoose connection open on ${mongodbpath}`);
    })
    .catch(function(error) {
      console.log(`Connection error message: ${error.message}`);
    })

  } catch(error) {
    res.json( { status: "db connection error", message: error.message } );
  }

};

module.exports = StartMongoServer;
</code></pre>



<h4 class="wp-block-heading">Authentication and authorization</h4>



<p>For user authentication we use the module <code>express-session</code> and to store session data in the session store in our database we use <code>connect-mongodb-session</code>. Therefore we install these modules as dependencies in our project and require the modules in our <em>secserver.js</em> main application file.</p>



<p>Then we create with <code>new MongoDBStore</code> a session storage in our MongoDB to store session data in collection <code>col_sessions</code>. errors are catched with <code>store.on</code>. </p>



<p>We use the session in our app with <code>app.use( session({...}) )</code>. With every request to our site a new session object is created with a unique session ID which include a session cookie object. The session object has keys options and the values for each key define how to deal with the session object. The session ID is created and signed using the <code>secret</code> option. We use <code>name</code> to provide a session cookie name and <code>store</code> to define where the session object should be stored (in case we store the session). </p>



<p>We can access the session object with <code>req.session</code> and the session ID with <code>req.session.id</code>. With every request we have a new session and this new session will be created but not stored anywhere so far. We say the session is <em>uninitialized</em>. The <code>saveUninitialized</code> false option ensure that a session will only be written to the store in case it has been modified. What does this mean?<br></p>



<p>We can modify the session when we store additional data into it. We always do this when the user is logging in via the <code>login</code> or the <code>register</code> route. When we post the data from the <em>login-</em> or from the <em>registration-form</em> to the server we call <em>loginUser</em> or the <em>createUser</em> module which is defined in <code>database/controllers/userC.js</code>. Both modules do basically the same thing: They create a userData Object and store the userData object into the session object and redirect the user to the dashboard when login or registration was successful. </p>



<pre class="wp-block-code"><code>....

var userData = { 
	userId: user._id, 
	name: user.name, 
	lastname: user.lastname, 
	email: user.email, 
	role: user.role 
	}

    req.session.userData = userData

    res.redirect('/dashboard')

....

</code></pre>



<p>If the user is successfully logged in the session is <em>initialized</em> (modified), the session object incl. the userData object are stored into the store and a cookie is stored into the requesting browser. The content of the cookie is only a hash of the session Id and with each request of a logged in user the session on the server is looked up. </p>



<p>The cookie in the browser will live max 1 week as we defined in the cookie object <code>maxAge</code> set to 1 week. Because of the cookie option <code>sameSite</code> true the cookie scope is limited to the same site. </p>



<p>Then the <code>resave</code> false option ensures that the session will not be updated with every request. This mean the session ID that has been created when the user has logged in will be kept until the user is logged out again.<br></p>



<pre class="wp-block-code"><code>// secserver.js

....

// server side session and cookie module
const session = require('express-session');
// mongodb session storage module
const connectMdbSession = require('connect-mongodb-session');

....

// Create MongoDB session storage
const MongoDBStore = connectMdbSession(session)
const store = new MongoDBStore({
  uri: mongodbpath,
  collection: 'col_sessions'
});

// catch errors in case store creation fails
store.on('error', function(error) {
  console.log(`error store session in session store: ${error.message}`);
});

// Create the express app
const app = express();

....

// use session to create session and session cookie
app.use(session({
  secret: sessionsecret,
  name: sessioncookiename,
  store: store,
  resave: false,
  saveUninitialized: false,
  // set cookie to 1 week maxAge
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7,
    sameSite: true
  },

}));

....
</code></pre>



<h4 class="wp-block-heading">Secure HTTP headers</h4>



<p>Response headers are HTTP header that come with the HTTP response from the server to the client. The http response header contain data that could possibly damage the integrity of the client. It is therefore important to secure the response header of your application.</p>



<p>To secure the http response headers I user the module <a href="https://helmetjs.github.io/">helmet</a>. This is a relatively easy-to-use module consisting of various middleware functionalities to secure various http response headers.</p>



<p>First we install <code>helmet</code>as a dependency of our project. Then we require helmet and use helmet right after we created the app. </p>



<pre class="wp-block-code"><code>// secserver.js

// hTTP module
const http = require('http');
// express module
const express = require('express');
// hTTP header security module
const helmet = require('helmet');

// Create the express app
const app = express();

....

// use secure HTTP headers using helmet
app.use(helmet())

</code></pre>



<p>Using simply <code>app.use(helmet())</code> set the http header security to default. Then the following 7 out 11 helmet features can be used.</p>



<ol class="wp-block-list"><li><a href="https://helmetjs.github.io/docs/dns-prefetch-control">dnsPrefetchControl</a> controls browser DNS prefetching</li><li><a href="https://helmetjs.github.io/docs/frameguard/">frameguard</a> to prevent clickjacking</li><li><a href="https://helmetjs.github.io/docs/hide-powered-by/">hidePoweredBy</a> to remove the X-Powered-By header</li><li><a href="https://helmetjs.github.io/docs/hsts/">hsts</a> for HTTP Strict Transport Security</li><li><a href="https://helmetjs.github.io/docs/ienoopen/">ieNoOpen</a> sets X-Download-Options for IE8+</li><li><a href="https://helmetjs.github.io/docs/dont-sniff-mimetype/">noSniff</a> to keep clients from sniffing the MIME type</li><li><a href="https://helmetjs.github.io/docs/xss-filter/">xssFilter</a> adds some small XSS protections<br></li></ol>



<p>When we then request our home page to retrieve the http headers using <code>curl -k --head</code> in the terminal we see the following output. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security patrick$ curl -k --head https://servtest.rottlaender.lan
HTTP/1.1 200 OK
Server: nginx/1.19.0
Date: Fri, 26 Jun 2020 16:14:14 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 1734
Connection: keep-alive
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Download-Options: noopen
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
ETag: W/"6c6-U2uWyDNyzlyBAbSI/Quxqo9RRQE"

Patricks-MBP:express-security patrick$ 
</code></pre>



<h4 class="wp-block-heading">App routing</h4>



<p><strong>get routes:</strong> We have the following <code>get</code> routes and navigation.</p>



<ul class="wp-block-list"><li>Home (/)</li><li>Login (/login)</li><li>Register (/register)</li><li>Dashboard (/dashboard)</li><li>Logout (/logout)<br></li></ul>



<p><code>get</code> routes involve an optional middleware and respond HTML back to the client. </p>



<pre class="wp-block-code"><code>app.get('/&lt;route&gt;', &lt;optional: someMiddleware&gt;, (req, res) =&gt; {
	
	res.send(`&lt;some HTML&gt;`)
})
</code></pre>



<p>I will not explain the HTML and css in detail. But as everyone can see, the HTML is the same for every route except for the <code>&lt;body&gt;</code>. Of course, this is not very nice and becomes a bit more efficient with the use of a template engine, which I will explain below using the <a href="https://pugjs.org/api/getting-started.html">PUG template engine</a>. I will then rebuild the app using PUG.</p>



<p>Lets have a look at the <code>middleware</code>. If a request is made for a route and a middleware function is included, the middleware function is first executed before the next routing function <code>function(req, res)</code> is called. A condition is built into the middleware function which is checked. My middleware is built so that in case the condition is true the middleware code is executed directly and the next routing function is omitted. If the condition is false, the next routing function <code>function(req, res)</code> is called.</p>



<p>I have built 2 different middleware functions which each check</p>



<p><strong>middleware 1 (login- and register route):</strong> a user is logged in</p>



<pre class="wp-block-code"><code>// secserver.js
....
// middleware 1 to redirect authenticated users to their dashboard
const redirectDashboard = (req, res, next) =&gt; {
  if (req.session.userData) {
    res.redirect('/dashboard')

  } else {
    next()
  }
}
....
</code></pre>



<p>If a user is logged in the request should be redirected to the dashboard route, in any other case (user is not logged in) the next routing function <code>function(req, res)</code> is called and respond the HTML to the browser. This middleware 1 is included in the <strong>/login-</strong> and <strong>/register</strong> route. This mean logged in users will be redirected to their dashboard, not logged in users will see the login- and register form. </p>



<p><strong>middleware 2 (dashboard- and logout route):</strong> a user is not logged in.</p>



<pre class="wp-block-code"><code>// secserver.js
....

// middleware 2 to redirect not authenticated users to login
const redirectLogin = (req, res, next) =&gt; {
  if (!req.session.userData) {
    res.redirect('/login')
  } else {
    next()
  }
}
....
</code></pre>



<p>If a user is not logged in the request should be redirected to the login roure, in any other case (user is logged in) the next routing function <code>function(req, res)</code> is called and respond the HTML to the browser. This middleware 2 is included in the <strong>/dashboard-</strong> and <strong>/logout</strong> route. This mean not logged in users will be redirected to login route, logged in users will see the dashboard- or can log themselves out. </p>



<p><strong>post routes:</strong> We have the following <code>post</code> routes.</p>



<ul class="wp-block-list"><li>/login</li><li>/register<br></li></ul>



<p>The login and the register <code>get</code> routes contain a form in the HTML. With these forms the user provide the data to login and for user registration. When the user click the send button the <em>action</em> is to call the login- or register <code>post</code> route. This will happen for all not logged in users. The login and the register <code>get</code> routes have the middleware <code>redirectDashboard</code>to redirect the user to the dashbard if the user is already logged in.<br></p>



<pre class="wp-block-code"><code>// secserver.js
....

app.get('/login', redirectDashboard, (req, res) =&gt; {
....
res.send(`
....
&lt;div class="form"&gt;
	&lt;form id='register_form' method='post' action='/register'&gt;
	......
	&lt;label for='send'&gt;
   		&lt;input class='sendbutton' type='submit' name='send' value='Send'&gt;
	&lt;/label&gt;
	&lt;/form&gt;
&lt;/div&gt;

`)
)}
....

app.get('/register', redirectDashboard, (req, res) =&gt; {
....
res.send(`
....
&lt;div class="form"&gt;
	&lt;form id='login_form' method='post' action='/login'&gt;
	......
	&lt;label for='send'&gt;
   		&lt;input class='sendbutton' type='submit' name='send' value='Send'&gt;
	&lt;/label&gt;
	&lt;/form&gt;
&lt;/div&gt;
`)
)}
.....
</code></pre>



<p>The <code>post</code> routes contain functions to login- (loginUser) or register (createUser) the user.<br></p>



<pre class="wp-block-code"><code>// secserver.js
....
// Post routes to manage user login and user registration
app.post('/login', userController.loginUser);

app.post('/register', userController.createUser);
....
</code></pre>



<p>The <code>loginUser</code> function is defined in the user controller <code>database/controllers/userC.js</code>. This function lookup a user in the database based on the email address that has been provided by the request body. The data that are attached to the request body have been provided by the user vie the login form of the app. If no user could be found in the database login is not possible. If a user exist with the given email address then the provided password will be compared with the one stored in the database. If the password match fail login is not possible because the provided password is wrong. in any other case, the login takes place and a userData object is created and attached to the session object.</p>



<pre class="wp-block-code"><code>// database/controllers/userC.js

User.findOne({ email: req.body.email }, function(error, user) {
  if (!user) {
    res.status(400).send({ code: 400, status: 'Bad Request', message: 'No User found with this email' })

    } else {
      if (bcrypt.compareSync(req.body.password, user.password)) {
    
        var userData = { userId: user._id, name: user.name, lastname: user.lastname, email: user.email, role: user.role }

          req.session.userData = userData

          res.redirect('/dashboard')

        } else {
          res.status(400).send({ code: 400, status: 'Bad Request', message: 'Wrong User password' })
        }

      }
    })

  }
</code></pre>



<p>The <code>createUser</code> function is also defined in the user controller <code>database/controllers/userC.js</code>. This function create a new User object based on the data from the request body provided by the user via the form. The provided password will be hashed and stored together with all other data into the database. Finally a userData object is created and attached to the session and the user will be redirected to the dashboard after the registration was successful.<br></p>



<pre class="wp-block-code"><code>// database/controllers/userC.js

createUser: async function (req, res) {
    // assign input data from request body to input variables
    const name = req.body.name
    const lastname = req.body.lastname
    const email = req.body.email
    const password = req.body.password
    const role = req.body.role

    const newUser = new User({
      name: name,
      lastname: lastname,
      email: email,
      password: password,
      role: role
    })

    newUser.password = await bcrypt.hash(newUser.password, saltRounds)

    await newUser.save(function(err, user) {
          if (err) {
            // if a validation err occur end request and send response
            res.status(400).send({ code: 400, status: 'Bad Request', message: err.message })
          } else {
            // req.session.userId = user._id

            var userData = { userId: user._id, name: user.name, lastname: user.lastname, email: user.email, role: user.role }

            req.session.userData = userData

            res.redirect('/dashboard')
          }
        })
  },
</code></pre>



<p>And we have a default <code>get</code> route.</p>



<ul class="wp-block-list"><li>/favicon.ico<br></li></ul>



<p>Browsers will by default try to request /favicon.ico from the root of a hostname, in order to show an icon in the browser tab. As we dont use favicon so far we must avoid that these requests returning a 404 (Not Found). Here The /favicon.ico request will be catched and send a 204 No Content status.</p>



<pre class="wp-block-code"><code>// secserver.js
....
app.get('/favicon.ico', function(req, res) {
    console.log(req.url);
    res.status(204).json({status: 'no favicon'});
});
....
</code></pre>



<h3 class="wp-block-heading">3. Express App (Pug Template Version)</h3>



<p>From a functional point of view this app is pretty much the same app then the HTML version. The difference is that we use PUG templates instead of HTML in each res.send().</p>



<h4 class="wp-block-heading">Setup a seperate Database</h4>



<p>For the PUG version of my app I set up a new database to manage the users and the sessions.</p>



<pre class="wp-block-code"><code>#&gt; mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b3e7f48a-a05c-4894-87db-996cb34eb1fb") }
MongoDB server version: 4.2.3

&gt; db
test

&gt; use admin
switched to db admin

&gt; db
admin

&gt; db.auth("adminUser", "adminpassword")
1

&gt; show dbs
admin               0.000GB
config              0.000GB
express-security    0.000GB
local               0.000GB

&gt; use express-security-pug
switched to db express-security-pug

&gt; db.createUser({ user: "owner_express-security-pug", pwd: "passowrd", roles: &#91;{ role: "dbOwner", db: "express-security-pug" }] })

Successfully added user: {
    "user" : "owner_express-security-pug",
    "roles" : &#91;
        {
            "role" : "dbOwner",
            "db" : "express-security-pug"
        }
    ]
}

&gt; db
express-security-pug

&gt; exit
</code></pre>



<p>Connection string to connect to express-security-pug db using the owner_express-security-pug user.</p>



<pre class="wp-block-code"><code>mongodb://owner_express-security-pug:password@localhost/express-security-pug
</code></pre>



<h4 class="wp-block-heading">Download the code from GitHub</h4>



<p>Pls. <a href="https://github.com/prottlaender/node-part-5-express-security-with-db-pug">go to my GitHub site</a> and clone the code. Here you find some inline documentation in the code.</p>



<h4 class="wp-block-heading">Create your app home directory express-security-pug</h4>



<p>My app home directory is different to the one that is available after you cloned the code from GitHub. </p>



<pre class="wp-block-code"><code>Patricks-MBP:2020-05-15-express-security patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security

Patricks-MBP:2020-05-15-express-security patrick$ mv node-part-5-express-security-with-db-pug express-security-pug

Patricks-MBP:2020-05-15-express-security patrick$ cd express-security-pug

Patricks-MBP:express-security-pug patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security/express-security-pug
</code></pre>



<h4 class="wp-block-heading">Install PUG and use it in your app</h4>



<p>First we install <a href="https://pugjs.org/api/getting-started.html">PUG</a> as a dependency. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security-pug patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security/express-security-pug

Patricks-MBP:express-security-pug patrick$ npm install pug --save
</code></pre>



<p><a href="https://pugjs.org/api/getting-started.html">PUG</a> is already <a href="https://pugjs.org/api/express.html">fully integrated</a> into Express. Pls. read the documentation <a href="https://expressjs.com/en/guide/using-template-engines.html">how to use template engines in Express</a>. </p>



<p>After you installed PUG the view engine must be set in your main application file <em>secserverpug.js</em>.</p>



<pre class="wp-block-code"><code>// secserverpug.js
....
// use Pug Template Engine
app.set('view engine', 'pug')
app.set('views', './views')
....
</code></pre>



<p>These instructions tell your app that PUG template engine is used and that the templates can be found in <code>/views</code> directory.</p>



<h4 class="wp-block-heading">PUG Directory setup</h4>



<p>In <code>/views</code> I setup the templates for home, login, registration and an error template. </p>



<p>In <code>/views/includes</code> I setup the files containing HTML or JavaScript. These can be included in the templates. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security-pug patrick$ ls -l
total 128
-rw-r--r--    1 patrick  staff    771  1 Jul 06:04 README.md
drwxr-xr-x    5 patrick  staff    160 29 Jun 05:26 database
drwxr-xr-x  150 patrick  staff   4800 29 Jun 06:11 node_modules
-rw-r--r--    1 patrick  staff  47547 29 Jun 06:11 package-lock.json
-rw-r--r--    1 patrick  staff    367 29 Jun 06:11 package.json
-rw-r--r--    1 patrick  staff   4393  2 Jul 05:34 secserverpug.js
drwxr-xr-x    3 patrick  staff     96 29 Jun 05:26 static
drwxr-xr-x    8 patrick  staff    256  2 Jul 05:45 views

Patricks-MBP:express-security-pug patrick$ ls -l views
total 40
-rw-r--r--  1 patrick  staff   549 30 Jun 05:35 dashboard.pug
-rw-r--r--  1 patrick  staff   522  2 Jul 05:50 err.pug
-rw-r--r--  1 patrick  staff   420 29 Jun 05:39 home.pug
drwxr-xr-x  6 patrick  staff   192 29 Jun 05:17 includes
-rw-r--r--  1 patrick  staff   735 30 Jun 05:02 login.pug
-rw-r--r--  1 patrick  staff  1067 30 Jun 05:08 register.pug

Patricks-MBP:express-security-pug patrick$ ls -l views/includes
total 32
-rw-r--r--  1 patrick  staff   76 29 Jun 05:39 foot.pug
-rw-r--r--  1 patrick  staff  167 29 Jun 05:24 head.pug
-rw-r--r--  1 patrick  staff  489  2 Jul 05:13 nav.pug
-rw-r--r--  1 patrick  staff  420 29 Jun 05:08 script.js

Patricks-MBP:express-security-pug patrick$ 
</code></pre>



<h4 class="wp-block-heading">The responsive Website Design</h4>



<p>Each site like <em>home</em>, <em>login</em>, <em>register</em> and <em>dashboard</em> has a <strong>specific site template</strong> in <code>/views</code> directory. The site content will be defined in the <em>main section</em> of each template. PUG enables files with HTML or JavaScript to be included. This makes the <em>site templates</em> clear and easy to maintain. The <strong>includes</strong> are located in <code>/views/includes</code> directory.</p>



<p>The website is build based on a grid design and each site template has the following structure.</p>



<pre class="wp-block-code"><code>doctype html

HTML

	Head
		include includes/head.pug	
	
	Body
		
		Grid-Container
			
				Header
					include includes/nav.pug
			
				Main
					... site template specific HTML ...
			
				Footer
					include includes/foot.pug
					
		&lt;script&gt;
			  include includes/script.js

</code></pre>



<p>The design of the website is defined in the css in <code>static/css/style.css</code>.</p>



<p>Here in the css we define the <strong>Site Structure</strong> as <em>grid areas</em> consisting of header, main and footer and link them to the <em>grid-container</em>. </p>



<pre class="wp-block-code"><code>....

.header { grid-area: header; background-color: #ffffff; border-radius: 5px;}
.main { grid-area: main; background-color: #ffffff; border-radius: 5px;}
.footer { grid-area: footer; background-color: #ffffff; border-radius: 5px;}

.grid-container {
  display: grid;
  grid-template-areas:
      "header"
      "main"
      "footer";
  grid-gap: 5px;
  background-color: #d1d1e0;
  padding: 50px;
}

....
</code></pre>



<p>The <strong>Navigation</strong> is defined in the Header area of the Grid-Container and the HTML comes into the template via <code>include includes/nav.pug</code>.</p>



<pre class="wp-block-code"><code>// includes/nav.pug

//(this) refers to the DOM element to which the onclick attribute belongs to
// the a DOM element will be given as parameter to the function

a(class="burgericon" onclick="myFunction(this)")
  div(class='burgerline' id='bar1')
  div(class='burgerline' id='bar2')
  div(class='burgerline' id='bar3')

a(class='link' href='/') Home
a(class='link' href='/login') Login
a(class='link' href='/register') Register
a(class='link' href='/dashboard') Dashboard
a(class='link' href='/logout') Logout
</code></pre>



<p>So the navigation design is then defined in the css. Each navigation object is an <code>a</code> link. We have <code>a</code> links with class <code>link</code> and <code>burgericon</code>. The burgericon is used to open the navigation bar onclick when the screen is smaller than 600px (like iphone displays etc., explained below), is cosisting of 3 burgerlines and these lines are created using 3 div objects with class <code>burgerline</code>. The burgelines will be transformed with speed 0.4s when you click on the burgericon (explained below). The burgericon is not visible and aligned on the right edge. All other navigation links are visible and aligned on the left edge.<br></p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....

/* style the navigation links with float on the left (side by side) */
.header a.link {
  float: left;
  display: block;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 1.4vw;
  color: #28283e;
}

/* hover effect for each navigation link */
.header a.link:hover {
  background-color: #28283e;
  color: #ffffff;
}

/* style the burgericon link on the right */
.header a.burgericon {
  float: right;
  display: none;
  padding: 14px 16px;
}

/* style each burgerline that create the burgericon */
.burgerline {
  width: 35px;
  height: 5px;
  background-color: #28283e;
  margin: 6px 0;
  transition: 0.4s;
}
....
</code></pre>



<p>When the display screen is lower than 600px the navigation links will not be shown and the burgericon (on the right side) will be faded in instead. </p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....
/* for screens up to 600px remove the navigation links and show the burgericon instead */
@media screen and (max-width: 600px) {
  .header a.link { display: none; }
  .header a.burgericon { display: block; }
}
....
</code></pre>



<p>When you click on the burgericon the burgerlines will be transformed so that you will see a cross instead of the hamburger like icon. The 2nd burgerline with <code>id='bar2'</code> will not be shown at all while the other 2 burgelines will be rotated 45 degrees counterclockwise (burgerline with <code>id='bar1'</code>) and clockwise (burgerline with <code>id='bar1'</code>). </p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....
/* style burgerlines after on onclick event */
/* the .change class will be added onclick with classList.toggle in the JavaScript */
/* rotate first bar */
.change #bar1 {
  /* rotate -45 degrees (counterclockwise) move 15px down in Y-direction */
  transform: rotate(-45deg) translateY(15px);
}
/* fade out the second bar */
.change #bar2 {
  opacity: 0;
}
/* rotate third bar */
.change #bar3 {
  /* rotate +45 degrees (clockwise) move 15px up in Y-direction */
  transform: rotate(45deg) translateY(-15px);
}
....
</code></pre>



<p>After clicking on the burgericon, the burgerlines are transformed as described. The links of the navigation menu are displayed one below the other (float none) and aligned left.</p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....
/* for screens up to 600px and after onclick event the responsive class will be added to the header */
@media screen and (max-width: 600px) {
  /* show navigation links left with no float (links shown among themselves) */
  .header.responsive a.link {
    float: none;
    display: block;
    text-align: left;
  }
}
....
</code></pre>



<p>All onclick functionalities are controlled by the javascript which is embedded in the HTML of each site template (pls see above includes/nav.pug). In the HTML, the onclick event is initiated in the burgericon link and the function myFunction is called with <code>onclick =" myFunction(this) "</code>. With the parameter <em>this</em> the entire burgericon object is transferred to the javascript function.</p>



<p>With each click on the burger icon, the class <code>change</code> is added to each burgerline or, if available, removed. This is done by the toggle() function. If <code>change</code> is set, the hamburg icon is transformed into a cross according to the specification in the css (see above). If <code>change</code> is withdrawn with a new click, the hamburger icon is displayed again.</p>



<p>But it happens even more in the javascript when you click on the hamburger icon. The element that has the id <code>responsivenav</code> is searched for and the variable<code>reponsiveNavElement</code> is assigned to this element. Is the class of the reponsiveNavElement <code>header</code> the class<code>responsive</code> is added after clicking on the hamburger icon. If the class <code>responsive</code> is set, as described above, the links of the navigation menu are displayed one below the other (float none) and aligned left. So it applies in the css <code>.header.responsive a.link {....}</code></p>



<p>In all other cases only the class <code>header</code> is set. So it applies in the css <code>.header a.link {....}</code> and the navigation links are not shown. </p>



<pre class="wp-block-code"><code>// includes/script.js

// the (burgerlines) parameter represent the DOM element that has been given to the function
function myFunction(burgerlines) {
  burgerlines.classList.toggle('change');

  var reponsiveNavElement = document.getElementById('responsivenav');
    if (reponsiveNavElement.className === 'header') {
      reponsiveNavElement.classList.add('responsive')
    } else {
      reponsiveNavElement.className = 'header';
    }
  }

</code></pre>



<p>Finally at the end of the css we define the defaults for <em>h1</em>, for our text content, the forms, the input fields and the send buttons.<br></p>



<h3 class="wp-block-heading">Summary and Outlook</h3>



<p>In this part 4 of my little node.js series we have seen how to setup a production ready environment for our express app. I showed this using a Mac OS, but in principle this setup also applies to Linux, for example.</p>



<p>The basic setup is, to put it simply, the app runs as a service on the server in the background using a Process Manager, but has no interface to the client. This client interface regulates a reverse proxy which is upstream of the app and accepts all requests and forwards them to the app, as well as the responses from the app back to the client. The communication is SSL/TLS secured.</p>



<p>At the center of the setup is a separate local MongoDB that manages all application data. In our example, these are the users, but also the sessions. I prefer to set up my own MongoDB on my server but of course it is conceivable to use a cloud-based solution or to install another database locally.</p>



<p>The express app itself uses secure HTTP response headers so that HTTP attacks like <em>clickjacking</em>, <em>MIME type sniffing</em> or some <em>smaller XSS attacks</em> on the client are made as difficult as possible. Access to personal areas of the application is secured by session-based authentication and authorization. The session-relevant data is stored in the database and not in the browser cookie, which means additional security with regard to attacks on the client. The browser cookie only contains a hash of the session ID to query the relevant user data from the database.</p>



<p>I would like to end my node.js series with Part 4. I discussed and demonstrated the basic concepts and procedures in parts 1 to 4. Of course there will be other interesting articles on the topic node.js and web programming on <a href="https://digitaldocblog.com">Digitaldocblog</a>. Just take a look.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Node.js series Part 3. The Simple Express Blog App with MongoDB</title>
		<link>https://digitaldocblog.com/webserver/nodejs-series-part-3-the-simple-express-blog-app-with-mongodb/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 08 Apr 2020 07:00:00 +0000</pubDate>
				<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Blog-Application]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<category><![CDATA[Web-Application]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=114</guid>

					<description><![CDATA[In this Part 3 of my node.js series I rebuild the simple blog app from the last Part 2 so that a MongoDB database is used instead of a simple&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In this Part 3 of my node.js series I rebuild the simple blog app from the last <a href="https://digitaldocblog.com/webserver/nodejs-series-part-2-create-a-simple-blog-app-with-expressjs/" title="Part 2">Part 2 </a>so that a <a href="https://www.mongodb.com/">MongoDB</a> database is used instead of a simple data file. To do this, a MongoDB must first be installed locally on the development system. We also use <a href="https://mongoosejs.com/">Mongoose</a> to access the database in our express blog application. I have described in detail on <a href="https://digitaldocblog.com/singleblog?article=4">Digitaldocblog</a> how to install MongoDB in my blog post <a href="https://digitaldocblog.com/singleblog?article=4">Mongodb and Mongoose on Ubuntu Linux</a>.</p>




<p>The creation of the database and the cloning of the application root directory from my <a href="https://github.com/prottlaender/node-part-3-express-blog-with-db-V2">GitHub page</a> will be briefly described in the following step-by-step instructions. This is followed by a description of the application functionality. Then I will explain more generally how data is modeled in a database-based Expressjs application with the help of mongoose and how the data is accessed so that the more basic software architecture is understood. The relevant code of our blog app is commented. In this respect, the explanations of the individual code passages can be found in the inline documentation.</p>




<h3 class="wp-block-heading">Create a MongoDB Database</h3>



<p>After the installation of MongoDB you have started the <em>mongod</em> service on your system. It is very important that you setup MongoDB with client authentication enabled. You have also created an admin user with a password on your admin default db. Pls. follow the description in my article <a href="https://digitaldocblog.com/singleblog?article=4">Mongodb and Mongoose on Ubuntu Linux</a>.</p>




<p>Then you create a database for your project and a user for your database using the <em>mongo</em> command on the console.</p>




<pre class="wp-block-code"><code>Patricks-MBP:digitaldocblog-V3 patrick$ mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4e8c592e-104d-48ef-b495-62129e446d23") }
MongoDB server version: 4.2.3

&gt; db
test

&gt; show dbs

&gt; use admin
switched to db admin

&gt; db.auth("admin", "YOUR-ADMIN-PASSWD")
1

&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB

&gt; use YOUR-DB-NAME
switched to db YOUR-DB-NAME

&gt; db
YOUR-DB-NAME

&gt; db.createCollection("col_default")
{ "ok" : 1 }

&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB
YOUR-DB-NAME	    0.000GB

&gt; db.createUser({ user: "YOUR-DB-USER", pwd: "YOUR-DB-USER-PASSWD", roles: [{ role: "dbOwner", db: "YOUR-DB-NAME" }] })
Successfully added user: {
	"user" : "YOUR-DB-USER",
	"roles" : [
		{
			"role" : "dbOwner",
			"db" : "YOUR-DB-NAME"
		}
	]
}

&gt; show users
{
	"_id" : "YOUR-DB-NAME.YOUR-DB-USER",
	"userId" : UUID("ef080b98-849f-41f4-b561-a658a88e4595"),
	"user" : "YOUR-DB-USER",
	"db" : "YOUR-DB-NAME",
	"roles" : [
		{
			"role" : "dbOwner",
			"db" : "YOUR-DB-NAME"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB
YOUR-DB-NAME	    0.000GB
&gt; 

&gt; exit
bye

</code></pre>



<p>If you enter the command <em>mongo</em> on the console, the MongoDB client connects to the MongoDB service. The MongoDB client is the so-called MongoDB shell with which the user can work on the console. After the connection is established, the MongoDB shell is displayed in the terminal and with the command <em>db</em> we see the output <em>test</em>. </p>




<p>The <em>db</em> command shows the database you are currently connected to. test is the default database and is actually no longer used. The <em>show dbs</em> command shows all available databases. Since we have activated client authentication nothing is shown here because we are not yet authenticated.</p>




<p>With <em>use admin</em> we switch to admin db and authenticate ourselves with <em>db.auth</em>. After we have entered the <em>db.auth</em> command in the MongoDB shell as described, the shell shows us a 1. This shows that the authentication was successful. As admin user we can now show all databases with <em>show dbs</em>.</p>




<p>With the command <em>use YOUR-DB-NAME</em> we create the database YOUR-DB-NAME and also switch from the database admin to the database YOUR-DB-NAME. With the command <em>db.createCollection</em> I always create a default collection in YOUR-DB-NAME to display the new database YOUR-DB-NAME with the <em>show dbs</em> command in the MongoDB shell. If you simply create the database and no collection the new database is not shown with the <em>show dbs</em> command. </p>




<p>Then I create a user with <em>db.createUser</em> for my new database YOUR-DB-NAME, assign the role <em>dbOwner</em> to this user and the password <em>YOUR-DB-USER-PASSWD</em>.</p>




<p>The database YOUR-DB-NAME is now created and with <em>exit</em> we leave the MongoDB shell.</p>




<h3 class="wp-block-heading">Create the application root directory</h3>



<p>Clone the Simple Blog App from my <a href="https://github.com/prottlaender/node-part-3-express-blog-with-db-V2">GitHub page</a> and then switch to the directory <em>node-part-3-express-blog-with-db-V2</em>.</p>




<pre class="wp-block-code"><code>Patricks-MBP:~ patrick$ cd node-part-3-express-blog-with-db-V2

</code></pre>



<p>The application root directory then looks like this.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l
total 72
-rw-r--r--   1 patrick  staff    768 9 Apr 05:19 README.md
-rw-r--r--   1 patrick  staff   2162 9 Apr 05:19 blog.js
drwxr-xr-x   6 patrick  staff    192 9 Apr 05:19 database
drwxr-xr-x   3 patrick  staff     96 9 Apr 05:19 modules
drwxr-xr-x  77 patrick  staff   2464 9 Apr 05:19 node_modules
-rw-r--r--   1 patrick  staff  22302 9 Apr 05:19 package-lock.json
-rw-r--r--   1 patrick  staff    188 9 Apr 05:19 package.json

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l database
total 16
drwxr-xr-x  4 patrick  staff  128  9 Apr 05:19 controllers
-rw-r--r--  1 patrick  staff  704  9 Apr 05:19 db_.js
drwxr-xr-x  4 patrick  staff  128  9 Apr 05:19 models

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l database/controllers
total 40
-rw-r--r--  1 patrick  staff  9464 9 Apr 05:19 blogController.js
-rw-r--r--  1 patrick  staff  5306 9 Apr 05:19 userController.js

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l database/models
total 16
-rw-r--r--  1 patrick  staff  1574 9 Apr 05:19 blogModel.js
-rw-r--r--  1 patrick  staff  1216 9 Apr 05:19 userModel.js

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l modules
total 8
-rw-r--r--  1 patrick  staff  175  9 Apr 05:19 logger.js

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ 

</code></pre>



<p>Read the README.md. After you run <em>npm install</em> You must adapt your database connection string and rename <em>database/db_.js</em> into <em>database/db.js</em>. Your database connection string ist as follows.</p>




<pre class="wp-block-code"><code>mongodb://YOUR-DB-USER:YOUR-DB-USER-PASSWD@localhost:27017/YOUR-DB-NAME

</code></pre>



<p>The application should run with <em>npm blog.js</em>. The application code is explained and commented inline. In addition, I will explain details in the following chapters.</p>




<h3 class="wp-block-heading">How does the application work ?</h3>



<p>The application looks like a very simple web application but already contains a lot of program logic. This program logic is mainly contained in the two user and blog controllers. </p>




<p>The <strong>application data</strong> are <em>users</em> and <em>blogs</em>. These data are stored in a MongoDB and can be created, changed or deleted by the application. When data is entered, i.e. when data sets are created and when data fields are changed, <strong>input validation</strong> takes place. This input validation is based on the mongoose built in input validation and especially for string values on the mongoose custom validation, whereby it is checked whether the input of a string corresponds to a defined regular expression (<a href="https://regex101.com/">regex for ECMA Java Script</a>).</p>




<p>The primary identifier for users is the email address. The <strong>users must be unique</strong> and can only be created if the email address is not already assigned to an existing user.</p>




<p>The users can be blog authors and therefore they have a reference to each blogid whose author they are. Whenever a blog post is created, the application checks whether a user with the specified email address already exists and whether the email address already belongs to an existing user. If the user does not exist or the specified email address belongs to an existing user, the blog post cannot be created. If a user exists and it is also his own email address, the new blog post can be created and the author&#8217;s name, first name and email address are stored on the blog in the database. In parallel the blogid of the new blog post is stored as reference on the user object.</p>




<p>We thus have a <strong>reference from users to their blogs where they are authors</strong> and a reference from blogs to the users or blog authors. When creating a blog, it is a condition that the author exists as a user in the database, but it may still be that we have blogs with authors in the database for which there is no longer a user. This is because it is possible to <strong>delete a user without deleting all blogs where the user is the author</strong>. Therefore it may still be that we have blogs with authors in the database for which there is no longer a user.</p>




<p>Consequently, when a blog is deleted, it is checked whether the author exists as a user. If the user no longer exists, the blog entry will still be deleted. If there is a user in the database, the blog post is deleted and the reference blogid on the user is deleted at the same time.</p>




<p>But we can also <strong>update the email address of a user</strong>. This is a very realistic use case because email addresses can change for users and consequently a user would like to change their changed email address accordingly in our application. Because the email address is the unique identifier of a user, we have to change the email address both on the user and on all blogs where the user is entered as the author. </p>




<p>Our application can also display blogs. All blogs are displayed or only the blogs for a specific year or month or only for a defined date. In order to display the blogs in this way, the blog data are selected accordingly from the database.</p>




<p>In addition, the application also displays a homepage and an about page, which have no further significance.</p>




<h3 class="wp-block-heading">Data Models</h3>



<p>To organize our application data in the <a href="https://www.mongodb.com/">MongoDB</a> we define so called models using <a href="https://mongoosejs.com/">Mongoose</a>. Models contain the essential data structure and data definitions that a database collection should have. Our database will have 2 collections one for the <em>users</em> and one for the <em>blogs</em>.</p>




<p>For each database collection exactly one model is defined in a seperate file. In our example, we need one model for each of the two collections <em>col_users</em> and <em>col_blogs</em>. </p>




<p>For <em>col_users</em> the model is defined in the file </p>




<ul class="wp-block-list">
	<li><em>database/models/userModel.js</em><br></li>
</ul>



<p>for the <em>col_blogs</em> the model is defined in the file </p>




<ul class="wp-block-list">
	<li><em>database/models/blogModel.js</em>.<br></li>
</ul>



<p>I would like to show a standard model here.</p>




<pre class="wp-block-code"><code>// model.js
....

mongoose = require('mongoose')
var Schema = mongoose.Schema

var dataSchema = new Schema ({ key1:..., key2:..., ..., keyN:...}) 

var Data = mongoose.model('col_data', dataSchema)

module.exports = Data

</code></pre>



<p>With <strong>mongoose.Schema</strong> we create a database Schema. With <strong>new Schema(&#8230;)</strong> we define exactly what the Schema looks like and which keys or data fields are defined for each data object that will be stored in the collection. The new Schema is stored in a variable that typically describes the purpose of the new Schema (userSchema or blogSchema in our app). With <strong>mongoose.model()</strong> we create the model and map it to the database collection. The first argument in the <em>mongoose.model()</em> function is the singular name of the database collection. So if we create the model with <em>col_data</em> mongoose is looking for <em>col_datas</em> collection in the database. The second argument in the callback is the new Schema that we defined before. This model will be stored in the Variable <em>Data</em> and exported with <strong>module.exports</strong>.<br/></p>




<p>It is extremely important that all input data are validated before the data is saved in the database. This ensures that the application only processes validated data.</p>




<p>In the model definition of or blog application, I mark all <strong>auto data fields</strong> with a preceding underscore. With auto data fields, the value is either created by the database (like the id) or a default value is always set (like created). This means that these data fields are never manipulated by data input.</p>




<p><strong>Input data fields</strong> are subject to mongoose built-in validation. The topic of input validation is described in great detail in the <a href="https://mongoosejs.com/docs/validation.html">mongoose documentation</a>. Nevertheless, I would like to go into a few points of input validation here.</p>




<p>Basically the specification of validation properties takes place in the database Schema definition per key of the data object. We have built-in validation properties or short validators like <em>required</em>, <em>minlength</em> or <em>maxlength</em> but also the option to define a custom validation function using the property <em>validate</em>. Here in the example below the custom validation function of the key &#8222;name&#8220; checks the input for the match with a <a href="https://regex101.com/">regex</a>. If the input value does not correspond to the <a href="https://regex101.com/">regex</a>, the function return  false and the validation has failed. If the function return true, the data can be saved and the validation was successful.</p>




<pre class="wp-block-code"><code>// model.js

....

mongoose = require('mongoose')
var Schema = mongoose.Schema

var dataSchema = new Schema ({ 

 // define the auto data fields
  _id: {
    type: Schema.ObjectId,
    auto: true
  },

  _created: {
    type: Date,
    default: Date.now()
  },

  // define the input data fields
  name: {
    type: String,
    required: true,
    // input string validation function
    // input sting must match regex criteria
    validate: function(name) {
      return /^[a-zA-Z0-9üÜäÄöÖ.’-]+$/.test(name)
    }
  },  
....

})

....

</code></pre>



<h3 class="wp-block-heading">Data Controllers</h3>



<p>To organize our application data accesses and data manipulations using Mongoose we define so called data controllers in separate files. </p>




<p>In principle, each <em>data model</em> that we have defined in our <em>data model files</em> are representing a <em>data perimeter</em>. A data perimeter can be accessed via so-called <em>controller modules</em> which are defined in separate <em>controller files</em>. These controller modules are in turn defined as <em>controller functions</em> in the corresponding <em>data controller</em>. </p>




<p>These controller functions define the <em>data operations</em> like search queries, create, update and delete data within the controller functions. These data operations are defined in a try &#8230; block and if an error occurs when accessing the data, this error is forwarded to the catch &#8230; block. This catch block then takes over the error handling. I do this try catch thing for all operations except for save(). With save() errors are handled directly in the callback.</p>




<p>In addition to the req and res parameter, the controller functions also receive next as a parameter. This is required to call the default error handler of the server which is defined in our main application file blog.js. </p>




<p>If the request cannot be ended with a response due to an <strong>error</strong> accessing the data, then the request will be passed to the catch block. The catch block call the next(error) function with the error as parameter in order to pass control to the <strong>default error handler</strong> to respond to the request. </p>




<p>If the request cannot be ended with a response due to an <strong>err</strong> accessing the data, then the request will also be passed to the catch block. But the catch block then call an <strong>individual error handler</strong> to respond to the request. </p>




<p>In our application we have the <em>user data perimeter</em> and the <em>blog data perimeter</em> and for each of these different data perimeters there is a separate data controller.</p>




<h4 class="wp-block-heading">User Controller</h4>



<p>The <strong>user data controller</strong> exists to control data access and data manipulations for the <em>user data perimeter</em>.</p>




<ul class="wp-block-list">
	<li>database/controllers/userController.js<br></li>
</ul>



<p>The user data controller contain the following <strong>user controller modules</strong> and functions.</p>




<h4 class="wp-block-heading">createUser</h4>



<p>The createUser function create a new User object in the database. We try first to find a user with the given email address. </p>




<p>If an error occurs here in the query, the request error is passed to the default error handler via catch block. If no error occurs, either a user is found or not. If a user is found, the user cannot be created with createUser and the response is 400 bad request. </p>




<p>If no user is found, the user can be created. This means that the newUser object is saved and the input data is validated when it is saved. If an input data validation error occurs, we will respond with 400 bad request. otherwise there is a 200 ok response and the new user object has been successfully created in the database.</p>




<h4 class="wp-block-heading">updateUserEmail</h4>



<p>With the updateUserEmail function, the email address of a user object can be changed. In parallel also the author email will be adapted on the blog objects where the user is author of blogs. </p>




<p>First the user is searched for with his existing email address. If the function runs on an error, the request and the error are passed on to the default error handler with catch. </p>




<p>If no user is found, we respond with 400 bad request. If, on the other hand, a user is found, the email address can be updated by saving the user object with the new email address. When saving, the input validation takes place again. Only if the input validation was successful the storage of the user object is completed.</p>




<p>Now the email address must be updated on the blogs where the user is the author. </p>




<p>For this we are looking for all blogs where the author email corresponds to the existing email address of the user. If the search runs for an err, we will respond with an individual 502 bad gateway this time because the request has been partially processed up to this point. The email address on the user object has already been updated, but the data for updating the author email addresses on the blogs cannot be queried. </p>




<p>If there is no err in the blog query, the user may not be the author of any blog. Then we answer with 200 ok and confirm that only the email address on the user object has been changed. </p>




<p>If, on the other hand, the user is the author of blogs, we use the updateMany() function to update the email address of any blog found.</p>




<p>This updateMany() function receive a filter object with the previously existing email address of the user as first parameter and then the update object to replace this existing email address with the new email address of the user. This operation is executed on any blog found in the database and is also carried out in a try block. If an err occurs, the request is passed on for individual error handling to the catch block. Here in the catch block we answer with a 502 bad gateway because the update on the user object has been already performed successfully but the update of the author email address on the blogs found was not successful because the updateMany() operation failed. </p>




<p>If the blog update process was successful, we respond with 200 ok. In this case the email address has been changed on the user object and also on his blogs.</p>




<h4 class="wp-block-heading">removeUser</h4>



<p>With removeUser function a user object can be removed from the database. We try first to find the user that should be removed with the given email address. If an error occurs, the request error is passed to the default error handler via catch block. </p>




<p>If no error occurs, either a user is found or not. </p>




<p>If no user is found, the user cannot be removed and the response is 400 bad request. </p>




<p>If the user to be removed has been found we try to delete this user from the database using the deleteOne() function. If an error occurs here, the request error is also passed to the default error handler via catch block. </p>




<p>If the deletion was successful we respond with 200 ok.</p>




<h4 class="wp-block-heading">Blog Controller</h4>



<p>The <strong>blog data controller</strong> exists to control data access and manipulations for the <em>blog data perimeter</em>.</p>




<ul class="wp-block-list">
	<li>database/controllers/blogController.js<br></li>
</ul>



<p>The blog data controller contain the following <strong>blog controller modules</strong> and functions.</p>




<h4 class="wp-block-heading">createBlog</h4>



<p>The createBlog module create a new blog object in the database and update the new blog id reference on the author user object. </p>




<p>The new blog object can only be created if the author data email, first- and lastname match with a user object in the database. So the author must already exist as a user in the database. </p>




<p>We try first to find a user with the author email address. If an error occurs, the request error is passed to the default error handler via catch block. If no error occurs, either a user is found or not. </p>




<p>If no user is found, we respond with 400 bad request. </p>




<p>If a user is found, it is checked whether the provided first name or last name does not match the first name or last name of the user in the database found with the given email address. If one of the names does not match, the condition is false and we send a 400 bad request. </p>




<p>If both names are the same, there is a perfect match of email, first name and last name and the provided author data are validated. Then the blog object can be saved and the blog input data will be validated.</p>




<p>If an input data validation error occurs, we will respond with 400 bad request. </p>




<p>In any other case the new blog has been saved to the database and we try to update the user object by adding the new blog id on the user object as a blog reference. Therefore, we try to use the updateOne() function to find the user object based on the author&#8217;s email address to add the blog id of the newly created blog object as a blog reference.</p>




<p>This operation is carried out in a try block and if an err occurs, it is passed on to the catch block. In case of an err we answer with a 502 bad gateway. The blog object is created but the user object is still not updated because the updateOne() operation was not successful. If the updateOne() operation was successful we respond with 200 ok.</p>




<h4 class="wp-block-heading">removeBlog</h4>



<p>The removeBlog module remove a blog object from the database and update the user object by removing the relevant blog id reference on the author user object. </p>




<p>We try to find a blog object that should be removed based on the blog title. If an error occurs during that query the default error handling function will be invoked via the catch block and next(error). In case of no error the query return one blog object or null which means that no blog object has been found. </p>




<p>If no blog has been found we respond with 400 bad request. </p>




<p>If the query was successful and we found a blog object we try to find a user based on the author email address. If an error occurs the default error handling function will be invoked via the catch block. In case of no error the query return one user object or no user object.</p>




<p>If we have no user object found that mean that the author of the blog is no longer a user in our application. In this case we try to remove only the blog using the deleteOne() function. If this blog deletion function fail we have no success and an error. We catch this error in the catch block to invoke the default error handler function. If the deleteOne() function can be executed successfully, we respond with ok 200. The blog object with the title has been deleted. </p>




<p>If we have found a user object this means that this user is the author of the blog object we want to delete. In this case we first try to remove the blog object using the deleteOne() function and catch the error in the catch block to invoke the default error handler function when the execution of deleteOne() fail. </p>




<p>When the blog deletion was successful, we also try to delete the blog id as a reference on the user object using the updateOne() function. If updateOne throw an err we go ahead with catch and respond with 502 bad gateway as the blog could be removed but the user object update failed. </p>




<p>If the user update of the user object was successful we respond with 200 ok.<br/></p>




<h4 class="wp-block-heading">returnAllBlogs</h4>



<p>The returnAllBlogs module is a function that searches all blog objects in the database and returns them in an array blogs when the requested url is /blogs. If the requested url is different than the next() function will be called to transfer to the next request handler in the row.</p>




<p>We try to search for all blog objects using the find() function. This find function return an error in case the query fail. In this case the catch block will invoke the default error handler function. In case the query was successful the function return an array blogs including the blog objects. </p>




<p>In case the array is empty or better the length is equal to 0 no blog object has been found in the database and we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into a blog array and return this blog array with 200 ok.</p>




<h4 class="wp-block-heading">returnYearBlogs</h4>



<p>The returnYearBlogs module is a function that searches blog objects of a certain year in the database and returns them in an array blogs when the requested url is /blogs/year. If the requested url is different than the next() function will be called to transfer to the next request handler in the row.</p>




<p>We try to search for all blog objects in a year using the find() function and return an error in case the query fail. In this case the catch block will invoke the default error handler function. </p>




<p>In case the query was successful the function return a query array blogs including the blog objects found for the relevant search criteria. In case no blog object has been found (length of blogs is equal to 0) in the database we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into another blog array and return this blog array with 200 ok.</p>




<h4 class="wp-block-heading">returnMonthBlogs</h4>



<p>The returnMonthBlogs module is a function that searches blog objects of a certain year and month in the database and returns them in an array blogs when the requested url is /blogs/year/month. If the requested url is different than the next() function will be called to transfer to the next request handler in the row.</p>




<p>We try to search for all blog objects in a year and month using the find() function and return an error in case the query fail. In this case the catch block will invoke the default error handler function. </p>




<p>In case the query was successful the function return a query array blogs including the blog objects found for the relevant search criteria. In case no blog object has been found (length blogs is equal to 0) in the database we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into another blog array and return this blog array with 200 ok.</p>




<h4 class="wp-block-heading">returnDateBlogs</h4>



<p>The returnDateBlogs module is a function that searches blog objects of a certain date in the database and returns them in an array blogs. </p>




<p>As this is the last routing handler in the app.get() routing function where the path is defined as /blogs/:year?/:month?/day? the requested url matches this definition or not. </p>




<p>In case the requested url is something like /blogs/year/month/day/<strong>else</strong> the url is not defined and then the default route error handler will be invoked and return 404 Not found. </p>




<p>In case the requested url path match /blogs/year/month/day we try to search for all blog objects for the date using the find() function and return an error in case the query fail. In case of an error the catch block will invoke the default error handler function. </p>




<p>In case the query was successful the function return a query array blogs including the blog objects found for the relevant search criteria. </p>




<p>In case no blog object has been found (length blogs is equal to 0) in the database we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into another blog array and return this blog array with 200 ok.</p>




<h3 class="wp-block-heading">Data operations in detail</h3>



<p>Our application perform the following data operations.</p>




<ul class="wp-block-list">
	<li>create data</li>
	<li>search and return data</li>
	<li>update data</li>
	<li>delete data <br></li>
</ul>



<p>These operations will be implemented in the controller modules. We use the following functions to perform these operations.</p>




<ul class="wp-block-list">
	<li>save()</li>
	<li>find()</li>
	<li>findOne()</li>
	<li>updateOne()</li>
	<li>updateMany()</li>
	<li>deleteOne()<br></li>
</ul>



<p>If we want to <strong>create</strong> a new Data object we call <em>new Data(  &#8230;  )</em> and apply the key  specifications according to the Schema defined in the model. </p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: Please note that we are using new Data(  &#8230;  ) here because we export <em>Data</em> in the above model example definition. If you look in the model files of our blog app, you will notice that I export in the user model <em>User</em> and in the blog model <em>Blog</em>. Consequently, for example, when creating a new user object in the user data controller, the call new User(  &#8230;  ) is made.</p>
</blockquote>



<p>The function <strong>save()</strong> receive a callback function with <em>error</em> as first parameter and <em>data</em> as second parameter. Within the callback we can work with <em>error</em> as the error object and with <em>data</em> as the data object that will be saved in the database. With save(), error handling takes place directly in the call back function using the <em>if (error) &#8230; else &#8230;</em> block.</p>




<pre class="wp-block-code"><code>// controller.js

newData = new Data({key1:..., key2:..., ..., keyN:...})

newData.save(function(error, data) {
	if (error) {

	// do something when an error occurs

	} else {

	// do what you need to do when the creation was successful

	} 
})

</code></pre>



<p>If we want to <strong>search and return data</strong> we call <em>find()</em> or <em>findOne()</em>. </p>




<p>If we expect that a search return several data objects as a result we are using the <em>find()</em> function. </p>




<p>The <em>find()</em> function is covered with the <em>try &#8230; catch &#8230;</em> blog. </p>




<p><strong>find()</strong> receive as first parameter a filter object as search criteria and as second parameter a callback function with <em>error</em> as first parameter and <em>data</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>data</em> which is an array containing all the data objects that have been found in the database. In case no data objects were found the <em>data array</em> is empty. In case the function fail we catch the error.</p>




<p>Suppose you want to search in <strong>Data</strong> perimeter for data objects that have a specificName. Then we pass the filter object  name: specificName  and then the callback function(error, data) &#8230; to the Data.find() function. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithName = { name: specificName }

try {

	Data.find(searchDataWithName, function(error, data) {

	if (data.length == 0) {

	// do something when no data have been found 

	} else {

	// do something with the data array that have been found 

	}

	})

} catch (error) {

// do something when an error occurs

}

</code></pre>



<p>If a search should return only one data object as a result we are using the <em>findOne()</em> method.</p>




<p>The <em>findOne()</em> function is covered with the <em>try &#8230; catch &#8230;</em> blog. </p>




<p><strong>findOne()</strong> receive as first parameter a filter object as search criteria and as second parameter a callback function with <em>error</em> as first parameter and <em>data</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>data</em> which is the object that has been found in the database. In case no data object has been found the value of data is null. In case the function fail we catch the error.</p>




<p>Suppose you want to search in <strong>Data</strong> perimeter for one data object that has a specificName. Then we pass the filter object  name: specificName  and then the callback function(error, data) &#8230; to the Data.findOne() function. </p>




<pre class="wp-block-code"><code>// controller.js


// create the filter object
var searchDataWithName = { name: specificName }

try {

Data.findOne(searchDataWithName, function(error, data) {

	if (!data) {

	// do something when no data have been found
	
	} else {

	// do something with the data in the data object that have been found 

	} 

	})

} catch (error) {

// do something when an error occurs

}



</code></pre>



<p>If we want to <strong>update</strong> an existing Data object we search the Data object, apply the changes and then call <em>save()</em>. We can also use <em>updateOne()</em> or <em>updateMany()</em>. </p>




<p>If we do search and <strong>save()</strong> the data object first must be found in the database and will then be returned using the <em>findOne()</em> function. Then we can apply the changes to one or more data attribute values i.e. update the email address of a user and then call save() to save the updated data object back into the database. This procedure has the advantage that input validation is used with save() and is therefore recommended whenever we receive changes directly as input values and these input values must be validated. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithName = { name: specificName }

try {

	Data.findOne(searchDataWithName, function(error, data) {

	if (!data) {

	// do something when no data have been found
	
	} else {

		// specify the update value
		var updateEmail = newEmail
	
		// update the value
		data.email = updateEmail

		data.save(function(err, updatedData) {

			if (err) {

			// do something when an err occurs
			
			} else {

			// do something when the update was successful

			}
		})
	} 
	})

} catch (error) {

// do something when an error occurs

}

</code></pre>



<p>If we use updateMany() or updateOne() the data objects or the one data object will be looked up and updated in the database in one step. The data object(s) will <strong>not be returned</strong>. This makes processing faster and saves network resources.</p>




<p>The functions updateMany() and updateOne() are both covered with the <em>try &#8230; catch &#8230;</em> blog. </p>




<p><strong>updateMany()</strong> receive as first parameter a filter object as search criteria, as second parameter the update object and as third parameter a callback function with <em>error</em> as first parameter and <em>result</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>result</em> which is an object containing data about the processing result  n: 1, nModified: 1, ok: 1 . This mean n objects found, n objects modified and the processing was ok (ok: 0 if the processing failed).</p>




<p>Suppose you want to find in <strong>Data</strong> perimeter for data objects that have a specificName and update all objects found with specificNewName. Then we pass the filter object  name: specificName , the update object  name: specificNewName  and then the callback function(error, result) &#8230; to the Data.updateMany() function. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithName = { name: specificName }

// create the update object
var updatedName = { name: specificNewName }

....

try {
      
   Data.updateMany(
      	
     searchDataWithName, 
      	
     updatedName, 
      	
     function(err, result) {
      
       // do something with the result
          
     })
     
} catch (err) {
     	
// do something with the err

}

....

</code></pre>



<p><strong>updateOne()</strong> also receive as first parameter a filter object as search criteria, as second parameter the update object and as third parameter a callback function with <em>error</em> as first parameter and <em>result</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>result</em> which is an object containing data about the processing result  n: 1, nModified: 1, ok: 1 . This mean n objects found, n objects modified and the processing was ok (ok: 0 if the processing failed).</p>




<p>Suppose you want to find in <strong>Data</strong> data perimeter for one data object that has a specificName and you want to update this single object with specificNewName. Then we pass the filter object  name: specificName , the update object  name: specificNewName  and then the callback function(error, result) &#8230; to the Data.updateOne() function. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithEmail = { name: specificEmail }

// create the update object
var updatedEmail = { name: specificNewEmail}

try {
   
   Data.updateOne(
      	
     searchDataWithEmail, 
      	
     updatedEmail, 
      	
     function(err, result) {
      
     // do something with the result
          
    })
     
} catch (err) {

// do something with the err

}

....

</code></pre>



<p>If we want to <strong>remove</strong> an existing Data object we search for the data object using <em>findOne()</em> to get the data object returned, and then call <em>deleteOne()</em>. </p>




<p>We do this 2 step approach i.e. in <em>removeBlogs</em> because we use the returned blog object to determine  first the id of the blog object and then use it to find and update the user object. You can do this in one single step only by using <em>deleteOne()</em>, but take into account that you will not receive a data object with which further queries or updates can be carried out.</p>




<p><strong>deleteOne()</strong> receive as first parameter a filter object as search criteria and as second parameter a callback function with <em>error</em> as first parameter and <em>result</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>result</em> which is an object containing data about the processing result  n: 1, deletedCount: 1, ok: 1 . This mean n objects found, n objects deleted and the processing was ok (ok: 0 if the processing failed). You can use the result object in the callback to check if the object to be removed has been found or not. But this an operation we don&#8217;t need to perform because we are using the 2 step approach with findOne() and then deleteOne().</p>




<pre class="wp-block-code"><code>....

if (result.n == 0) {
  // do something if no object to be removed has been found
} else {
  // do something when the delete was successful
}

....

</code></pre>



<p>Suppose you want to find in <strong>User</strong> data perimeter for a data object that has a specificName and you want to remove this object from the database. Then we pass the filter object  name: specificName  and then the callback function(error, result) &#8230; to the User.deleteOne() function. </p>




<pre class="wp-block-code"><code>// contoller.js

/ create the filter object
var searchDataWithName = { name: specificName }

try {

	User.findOne(searchDataWithName, function(error, user) {

	if (!user) {

	// do something when no data have been found
	
	} else {
	
		try {
		
		User.deleteOne(searchDataWithName, function(error, result) {
		
			// do something when the delete was successful
		
		})
		
		
		} catch (error) {
		
		// do something when an error occurs		
		}		
}
})


} catch (error) {

// do something when an error occurs

}

</code></pre>



<h3 class="wp-block-heading">HTTP request Routing</h3>



<p>In our application main file <em>blog.js</em> we define routes to process HTTP POST and HTTP GET requests.</p>




<p><strong>HTTP POST requests</strong> are routed using the app.post(&#8218;routingPath&#8216;, routingHandler) method. </p>




<p>During the <strong>create-, update- and remove data</strong> operations app.post() routes are called and the request and response objects are transferred to the corresponding routingHandler to take over the request handling. The request body contain all relevant input data to process the request. </p>




<p>The routingHandler then calls the controller module and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends the response. </p>




<p>So for example if an HTTP POST request is made to the path <em>/createusers</em> the app.post(&#8218;/createusers&#8216;, userController.createUser) route is called and the <em>createUser</em> module take over the complete processing. </p>




<pre class="wp-block-code"><code>// blog.js

....

// load database controllers
const userController = require('./database/controllers/userController');
const blogController = require('./database/controllers/blogController');

....

// define routes (routing table)

....

app.post('/createusers', userController.createUser)

app.post('/updateuseremail', userController.updateUserEmail)

app.post('/removeusers', userController.removeUser)

app.post('/createblogs', blogController.createBlog)

app.post('/removeblogs', blogController.removeBlog)

....

</code></pre>



<p>You have to imagine it in reality with a real web application like this: On a website there is an HTML form and the end user of the application can enter user data such as last name, first name and email address to add for example a new user in the application or in the application database. The moment the user of the application clicks on the send button, the data entered in the form is transferred to the route /createusers with HTTP POST which means that the relevant app.post(&#8218;/createusers&#8216;, userController.createUser) function is called to handle this HTTP POST request. </p>




<p>Unfortunately we are not yet dealing with a real web application because there is no HTML form until now. This is exactly where <a href="https://www.postman.com/">Postman</a> comes in to test an HTTP POST action. In principle, Postman replaces the form. With Postman I can (amongst other things) transfer HTTP POST requests to the application and thus I also transfer the request body. It is therefore necessary that you familiarize yourself with <a href="https://www.postman.com/">Postman</a> to test the applications app.post() routes.</p>




<p><strong>HTTP GET requests</strong> are routed using the app.get(&#8218;routingPath&#8216;, routingHandler) method.</p>




<p>So for example if an HTTP GET request is made to the path <em>/</em> the app.get(&#8218;/&#8216;, routingHandler) route is called and the <em>routingHandler</em> take over the complete processing and send directly the response. The same happens when an HTTP GET request is made on the route <em>/about</em>. This is easy and not spectacular.</p>




<pre class="wp-block-code"><code>// blog.js

....

// load database controllers
const userController = require('./database/controllers/userController');
const blogController = require('./database/controllers/blogController');

....

// define routes (routing table)

....

app.get('/', (req, res) =&gt; {
  res.send('Hello, this is the Blog Home Page.')
})

app.get('/about', (req, res) =&gt; {
  res.send('Hello, this is the Blog About Page.')
})

....


</code></pre>



<p>It is a bit more special when an HTTP GET request is made to the route app.get(&#8218;/blogs/:year?/:month?/:day?&#8216;, &#8230;. ). </p>




<p>The route definition here provides so-called request parameters. The <em>/blogs</em> route can be parameterized with the parameters year, month and day. The question mark behind each parameter indicates that the parameter is optional.</p>




<p>The request is forwarded to several routing handlers. </p>




<p>The first routing handler assigns the request url and the request parameters year, month and day to variables and calls next() to hand over the request to the next routing handler in the row.</p>




<p>The next routingHandler is <em>blogController.returnAllBlogs</em>. This routingHandler calls the controller module <em>returnAllBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs as response <strong>if the request url is equal to /blogs</strong> otherwise next() is called to hand over the request to the next routing handler in the row.</p>




<p>The next routingHandler is <em>blogController.returnYearBlogs</em>. This routingHandler calls the controller module <em>returnYearBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs in the specified year as response <strong>if the request url is equal to /blogs/year</strong> otherwise next() is called to hand over the request to the next routing handler in the row.</p>




<p>The next routingHandler is <em>blogController.returnMonthBlogs</em>. This routingHandler calls the controller module <em>returnMonthBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs in the specified year and month as response <strong>if the request url is equal to /blogs/year/month</strong> otherwise next() is called to hand over the request to the next routing handler in the row.</p>




<p>The next and last routingHandler is <em>blogController.returnDateBlogs</em>. This routingHandler calls the controller module <em>returnDateBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs from the specified date.</p>




<p>Any other route will end up in an error 404 Bad request. </p>




<pre class="wp-block-code"><code>// blog.js

....

// load database controllers
const userController = require('./database/controllers/userController');
const blogController = require('./database/controllers/blogController');

....

// define routes (routing table)

....

app.get('/blogs/:year?/:month?/:day?',

        (req, res, next) =&gt; {
          url = req.url
          year = req.params.year
          month = req.params.month
          day = req.params.day

          next()
        },

        blogController.returnAllBlogs,
        blogController.returnYearBlogs,
        blogController.returnMonthBlogs,
        blogController.returnDateBlogs

      )

....

</code></pre>



<h3 class="wp-block-heading">Status Handling</h3>



<p>In our application we work with the following HTTP Status codes.</p>




<ul class="wp-block-list">
	<li>code 200: status: Ok. Request completed.</li>
	<li>code 500: status: Internal Server Error. Request failed due to server error.</li>
	<li>code 400: status: Bad Request. Request failed due to wrong input data.</li>
	<li>code 404: status: Not Found. Request failed due to wrong route.</li>
	<li>code 502: status: Bad Gateway. Request partly completed but not fully completed due to missing data.<br></li>
</ul>



<h3 class="wp-block-heading">Summary and Outlook</h3>



<p>In this Part 3 of my node.js series I explained how to setup our express blog app using a MongoDB database. We learned how to create data models and controllers to control access to the data. But the blog app has still no HTML frontend or no HTML template rendering is used.</p>




<p>So in the next <a href="https://digitaldocblog.com/mac/nodejs-series-part-4-express-website-with-authentication-and-authorization-in-a-mac-production-environment/" title="Part 4">Part 4</a> of my node.js series I will introduce how to extend the blog app with an HTML interface. Therefore we implement the use of the template engine <a href="https://pugjs.org/api/getting-started.html">Pug</a>. With <a href="https://pugjs.org/api/getting-started.html">Pug</a> we can create an HTML interface for our blog application.</p>




]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Node.js series Part 2. Create a Simple Blog App with Express.js</title>
		<link>https://digitaldocblog.com/webserver/nodejs-series-part-2-create-a-simple-blog-app-with-expressjs/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 21 Mar 2020 08:00:00 +0000</pubDate>
				<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=111</guid>

					<description><![CDATA[Chapter 1: Introduction In Part 1 of my node.js series we have learned how to easily build a web server with node.js on-board resources. Lastly we installed the Express.js module&#8230;]]></description>
										<content:encoded><![CDATA[
<h3 class="wp-block-heading">Chapter 1: Introduction</h3>



<p>In <a href="https://digitaldocblog.com/webserver/nodejs-series-part-1-create-a-simple-web-server-with-nodejs/" title="Node.js series Part 1. Create a Simple Web-Server with Node.js">Part 1</a> of my node.js series we have learned how to easily build a web server with node.js on-board resources. Lastly we installed the Express.js module and configured simple routes as application end points that respond to http client requests. In this part 2 I would like to take a closer look at the most important functionalities of Express.js with you.</p>




<p>In connection with Express, terms like <em>framework</em> or <em>web api</em> keep coming up. Everyone says Express is a <em>node.js web application framework</em> which is absolutely true. But what does this mean? I would like to explain this here with my own words.</p>




<p>Developers install the Express module in the application root directory and integrate the module with the require() function in the application main file. This is done with the following command line.</p>




<pre class="wp-block-code"><code>var express = require('express')
var app = express()
</code></pre>



<p>The express module is first referenced to the variable <em>express</em> with the require() function and an express() function is exported from the express module. The express() function generates an <em>express application</em> which is stored in the variable <em>app</em>. From this moment on, the developer has a whole range of <em>Express Features</em> available that can be used in the web application that is to be built. The range of express features is provided by the <strong><a href="https://expressjs.com/">Express Framework</a></strong>.</p>




<p>The features provided relate to the development of web applications. That means all these features from the Express Framework are designed to program the response behavior of a web server to requests from a client exactly as it is desired. These features are essentially about <em>Routing-</em> and so-called <em>Middleware-functionalities</em>.</p>




<p>The <strong>Routing</strong> tools in the Express Framework enable the developer to program the response behavior of the web server to the request for a special <em>application end point</em>. An application end point is a route that is e.g. defined as &#8222;/&#8220; or &#8222;/about&#8220;. The response from the server should be different here. The developer can program the end points in a very simplified way so that the request for &#8222;/&#8220; is answered by the server with the <em>Home Page</em>, the request for &#8222;/about&#8220; is answered with the <em>About Page</em>. The <strong>Request-</strong> and <strong>Response Objects</strong> are very central to the routing tools. The developer can access the properties of these objects using various methods and thus program his end points accordingly.</p>




<p>To continue the example above the server immediately responds to the client&#8217;s request and delivers either the <em>Home Page</em> or the <em>About Page</em>. If the server should process after the request and before the response some code, we are talking about <strong>Middleware</strong>. Express offers various methods to access <em>express internal middleware</em> and then switch it between the request and the response. You can also program your <em>own middleware</em> functions, which can then be integrated into the application with the require() function.</p>




<p>All in all, Express is a very powerful framework that is all about programming web servers or web applications. The Express Features serve as an <em>application programming interface</em> between the client and server and that is why these features are also called <strong>Express web api</strong>. We will take a closer look at <em>Express Routing</em> and <em>Express Middleware</em> in this Part 2 of the node.js series.</p>




<h3 class="wp-block-heading">Chapter 2: Express Routing</h3>



<p>We start here with the directory structure of the <em>application root directory</em> from Part 1 of my node.js series and explain the content of the <em>server.js</em> file.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ ls -l
total 56
drwxr-xr-x  52 patrick  staff   1664 21 Mär 08:13 node_modules
-rw-r--r--   1 patrick  staff  14292 21 Mär 11:28 package-lock.json
-rw-r--r--   1 patrick  staff    162 21 Mär 10:16 package.json
-rw-r--r--   1 patrick  staff   2435 21 Mär 17:47 server.js
Patricks-MBP:express-basic patrick$ 

</code></pre>



<p>The <em>server.js</em> file is the <em>application main file</em> and contain the code of the application. The <em>package.json</em> file contain meta data of the application or project such as which external modules or dependencies have been installed to be used by the application. The package-lock.json file contain the complete directory tree of all installed dependencies and finally the directory <em>node_modules</em> contain all dependencies or external modules or packages that have been installed.</p>




<p>At the end of part 1 we already installed the external module Express.js with <em>npm install express &#8211;save</em> and can now load this module in our application. The <em>server.js</em> file looks like this.</p>




<pre class="wp-block-code"><code>// server.js

// load http module
const http = require('http')

// load third party Express module
const express = require('express')
const app = express()

// define the routes
app.get('/', (req, res) =&gt; {
  res.send('Hello, this is my home Page')
})

app.get('/about', (req, res) =&gt; {
  res.send('Hello, this is my about Page')
})

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My node.js web server is alive and running at port 3000')

</code></pre>



<p>We do the following with the code in the <em>server.js</em> file (from top to bottom).</p>




<ol class="wp-block-list">
	<li>load modules</li>
	<li>define routes</li>
	<li>create the server</li>
	<li>define the port the server is listening</li>
	<li>log a success message to the console when all the code runs without problems<br></li>
</ol>



<h4 class="wp-block-heading">The Routing method</h4>



<p>As you can see in the code we already defined 2 simple routes or application end points (URIs). These routes are defined with routing methods and have the following notation.</p>




<pre class="wp-block-code"><code>app.routingMethod( 'routingPath', routingHandler(req, res) =&gt; { ... })

</code></pre>



<p>In our server.js file, we created an app as an instance of the express class by calling the express() function right after we loaded the express module. Routing methods can now be attached to this app. Each routing method corresponds to an http verb such as GET, POST, PUT or DELETE. In our example, we will deal with get() and post() here. The routing method receives 2 parameters:</p>




<ol class="wp-block-list">
	<li><strong>routingPath</strong>: the path of the route end point starting from the root of the application &#8222;/&#8220;. Simply this is the path that the http request passed to the application. If the path passed meets an end point definition, the routingHandler code is executed.</li>
	<li><strong>routingHandler:</strong> the routingHandler is a callback function that receives parameters. Here in the notation above the callback receives 2 parameters. The first parameter is the request object, the second the response object. Because the parameters <em>req</em> and <em>res</em> were passed, the code has access to the methods and properties of the request and response objects. We will talk about these Objects later in this article. <br></li>
</ol>



<p>While the routingPath is a pretty logical thing, we&#8217;ll take a closer look at the routingHandler. The routingHandler contains code that is executed after a request and sends the response. </p>




<h4 class="wp-block-heading">The routing handler</h4>



<p>The routing handler is a callback function with <em>req</em> and <em>res</em> as parameters and process code after the requests and before sending the response. The response is sent with the res.send() method back to the client. </p>




<pre class="wp-block-code"><code>app.routingMethod( 'routingPath', routingHandler(req, res) =&gt; { 

... 

})

</code></pre>



<p>Here the res.send() method send a string back to the client.</p>




<pre class="wp-block-code"><code>// server.js

.........

// define the routes
app.get('/', (req, res) =&gt; {

  res.send('Hello, this is my Home Page')

})

......

</code></pre>



<p>The routing handler can also receive a function as a parameter. </p>




<pre class="wp-block-code"><code>app.routingMethod( 'routingPath', routingHandler(req, res, next) =&gt; { 

... 

})

</code></pre>



<p>Here the routing handler receive <em>req</em> and <em>res</em> but also the function <em>next()</em> as parameter. The next() function forward the processing to the next function(req, res). This final function sen the response to the client with the res.send() method. </p>




<pre class="wp-block-code"><code>// server.js

.........

app.get('/', (req, res, next) =&gt; {
  console.log('this request will be responded by next()');
  next();
}, function (req, res) {
  res.send('This is the response to the request from next()');
})

.........

</code></pre>



<p>As we have seen above the routing handler can receive <em>req</em> and <em>res</em> and <em>functions</em> as parameter. </p>




<p>You can also collect routing handler functions into an array and pass the array as parameter into the routing method. </p>




<pre class="wp-block-code"><code>app.routingMethod( 'routingPath', [array] )

</code></pre>



<p>So lets define 3 functions and pass them as array into the routing method.</p>




<pre class="wp-block-code"><code>// server.js

.........

var r1 = function (req, res, next) {
  console.log('r1 ! The request will be responded by r3');
  next();
}

var r2 = function (req, res, next) {
  console.log('r2 ! The request will be responded by r3');
  next();
}

var r3 = function (req, res) {
  res.send('r3 ! Hello, this is the response !');
}

app.get('/example', [r1, r2, r3]);

.........

</code></pre>



<p>In the example above there are 3 routing handler functions that are collected in an array. The array is passed to the routing method as a parameter. r1 and r2 each execute a console.log instruction and then pass the routing on to the next routing handler function with next(). r3 then returns the response to the client using the res.send() method.</p>




<p>You can collect functions in an array and insert them into the routing method before a last routing handler.</p>




<pre class="wp-block-code"><code>app.routingMethod( 'routingPath', [array], (req, res, next) =&gt; { 

... 

})

</code></pre>



<p>The last of these functions in the array forward the request to the last routing handler for processing. This last routing handler also contains a next() function and processes code first before finally answering the request.</p>




<pre class="wp-block-code"><code>// server.js

.........

var r1 = function (req, res, next) {
  console.log('r1 ! The request will be responded by final');
  next();
}

var r2 = function (req, res, next) {
  console.log('r2 ! The request will be responded by final');
  next();
}

var r3 = function (req, res, next) {
  console.log('r3 ! The request will be responded by final');
  next();
}

app.get('/example', [r1, r2, r3], (req, res, next) =&gt; {
    console.log('log 4 ! The request will be responded by final');
    next();
  }, function (req, res) {
      console.log('final ! This is the response to the request')
})

.........

</code></pre>



<h3 class="wp-block-heading">The response method res.send()</h3>



<p>The <em>res.send(body)</em> method send the http response back to the client. The body parameter can be </p>




<ul class="wp-block-list">
	<li>a string</li>
	<li>an object </li>
	<li>an array</li>
	<li>a buffer object. <br></li>
</ul>



<h5 class="wp-block-heading">res.send() with string response</h5>



<p>When res.send() body is a string the method sets the Content-Type to “text/html”. </p>




<p>res.send(body); body = String.</p>




<pre class="wp-block-code"><code>// server.js

.........

// define the routes
app.get('/', (req, res) =&gt; {

  res.send('Hello, this is my Home Page')

})

......

</code></pre>



<p>Start the server with <em>node server.js</em> and run <em>curl -i localhost:3000</em> in another terminal window and check the output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 27
ETag: W/"1b-AX0brvVSaJSaZMvUvejQv+1wFQA"
Date: Sat, 21 Mar 2020 16:50:26 GMT
Connection: keep-alive

Hello, this is my Home Page

Patricks-MBP:express-basic patrick$ 

</code></pre>



<h5 class="wp-block-heading">res.send() with object or array response</h5>



<p>When the body is an Array or an Object, the Content-Type is application/json.</p>




<p>res.send(body); body = Object.</p>




<pre class="wp-block-code"><code>// server.js

.........

// define the routes
app.get('/', (req, res) =&gt; {

  res.send( { error: 'something wrong in my app' } )

})

......

</code></pre>



<p>Start the server with <em>node server.js</em> and run <em>curl -i localhost:3000</em> in another terminal window and check the output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 37
ETag: W/"25-8fYR5HXYWF9HTHAAgk3niZYRep4"
Date: Sat, 21 Mar 2020 13:34:03 GMT
Connection: keep-alive

{"error":"something wrong in my app"}

Patricks-MBP:express-basic patrick$ 

</code></pre>



<p>res.send(body); body = Array.</p>




<pre class="wp-block-code"><code>// server.js

.........

// define the routes
app.get('/', (req, res) =&gt; {

  var array = [1, 2, 3]
  res.send(array)
  
})

......

</code></pre>



<p>Start the server with <em>node server.js</em> and run <em>curl -i localhost:3000</em> in another terminal window and check the output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 7
ETag: W/"7-nvUMyCrkdCefuOgolhQnArzLszo"
Date: Sat, 21 Mar 2020 13:35:57 GMT
Connection: keep-alive

[1,2,3]

Patricks-MBP:express-basic patrick$ 

</code></pre>



<h5 class="wp-block-heading">res.send() with Buffer response</h5>



<p>When the body is a Buffer object the Content-Type will be set to <em>application/octet-stream</em>.</p>




<p>res.send(body); body = Buffer.</p>




<pre class="wp-block-code"><code>// server.js

.........

// define the routes
app.get('/', (req, res) =&gt; {

 res.send(Buffer.from('&lt;p&gt;This is my buffer HTML&lt;/p&gt;'))
  
})

......

</code></pre>



<p>Start the server with <em>node server.js</em> and run <em>curl -i localhost:3000</em> in another terminal window and check the output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/octet-stream
Content-Length: 29
ETag: W/"1d-TcgrXqCfH0MW//p+ASn/khisjHQ"
Date: Sat, 21 Mar 2020 13:39:23 GMT
Connection: keep-alive

&lt;p&gt;This is my buffer HTML&lt;/p&gt;

Patricks-MBP:express-basic patrick$ 

</code></pre>



<h3 class="wp-block-heading">Properties of the Request Object</h3>



<p>The request object has properties that can be used on the request object. You can access various properties that have been provided with the request and process these data in your routing handler. </p>




<p>For example: You can access the request properties <em>path</em> and <em>method</em> with <em>req.path</em> and <em>req.method</em>. So when the client request i.e. the route &#8222;/users&#8220; with HTTP GET then these properties will have the corresponing value.<br/></p>




<pre class="wp-block-code"><code>// server.js

.........

app.get('/users', (req, res) =&gt; {

  path = req.path
  method = req.method

  console.log('Access / with GET. Path: ' +path +' and Method: ' +method);

  res.send('Hello, this is my Users Page')

})

.........

</code></pre>



<p>So start the server with <em>node server.js</em> in the server terminal and then access the route with <em>curl -i localhost:3000/users</em> in a different terminal. In the server terminal you see the following output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ node server.js
My node.js web server is alive and running at port 3000

Access /users with GET. Path: /users and Method: GET

</code></pre>



<p>For example: You have many users in your database and each user should have his own profile page in your web app. To provide such a profile page for each of your users you could create one route for each user. This mean you would have many routes and you must change your application by programming a new route whenever a new user join to your user population. This is not useful.</p>




<p>This can be avoided by using request parameters. Request parameters are defined in your route as follows.</p>




<pre class="wp-block-code"><code>// server.js

.........

app.get('/users/:name', (req, res) =&gt; {

  path = req.path
  method = req.method
  username = req.params.name

  console.log('Access /users/patrick with GET. Path: ' +path +' and Method: ' +method);
  
  console.log('Request Parameter name is: ' +username);

  res.send('Hello, this is my Home Page')

})

.........

</code></pre>



<p>Start the server with <em>node server.js</em> in the server terminal and then access the route with <em>curl -i localhost:3000/users/patrick</em> in a different terminal. In the server terminal you see the following output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ node server.js
My node.js web server is alive and running at port 3000

Access /users/patrick with GET. Path: /users/patrick and Method: GET

Request Parameter name is: patrick

</code></pre>



<p>Each of your users can access their individual profile page via a route <em>/users/:name</em>. </p>




<p>Suppose you want to show all users on the route <em>/users</em> in a list, you would expect that this would be possible without additional parameters when accessing the route <em>/users</em>. Unfortunately, this does not work in the current configuration.</p>




<p>Keep the server started in the server terminal and then access the route with <em>curl -i localhost:3000/users</em> in a different terminal. In the server terminal you see the following output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i localhost:3000/users
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 144
Date: Sat, 21 Mar 2020 06:51:23 GMT
Connection: keep-alive

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;Error&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;pre&gt;Cannot GET /users&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;
Patricks-MBP:express-basic patrick$ 

</code></pre>



<p>The 404 HTTP status code tell you that the route <em>/users</em> does not exist and nothing has been found. To solve this issue you can add a question mark to the name in your route definition. This tells Express that the request parameter is optional and that the route /users can also be requested. </p>




<pre class="wp-block-code"><code>// server.js

.........

app.get('/users/:name?', (req, res) =&gt; {

  path = req.path
  method = req.method
  username = req.params.name

  console.log('Access /users/patrick with GET. Path: ' +path +' and Method: ' +method);
  
  console.log('Request Parameter name is: ' +username);

  res.send('Hello, this is my Home Page')

})

.........

</code></pre>



<p>Start the server again in the server terminal and then access the route with <em>curl -i localhost:3000/users</em> in a different terminal again.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i localhost:3000/users
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 27
ETag: W/"1b-AX0brvVSaJSaZMvUvejQv+1wFQA"
Date: Sat, 21 Mar 2020 08:23:03 GMT
Connection: keep-alive

Hello, this is my Home Page

Patricks-MBP:express-basic patrick$ 

</code></pre>



<h3 class="wp-block-heading">Chapter 3: Middleware in Express</h3>



<p>As I mentioned in the introduction, middleware simply means that code is executed between the request and the response in order to parameterize the response if necessary. Lets have a look at the following route definition from above to show how routing in express sometimes behave like a middleware.</p>




<pre class="wp-block-code"><code>....

app.get('/example', [r1, r2, r3], (req, res, next) =&gt; {
    console.log('log 4 ! The request will be responded by final');
    next();
  }, function (req, res) {
      console.log('final ! This is the response to the request')
      
....

</code></pre>



<p>After a GET request on the route /example, the routing handler functions r1, r2 and r3 are executed. Console.log commands are executed from r1 to r3 and the request is forwarded with next(). Until then, however, no response is returned. The request is forwarded by r3 to the last routing handler function, which also first executes a console.log instruction before the request is then answered by the last routing handler function. From r1 to the response, the routing handler functions behaved like middleware.</p>




<p>It is also possible to load modules as middleware and always execute the code of the middleware when processing a request with any route and before the response. </p>




<p>We assume the following directory structure. </p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ ls -l
total 64
drwxr-xr-x   8 patrick  staff    256 21 Mär 16:06 modules
drwxr-xr-x  52 patrick  staff   1664 21 Mär 08:13 node_modules
-rw-r--r--   1 patrick  staff  14292 21 Mär 11:28 package-lock.json
-rw-r--r--   1 patrick  staff    162 21 Mär 10:16 package.json
-rw-r--r--   1 patrick  staff   1635 21 Mär 09:22 server.js

Patricks-MBP:express-basic patrick$ 

</code></pre>



<p>A very good but simple example of how middleware modules work is the use of a simple console logger. To demonstrate this, I create a logger.js file in the modules directory. </p>




<p>The looger.js file in the modules directory has the following code.</p>




<pre class="wp-block-code"><code>// modules/logger.js

var logger = function(req, res, next) {

	var method = req.method
	var path = req.path

	console.log(method +' ' +path);
	next()

}

module.exports = logger;

</code></pre>



<p>The logger.js file contain a simple function logger() that will be exported using module.exports. Whenever a request is made for any route, the req.method and the req.path will be logged in the terminal and then the processing will be forwarded with the next() function. So first the request is passed to the application, then the console.log instruction is executed and then the request will be forwarded to the respective routing method.<br/></p>




<p>The routes are defined in our main application file server.js. The server.js file in the modules directory has the following content.</p>




<pre class="wp-block-code"><code>// server.js

// load node http module
const http = require('http')

// load third party Express module
const express = require('express')
const app = express()

// load own modules
const logger = require('./modules/logger')

// Integrate Middleware
app.use(logger);

// define the routes
app.get('/', (req, res) =&gt; {
  res.send('Hello, this is the Blog Home Page.')
})

app.get('/about', (req, res) =&gt; {
  res.send('Hello, this is the Blog About Page.')
})

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My node.js web server is alive and running at port 3000')

</code></pre>



<p>In the server.js main application file I load the module and store the logger() function into the variable logger. The  middleware is integrated in the code with app.use. </p>




<p>After that I start the server with node server.js. In another terminal window I use curl to call routes &#8222;/&#8220; and &#8222;/about&#8220;.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-blog patrick$ curl -i localhost:3000/
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 34
ETag: W/"22-jCGRti3cySGTHqyUOi9QHFbFw2U"
Date: Sat, 21 Mar 2020 12:53:32 GMT
Connection: keep-alive

Hello, this is the Blog Home Page.

Patricks-MBP:express-blog patrick$ curl -i localhost:3000/about
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 35
ETag: W/"23-hKbwboK7j6DObmy7eAWiCel3bMQ"
Date: Sat, 21 Mar 2020 12:53:35 GMT
Connection: keep-alive


Hello, this is the Blog About Page.

Patricks-MBP:express-blog patrick$

</code></pre>



<p>In the first terminal window in which the server is running we see that the logging has worked for both routes. The console.log command of the logger middleware module was executed for both requests.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-blog patrick$ node server.js
My node.js web server is alive and running at port 3000

GET /
GET /about


</code></pre>



<h3 class="wp-block-heading">Chapter 4: Create a Small Blog app with express</h3>



<p>The small Blog app should be a web app without any HTML rendering and no input validation. It should simply show how we can make use of the things we learned so far. This blog will have blogs and users stored in a data file. We will create routes end points to add-, and remove users and blogs and we will create modules which contain the program logic to manipulate data.</p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: You <strong>should never</strong> ever implement an application in production without any input validation. From a security perspective, this is absolutely unacceptable. I will deal with the topic <em>input validation with Express</em> in an extra post here on Digitaldocblog.</p>
</blockquote>



<p>You can find the code discussed here in this chapter on my <a href="https://github.com/prottlaender/node-part-2-express-blog-V1">GitHub page</a>. </p>




<p>First we create a new application root directory <em>express-blog</em>. In this directory we create the main application file <em>blog.js</em> and a <em>package.json</em> file with the touch command.</p>




<pre class="wp-block-code"><code>Patricks-MBP:2020-03-08 patrick$ mkdir express-blog
Patricks-MBP:2020-03-08 patrick$ ls -l
total 0
drwxr-xr-x  9 patrick  staff  288 21 Mär 07:34 express-basic
drwxr-xr-x  2 patrick  staff   64 21 Mär 07:18 express-blog
drwxr-xr-x  6 patrick  staff  192 21 Mär 09:26 node-basic

Patricks-MBP:2020-03-08 patrick$ cd express-blog

Patricks-MBP:express-blog patrick$ ls -l

Patricks-MBP:express-blog patrick$ touch blog.js
Patricks-MBP:express-blog patrick$ touch package.json

Patricks-MBP:express-blog patrick$ ls -l
total 0
-rw-r--r--  1 patrick  staff  0 21 Mär 07:19 blog.js
-rw-r--r--  1 patrick  staff  0 21 Mär 07:19 package.json

Patricks-MBP:express-blog patrick$ 

</code></pre>



<p>We open the package.json file in our editor and edit the file as follows. </p>




<pre class="wp-block-code"><code>{
  "name": "simple_blog",
  "version": "0.0.1",
  "main": "blog.js",
  "author": "Patrick Rottlaender"
}

</code></pre>



<p>We install express with <em>npm install express &#8211;save &#8211;save-exact</em> to ensure that we will install express in the latest version but without updates to the version by future installs. </p>




<pre class="wp-block-code"><code>Patricks-MBP:express-blog patrick$ npm install express --save --save-exact
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN simple_blog@0.0.1 No description
npm WARN simple_blog@0.0.1 No repository field.
npm WARN simple_blog@0.0.1 No license field.

+ express@4.17.1
added 50 packages from 37 contributors and audited 126 packages in 2.167s
found 0 vulnerabilities

Patricks-MBP:express-blog patrick$ ls -l
total 40
-rw-r--r--   1 patrick  staff      0 21 Mär 07:19 blog.js
drwxr-xr-x  52 patrick  staff   1664 21 Mär 07:33 node_modules
-rw-r--r--   1 patrick  staff  14287 21 Mär 07:33 package-lock.json
-rw-r--r--   1 patrick  staff    155 21 Mär 07:33 package.json

Patricks-MBP:express-blog patrick$ 

</code></pre>



<p>Then we create a data.json file and a modules directory. </p>




<pre class="wp-block-code"><code>Patricks-MBP:express-blog patrick$ touch data.json

Patricks-MBP:express-blog patrick$ mkdir modules

Patricks-MBP:express-blog patrick$ ls -l
total 40
-rw-r--r--   1 patrick  staff      0 21 Mär 07:19 blog.js
-rw-r--r--   1 patrick  staff      0 21 Mär 07:44 data.json
drwxr-xr-x   2 patrick  staff     64 21 Mär 07:51 modules
drwxr-xr-x  52 patrick  staff   1664 21 Mär 07:33 node_modules
-rw-r--r--   1 patrick  staff  14287 21 Mär 07:33 package-lock.json
-rw-r--r--   1 patrick  staff    155 21 Mär 07:33 package.json

Patricks-MBP:express-blog patrick$ 

</code></pre>



<p>The structure of the application root directory has now been created and we can start developing the blog app.</p>




<p><strong>First step</strong>: First I want to write the initial code in the blog.js main application file. The code loads the express module which we installed earlier and starts the server on port 3000 of the local host. In addition, a home route is already defined.</p>




<pre class="wp-block-code"><code>// blog.js

// load node http module
const http = require('http')

// load third party Express module
const express = require('express')
const app = express()

// define the routes
app.get('/', (req, res) =&gt; {
  res.send('Hello, this is the Blog Home Page.')
})

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My Blog server is running at port 3000')

</code></pre>



<p>To create users and blog data I should have 2 different modules. One that will create the users and the other one will create the blogs. Therefore I create 2 files in the modules directory. </p>




<pre class="wp-block-code"><code>Patricks-MBP:express-blog patrick$ touch modules/createUsers.js
Patricks-MBP:express-blog patrick$ touch modules/createBlogs.js

Patricks-MBP:express-blog patrick$ ls -l modules
total 0
-rw-r--r--  1 patrick  staff  0 21 Mär 08:02 createBlogs.js
-rw-r--r--  1 patrick  staff  0 21 Mär 08:02 createUsers.js

Patricks-MBP:express-blog patrick$ 

</code></pre>



<p><strong>Second step</strong>: In the data.json file I will store the user and blog data. The data file is currently empty but will have the following structure.</p>




<pre class="wp-block-code"><code>{
	"users":[{name:..., lastname:..., email:..., id:... },{...},...],
	"blogs":[{title:..., author:..., date:..., id:... },{...},...]

}

</code></pre>



<p>There is a json data object with the keys <em>users</em> and <em>blogs</em>. These keys have an array value with objects as array elements. </p>




<pre class="wp-block-code"><code>i,j = 0, 1, 2 ...

data.users[i]
data.blogs[j]

</code></pre>



<p>I will now program the 2 modules <em>usersAdd</em> and <em>blogsAdd</em> in the createUsers.js and createBlogs.js files. These files contain functions that initially create user or blog records or add corresponding user or blog records.</p>




<p>The <em>createUsers.js</em> file contains the following code.</p>




<pre class="wp-block-code"><code>// modules/createUsers.js

// load node fs module
const fs = require('fs')

const usersAdd = function(req, res) {

    var dataExp = fs.readFileSync('./data.json', 'utf8')

    if(!dataExp) {
      console.log('no data available');
      var data = {}
      data.users = []

      var newUserName = req.body.name
      var newUserLastname = req.body.lastname
      var newUserEmail = req.body.email
      var newUserId = 100

      var newUser = {
        name: newUserName,
        lastname: newUserLastname,
        email: newUserEmail,
        id: newUserId
      }

    data.users.push(newUser)

    dataToFile = JSON.stringify(data)

      fs.writeFile('./data.json', dataToFile, function(err) {
        if (err) throw err;
        console.log('Intial User created');
        });

    } else {
      var data = JSON.parse(dataExp)

      if(!data.users) {
        console.log('no users are available')
        data.users = []

        var newUserName = req.body.name
        var newUserLastname = req.body.lastname
        var newUserEmail = req.body.email
        var newUserId = 100

        var newUser = {
          name: newUserName,
          lastname: newUserLastname,
          email: newUserEmail,
          id: newUserId
        }

      data.users.push(newUser)

      dataToFile = JSON.stringify(data)

        fs.writeFile('./data.json', dataToFile, function(err) {
          if (err) throw err;
          console.log('Intial User created');
          });

      } else {
        console.log('users are available')
        var newID
        var minID = data.users[0].id

        for (i = 0; i &lt; data.users.length; i++) {
          if (data.users[i].id &gt;= minID) {
              newID = data.users[i].id + 100
          }
        }

        var newUserName = req.body.name
        var newUserLastname = req.body.lastname
        var newUserEmail = req.body.email
        var newUserId = newID

        var newUser = {
          name: newUserName,
          lastname: newUserLastname,
          email: newUserEmail,
          id: newUserId
        }

      data.users.push(newUser)

      dataToFile = JSON.stringify(data)

      fs.writeFile('./data.json', dataToFile, function(err) {
        if (err) throw err;
        console.log('User added');
        });
      }
  }
}

module.exports = usersAdd;

</code></pre>



<p>The <em>fs</em> module is loaded first. This is a node internal module which is used to read files and also to write data into a file. Then we create the <em>usersAdd</em> function that will be exported with <em>module.exports</em>.</p>




<p>The usersAdd function read the data.json file with fs.readFileSync and store the received data into the dataExp variable. If dataExp is empty we have an empty data file and must first create the empty data Object and store this into the variable data. Then we create the users key on the data object with data.users and assign an empty array. </p>




<p>From the request body we receive the name, lastname and email and store these data into new user variables. For the initial user entry we define the id 100. </p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: Later in this tutorial we will see the POST route definition /createusers in the application main file blog.js. This POST route will call usersAdd with the parameters req and res so that we have access to the req.body object in createUsers.js. We will see this later. </p>
</blockquote>



<p>We create a newUser object with the keys like name, lastname, email, id and assign the new user variables we received from the request body to them as values. Then we push the newUser object into the array of the users key (created with data.users = [ ] at the beginning) which is linked to the data object that we created at the beginning with data =  .</p>




<pre class="wp-block-code"><code>data.users.push(newUser)

</code></pre>



<p>After this we have the following JavaScript data object.</p>




<pre class="wp-block-code"><code>{

	"users": { [ {name:..., lastname:..., email:..., id:... } ] }

}

</code></pre>



<p>With JSON.stringify() we take the JavaScript data object, create a JSON string out of it and store this string into the dataToFile variable. With fs.writeFile we write the string into the so far empty data.json file.<br/></p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: If you use JavaScript to develop applications, JavaScript objects have to be converted into strings if the data is to be stored in a database or a data file. The same applies if you want to send data to an API or to a webserver. The JSON.stringify() function does this for us.</p>
</blockquote>



<p>So far we know what the code does in case the data.json file is completely empty and the first if condition is true (if(!dataExp)). And now lets see what happens what the code does in case the first if condition is false which means that the data.json file already has data because that is the case if the variable dataExp is not empty. </p>




<p>As we have seen we store a JSON string in the data file. So when we read the file and store the data into the variable dataExp we have JSON string data in that variable. To process these data in our JavaScript code we must parse this JSON so that a JavaScript object is created from the JSON string. This is what we do with the JSON.parse() function. </p>




<p>Here we store the JavaScript object into the variable data.</p>




<pre class="wp-block-code"><code>var data = JSON.parse(dataExp)

</code></pre>



<p>Since our code is designed to store only one data object in the data.json file, the variable data is our data object. So when we have the data object we can ask if users are already existing. </p>




<p>Therefore we use the if condition to check if the key data.users exist.</p>




<p>In case the condition if(!data.users) is true, the key data.users is not existing which means that <strong>no users are available so far</strong>. At his point we create a data.users key and assign an empty array. In the following, a newUser object is created in the same way as described above and inserted into the array using the data.users.push() method. Now the data object has an additional key data.users and this key has a newUser Object as value. Now we can convert this entire data object into a string again and completely overwrite the data.json file.</p>




<p>In case the condition if(!data.users) is false, the key data.users is existing and <strong>users are available</strong>. If users exist the individual user records naturally have existing ids. So we first have to create an algorithm to get a new user ID for the new user.</p>




<p>We first create a variable newID and a variable minID. minID corresponds to the userID which has to be assigned at least since it corresponds to the  userID of our first user data object. minID must be the id value of the first user data object record. Since the user objects are stored in an array, this must correspond to the user object at position zero.</p>




<pre class="wp-block-code"><code>var minID = data.users[0].id

</code></pre>



<p>newID should be plus 100 larger than the id of the last found user object.</p>




<p>That is why we iterate through all user objects, adding the value 100 to the id value of the last user object found. Finally, we take the id value of the last user object and add 100 and assign this value to newID. </p>




<p>In the following again a newUser object is created, the entire data object is converted into a string and stored into the data.json file.</p>




<p>The code for the blogsAdd function is implemented exactly according to the same scheme. The only difference is that the blog id only grows by 1. </p>




<p>The createBlogs.js file contains the following code.</p>




<pre class="wp-block-code"><code>// modules/createBlogs.js

// load node fs module
const fs = require('fs')

const blogsAdd = function(req, res) {

    var dataExp = fs.readFileSync('./data.json', 'utf8')

    if(!dataExp) {
      console.log('no data available')
      data = {}
      data.blogs = []

      var newBlogTitle = req.body.title
      var newBlogAuthor = req.body.author
      var newBlogDate = req.body.date
      var newBlogId = 1

      var newBlog = {
        title: newBlogTitle,
        author: newBlogAuthor,
        date: newBlogDate,
        id: newBlogId
      }

    data.blogs.push(newBlog)

    dataToFile = JSON.stringify(data)

      fs.writeFile('./data.json', dataToFile, function(err) {
        if (err) throw err;
        console.log('Intial Blog created');
        });

    } else {
      var data = JSON.parse(dataExp)

      if (!data.blogs) {
        console.log('no blog are available')
        data.blogs = []

        var newBlogTitle = req.body.title
        var newBlogAuthor = req.body.author
        var newBlogDate = req.body.date
        var newBlogId = 1

        var newBlog = {
          title: newBlogTitle,
          author: newBlogAuthor,
          date: newBlogDate,
          id: newBlogId
        }

      data.blogs.push(newBlog)

      dataToFile = JSON.stringify(data)

        fs.writeFile('./data.json', dataToFile, function(err) {
          if (err) throw err;
          console.log('Intial blog created');
          });

      } else {
        console.log('blogs are available');
        var newID
        var minID = data.blogs[0].id

        for (i = 0; i &lt; data.blogs.length; i++) {
          if (data.blogs[i].id &gt;= minID) {
              newID = data.blogs[i].id + 1
          }
        }

        var newBlogTitle = req.body.title
        var newBlogAuthor = req.body.author
        var newBlogDate = req.body.date
        var newBlogId = newID

        var newBlog = {
          title: newBlogTitle,
          author: newBlogAuthor,
          date: newBlogDate,
          id: newBlogId
        }

      data.blogs.push(newBlog)

      dataToFile = JSON.stringify(data)

      fs.writeFile('./data.json', dataToFile, function(err) {
        if (err) throw err;
        console.log('blog added');
        });
      }
  }
}

module.exports = blogsAdd;

</code></pre>



<p><strong>Third Step</strong>: The blog.js file needs to be adjusted. First we integrate middleware that allows us to parse incoming http requests with urlencoded payloads.</p>




<pre class="wp-block-code"><code>app.use(express.urlencoded({ extended: false }))

</code></pre>



<p>Then the two modules must be loaded into the blog.js file with the require() function. Therefore we require the files createUsers.js and createBlogs.js. </p>




<pre class="wp-block-code"><code>const createUsers = require('./modules/createUsers')
const createBlogs = require('./modules/createBlogs')

</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: I would like to explain the topic require() of modules again at this point. The files createBlogs.js and createUsers.js contain the usersAdd and blogsAdd functions which are each exported with module.exports. The module.exports instruction means that these functions can be called in other files of the application if the createBlogs.js and createUsers.js files are loaded with require(). usersAdd and blogsAdd have no return value and therefore the functions themselves are saved in the variables createBlogs and createUsers in blog.js. If e.g. createUsers(req, res) is called in a POST route, the usersAdd function is called and req an res are passed as parameters.</p>
</blockquote>



<p>As we can see in the code of the two modules above, the values for the initial creation or the addition of user- or blog objects are passed to the functions usersAdd or blogsAdd via the request body. For this, POST routes /createusers and /createblogs must be created in the blog.js file. These POST routes call the functions usersAdd or blogsAdd via createUsers() or createBlogs(). </p>




<p>The blog.js file contains the following code.</p>




<pre class="wp-block-code"><code>// blog.js

// load node http module
const http = require('http')

// load third party Express module
const express = require('express')
const app = express()

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))

// load own modules
const createUsers = require('./modules/createUsers')
const createBlogs = require('./modules/createBlogs')

// define the routes
app.get('/', (req, res) =&gt; {
  res.send('Hello, this is the Blog Home Page.')
})

app.post('/createusers', (req, res) =&gt; {
  createUsers(req, res)
  res.send('User has been added successfully.')
})

app.post('/createblogs', (req, res) =&gt; {
  createBlogs(req, res)
  res.send('Blog has been added successfully.')
})

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My node.js web server is alive and running at port 3000')

</code></pre>



<p>Now we are able to add blogs and users. </p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: Here in this application we have no User interface to enter the user variables like name, lastname, email or the blog variables like title, author and date. With this application you cannot enter the data in a form and then transfer it to the application routes /createusers or /createblogs using HTTP POST. This is where <a href="https://www.postman.com">Postman</a> comes in. With <a href="https://www.postman.com">Postman</a> you can simulate a form by manually entering this data in the HTTP body of the HTTP POST request. Postman check whether the POST request was successful or not. I will not go into Postman at this point. So pls. check the documentation on the <a href="https://www.postman.com">Postman website</a>.</p>
</blockquote>



<p>But there is still no way to remove data from the data.json. We now want to show this using the example of how to remove users.</p>




<p>The module which should take over exactly this functionality is the function usersRemove() which I will write in the file modules/usersRemove.js. To do this, we first create an empty file usersRemove.js in the modules directory.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-blog patrick$ pwd
/Users/patrick/Software/dev/node/myArticles/2020-03-08/express-blog
Patricks-MBP:express-blog patrick$ ls -l modules
total 24
-rw-r--r--  1 patrick  staff  2285 21 Mär 17:18 createBlogs.js
-rw-r--r--  1 patrick  staff  2319 21 Mär 17:17 createUsers.js
-rw-r--r--  1 patrick  staff   652 21 Mär 06:50 removeUsers.js

Patricks-MBP:express-blog patrick$ 

</code></pre>



<p>The <em>removeUsers.js</em> file contains the following code.</p>




<pre class="wp-block-code"><code>// modules/removeUsers.js

// load node fs module
const fs = require('fs')

const usersRemove = function(req, res) {
  var dataExp = fs.readFileSync('./data.json', 'utf8')
  var data = JSON.parse(dataExp)

  var delUserID = req.body.id - 0
  
  var elementFound = function(user) {
    return user.id === delUserID
  }

  var index = data.users.findIndex(elementFound)

  data.users.splice(index, 1)

  dataToFile = JSON.stringify(data)
 
  fs.writeFile('./data.json', dataToFile, function(err) {
    if (err) throw err;
    console.log('userID removed');
    });
 
}

module.exports = usersRemove;

</code></pre>



<p>We first load the node fs module again and then define the function usersRemove() which is then exported with module.exports at the end of the code. The function usersRemove() receive req and res as parameters, read the data.json file and parse the read data into a JavaScript object represented by the variable data. </p>




<p>To show you the data object I just run the script as follows.</p>




<pre class="wp-block-code"><code>// modules/removeUsers.js

// load node fs module
const fs = require('fs')

const usersRemove = function(req, res) {
  var dataExp = fs.readFileSync('./data.json', 'utf8')
  var data = JSON.parse(dataExp)
  
  console.log(data)

}

module.exports = usersRemove;

</code></pre>



<p>When you check your console you can see that we saved all the json-data from the file in the variable data. We see a JavaScript object that can be used in our code.</p>




<pre class="wp-block-code"><code>{
  blogs: [
    {
      title: 'First Title',
      author: 'First test author',
      date: '2020-03-28',
      id: 1
    },
    {
      title: 'Second Title',
      author: 'Second test author',
      date: '2020-03-28',
      id: 2
    }
  ],
  users: [
    {
      name: 'Oskar',
      lastname: 'Rottländer',
      email: 'o.rottlaender@test.com',
      id: 100
    },
    {
      name: 'Patrick',
      lastname: 'Rottländer',
      email: 'p.rottlaender@test.com',
      id: 200
    },
    {
      name: 'Carolin',
      lastname: 'Rottländer',
      email: 'c.rottlaender@test.com',
      id: 300
    }
  ]
}

</code></pre>



<p>In the code we take the userID from the req.body and store it into the variable delUserID. The value from the req.body is a string. As we operate with userIDs as numbers in our json data file we must convert the string into a number. This is done with &#8222;- 0&#8220;. Here we subtract the number value zero and tell JavaScript that the delUserID is a number instead of a string. </p>




<p>Then we must find the user object that need to be deleted. user objects are elements in the data.users array. Consequently we must find the user object with a userID from the req.body in the data.users array because this userID identify the user object that should then be deleted and therefore removed from the data.users array. </p>




<p>The callback function elementFound return true when the userID from the rep.body is equal to a userID of a user object in the data.users array. </p>




<p>The method data.users.findIndex() return the index of the first user object found in the data.users array where the userID from the rep.body is equal to the userID of the user object. </p>




<p>The data.users.splice(index, 1) remove one user object at the position of index. As the findIndex() method before returned the exact position of the user object that we want to delete the splice() method here ultimately removes the user object.</p>




<p>The complete data object consisting of blog objects and user objects is now reduced by one user object. the reduced data object is converted as a whole into a string and written again into the file data.json using the fs.writeFile() method.</p>




<p>The blogsRemove() function works identically to the usersRemove() function explained above. The file removeBlogs.js in the module directory therefore looks like this.</p>




<pre class="wp-block-code"><code>// modules/removeBlogs.js

// load node fs module
const fs = require('fs')

const blogsRemove = function(req, res) {
  var dataExp = fs.readFileSync('./data.json', 'utf8')
  var data = JSON.parse(dataExp)

  var delBlogID = req.body.id - 0

  var elementFound = function(blog) {
    return blog.id === delBlogID
  }

  var index = data.blogs.findIndex(elementFound)

  data.blogs.splice(index, 1)

  dataToFile = JSON.stringify(data)

  fs.writeFile('./data.json', dataToFile, function(err) {
    if (err) throw err;
    console.log('blogID removed');
    });
}

module.exports = blogsRemove;

</code></pre>



<p>In the code of the two removeUsers.js and removeBlogs.js modules above, the values for the to be removed user- or blog objects are passed to the functions usersRemove() or blogsRemove() via the request body. For this, POST routes /removeusers and /removeblogs must be created in the blog.js file. These POST routes call these functions usersRemove() or blogsRemove() which are defined in the modules removeUsers.js and removeBlogs.js. These modules must also be loaded into the blog.js file with the require() function.</p>




<p>The blog.js file now contains the following code.</p>




<pre class="wp-block-code"><code>// blog.js

// load node http module
const http = require('http')

// load third party Express module
const express = require('express')
const app = express()

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))

// load own modules
const createUsers = require('./modules/createUsers')
const removeUsers = require('./modules/removeUsers')
const createBlogs = require('./modules/createBlogs')
const removeBlogs = require('./modules/removeBlogs')

// define the routes
app.get('/', (req, res) =&gt; {
  res.send('Hello, this is the Blog Home Page.')
})

app.post('/createusers', (req, res) =&gt; {
  createUsers(req, res)
  res.send('User has been added successfully.')
})

app.post('/removeusers', (req, res) =&gt; {
  removeUsers(req, res)
  res.send('User has been successfully removed.')
})


app.post('/createblogs', (req, res) =&gt; {
  createBlogs(req, res)
  res.send('Blog has been added successfully.')
})

app.post('/removeblogs', (req, res) =&gt; {
  removeBlogs(req, res)
  res.send('Blog has been successfully removed.')
})

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My node.js web server is alive and running at port 3000')

</code></pre>



<p><strong>Fourth step</strong>: Our application can currently create users and create blogs as well as delete blogs and users. Thats fine so far. Now another functionality should be added, namely the display of blogs. This is to be implemented in such a way that the GET request for one route sends different responses back to the server depending on the request parameters provided with the request.</p>




<p>What does this mean ? </p>




<p>For example: We have various blogs in our data file, all of them have been created for specific dates. We want to see all blogs, but also blogs from a certain year or month or blogs that were created on a specific date. </p>




<p>You want to access all blogs using this route.</p>




<pre class="wp-block-code"><code>app.get('/blog', (req, res) =&gt; {
  	....
  
  })
</code></pre>



<p>And you  want to access all blogs in 2020 using this route.</p>




<pre class="wp-block-code"><code>app.get('/blog/2020', (req, res) =&gt; {
  	....
  
  })
</code></pre>



<p>And so on.</p>




<p>We can do this much more elegantly using request parameter. We create the following GET route in our blog.js file.</p>




<pre class="wp-block-code"><code>// blog.js

.....

app.get('/blog/:year?/:month?/:day?', (req, res) =&gt; {
  	....
  
  })
  
.....
</code></pre>



<p>The question mark indicates that the parameters year, month and day are optional and can also be omitted when requesting.</p>




<p>We have defined a route that should give different responds depending on the request parameters. That is why we first have to evaluate the request parameters in the route definition and then define conditions as to how the different inquiries should be answered.</p>




<pre class="wp-block-code"><code>// blog.js

.....

app.get('/blog/:year?/:month?/:day?', (req, res) =&gt; {

  url = req.url
  year = req.params.year
  month = req.params.month
  day = req.params.day

    if (url == '/blog') {
      	...    
    }

    else if (url == '/blog/'+year) {
 		...
    }

    else if (url == '/blog/'+year+'/'+month) {
    	 ...
    }

    else if (url == '/blog/'+year+'/'+month+'/'+day) {
     	...
    }

    else {
      res.status(404).send('Not Found')
    }

})

.....

</code></pre>



<p>I will come back to the main application file blog.js later.</p>




<p>Our goal is to display blog posts. Depending on the route, we want to show  (1) all blogs or (2) all blogs of a year or (3) all blogs of a year and a month or (4) all blog posts from a specific day. </p>




<p>To collect all these data from our data.json file we basically need 4 new functions to perform those queries. Therefore I create a new queryModule in the modules directory. This queryModule contain all these 4 query functions and all of them will be made available within our application. The notation of the code in the queryModule file is slightly different than in the previous modules. </p>




<p>The reason is that we previously had one file as a module in the modules directory and only one function in that file. The export value was the function. These modules looked like this.</p>




<pre class="wp-block-code"><code>// modules/previousModule.js

var myFunction = function() {
	....
}
module.exports = myFunction

</code></pre>



<p>In our main application file we load the previousModule with the require function and store a function into the variable previousModule. We can call the function in the main application file directly with previousModule().</p>




<pre class="wp-block-code"><code>// mainApplicationFile.js

.....

const previousModule = require('./modules/previousModule')

.....

previousModule()

....


</code></pre>



<p>Here in the queryModule (which is our queryBlogs.js file in modules directory) we collect 4 functions but we do not export them. Instead we use module.exports to export an object with 4 keys. Each of these keys has exactly one value and that is the respective function.</p>




<pre class="wp-block-code"><code>// modules/queryModule.js

module.exports = {

	function1: function() {
				....	
			}
	
	function2: function() {
				....	
			}
			
	function3: function() {
				....	
			}
			
	function4: function() {
				....	
			}

}

</code></pre>



<p>In our main application file we load the queryModule with the require function and store an object into the variable queryModule. We can call the functions in the main application file via the object.key notation. </p>




<pre class="wp-block-code"><code>// mainApplicationFile.js

.....

const queryModule = require('./modules/queryModule')

.....

queryModule.function1()

queryModule.function2()

queryModule.function3()

queryModule.function4()

....

</code></pre>



<p>When we take a look at our new queryModule which is the queryBlogs.js file in the modules directory you see that we have an object with 4 different keys and those keys have a function() as values. </p>




<ul class="wp-block-list">
	<li>queryAllBlogs</li>
	<li>queryBlogsYear</li>
	<li>queryBlogsYearMonth</li>
	<li>queryBlogsYearMonthDay<br></li>
</ul>



<p>There is another important difference to the previous modules. Those functions in queryBlogs.js return each a value and this value can be used later in our main application file blog.js. This value is an array of blog posts that should be displayed when a certain route has been requested. </p>




<p>So the queryBlogs.js file looks as follows. I will explain the queryAllBlogs and the queryBlogsYear in detail. The other 2 functions queryBlogsYearMonth and queryBlogsYearMonthDay are schematically the same.</p>




<pre class="wp-block-code"><code>// modules/queryBlogs.js

// load node fs module
const fs = require('fs')

module.exports = {

  queryAllBlogs: function() {

    var allBlogs = []

    var dataExp = fs.readFileSync('./data.json', 'utf8')
    var data = JSON.parse(dataExp)

    for(i = 0; i &lt; data.blogs.length; i++) {
      var dataSet = {
        title: data.blogs[i].title,
        author: data.blogs[i].author,
        date: data.blogs[i].date
      }
      allBlogs.push(dataSet)
    }
      return allBlogs
  },

  queryBlogsYear: function(allBlogs) {
    var yearBlogs = []
    for (i = 0; i &lt; allBlogs.length; i++) {

      blogDate = allBlogs[i].date
      parsedBlogDate = new Date (Date.parse(blogDate))
      parsedBlogDateYear = parsedBlogDate.getFullYear()

      if (year == parsedBlogDateYear) {
        var dataset = {
          title: allBlogs[i].title,
          author: allBlogs[i].author,
          date: blogDate
        }
        yearBlogs.push(dataset)
      }
  }
  return yearBlogs
  },

  queryBlogsYearMonth: function(allBlogs) {
    var yearMonthBlogs = []
    for (i = 0; i &lt; allBlogs.length; i++) {

      blogDate = allBlogs[i].date
      parsedBlogDate = new Date (Date.parse(blogDate))
      parsedBlogDateMonth = (parsedBlogDate.getMonth() + 1)
      parsedBlogDateYear = parsedBlogDate.getFullYear()

      if (year == parsedBlogDateYear &amp;&amp; month == parsedBlogDateMonth) {
        var dataset = {
          title: allBlogs[i].title,
          author: allBlogs[i].author,
          date: blogDate
        }
        yearMonthBlogs.push(dataset)
      }
  }
  return yearMonthBlogs
  },

  queryBlogsYearMonthDay: function(allBlogs) {
    var yearMonthDayBlogs = []
    for (i = 0; i &lt; allBlogs.length; i++) {

      blogDate = allBlogs[i].date
      parsedBlogDate = new Date (Date.parse(blogDate))
      parsedBlogDateDay = parsedBlogDate.getDate()
      parsedBlogDateMonth = (parsedBlogDate.getMonth() + 1)
      parsedBlogDateYear = parsedBlogDate.getFullYear()

      if (year == parsedBlogDateYear &amp;&amp; month == parsedBlogDateMonth &amp;&amp; day == parsedBlogDateDay) {
        var dataset = {
          title: allBlogs[i].title,
          author: allBlogs[i].author,
          date: blogDate
        }
        yearMonthDayBlogs.push(dataset)
      }
    }
    return yearMonthDayBlogs
  }

}

</code></pre>



<p>Our data is stored as a string in a data.json file. Every operation of our application in relation to the data requires that we have access to a JavaScript data object. So if we want to search or select data to display only a part of it in the application, e.g. only all blog posts from a certain year, it is still necessary to have read the entire data from the data file in beforehand. In a larger project with a larger amount of data, this approach is definitely not the right one.</p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: With larger amounts of data, it makes sense to use a database such as MongoDB because we can then search for specific values directly in the database and it is not necessary to retrieve all data from the database. I will show you the use of a MongoDB in a node.js project in another article at a later time. For simplicity&#8217;s sake, let&#8217;s stick here in this article to a file-based approach.</p>
</blockquote>



<p>Therefore the queryAllBlogs function serves as the basis for our other queries for displaying blogs. This function first defines an empty array allBlogs. Then, as already described above, the data is read completely from the data file with fs.readFileSync and converted into a JavaScript object with JSON.parse. Now we have access to blog posts with data.blogs. However, this is not entirely true. As we have already seen above, data.blogs is a key in the data object and this key has an array as value. Strictly speaking, this array contains elements that are the blog posts.</p>




<p>In any case, with the for loop we iterate through all elements of the array using data.blogs[i] so that each individual blog data record can be read from the data file and attached with the allBlogs.push() method as an dataSet object to the allBlogs array that was defined first. The function queryAllBlogs() then return allBlogs back to the caller. allBlogs contain all the dataSet objects. The allBlogs array looks like the following. </p>




<pre class="wp-block-code"><code>[
	{
	
	title: valueTitle,
	author: valueAuthor,
	data: valueDate
	
	},
	
	{
	
	...
	
	},
	
	...

]

</code></pre>



<p>The function queryBlogsYear take the allBlogs array as parameter (like any other function queryBlogs* defined in the module). This is because we want to select data from it in the queryBlogsYear function and therefore all blog posts must be available in the function scope. </p>




<p>First we create the empty array yearBlogs. This array will contain at the end of the function code all the data that should be returned later by the queryBlogsYear function. </p>




<p>Then we iterate through the allBlogs array using the for loop. </p>




<p>In the for loop, we first read at the value of the blog date with allblogs[i].date and store the value in the variable blogDate. In the data file the date is saved with ISO 8601 date format (YYYY-mm-dd). It is highly recommended to always save the date in this format since ISO 8601 is the date format preferred by JavaScript and so all other operations with the date are then made easier. In order to work well with the date string yyyy-mm-dd in JavaScript, this string date must first be converted into a number using. Then the number will be converted into a date object using the Date.parse() method. </p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: Date.parse() receive the string date in ISO 8601 format yyyy-mm-dd and returns a number that represents the milliseconds between January 1st, 1970 00:00:00 UTC. This number is unique and is required to create the date object using the new Date() method. With this date object we have with JavaScript access to the year, month or day of the given date object. </p>
</blockquote>



<p>Therefore, in our code Date.parse() is passed directly as parameter into the new Date() method so that the required date object can be generated directly from the returned number. The date object is stored in the variable parsedBlogDate.</p>




<p>Because parsedBlogDate represents an object, the parsedBlogDate.getFullYear() method gives us access to the year passed with the date. The year is stored in the parsedBlogDateYear variable. </p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: Later we will use parsedBlogDate.getMonth() to retrieve the month from the date object. This method returns 0 for January and 11 for December. It is therefore necessary to add &#8222;+1&#8220; to get the usual values 1 for January and 12 for December. And we will use parsedBlogDate.getDate() to retrieve the day of the month as 1 for the first day and max 31 for the last day of the respective month. </p>
</blockquote>



<p>Then we compare in the if loop the year passed in the request (year = req.params.year, variable year is defined in blog.js) with the years of all blog posts. We only generate a dataset where the year from the request matches the year of the blog post. The array yearBlogs created in this way is then returned to the caller as a return value.</p>




<p>I will now come back to main application file blog.js and the specific route definition where we evaluate the request parameters and provide different responses. With this route we send, depending on the request parameters, the following responses.</p>




<ul class="wp-block-list">
	<li>all blog posts  &#8211; res.send(allBlogs)</li>
	<li>blog posts of given year &#8211; res.send(blogsYear)</li>
	<li>blog posts of a give year and month &#8211; res.send(blogsYearMonth)</li>
	<li>blog posts of a given date &#8211; res.send(blogsYearMonthDay)<br></li>
</ul>



<pre class="wp-block-code"><code>// blog.js

....

const queryBlogs = require('./modules/queryBlogs')

....

app.get('/blog/:year?/:month?/:day?', (req, res) =&gt; {

  url = req.url
  year = req.params.year
  month = req.params.month
  day = req.params.day

  var allBlogs = queryBlogs.queryAllBlogs()

    if (url == '/blog') {
      if (allBlogs.length == 0) {
        res.send('no post found')
      } else {
        res.send(allBlogs)
      }
    }

    else if (url == '/blog/'+year) {

      const blogsYear = queryBlogs.queryBlogsYear(allBlogs)

      if(blogsYear.length == 0) {
        res.send('no post found for this year')
      } else {
        res.send(blogsYear)
      }

    }

    else if (url == '/blog/'+year+'/'+month) {

      const blogsYearMonth = queryBlogs.queryBlogsYearMonth(allBlogs)

      if(blogsYearMonth.length == 0) {
        res.send('no post found for this year and month')
      } else {
        res.send(blogsYearMonth)
      }

    }

    else if (url == '/blog/'+year+'/'+month+'/'+day) {

      const blogsYearMonthDay = queryBlogs.queryBlogsYearMonthDay(allBlogs)

      if(blogsYearMonthDay.length == 0) {
        res.send('no post found for this year and month and day')
      } else {
        res.send(blogsYearMonthDay)
      }

    }

    else {
      res.status(404).send('Not Found')
    }

})

....

</code></pre>



<p>We have defined a route that give different responds depending on the request parameters. We want to see all blogs when the request url == /blog, we see all blogs i.e. of a given year 2019 when the request url == /blog/2019 and so an.</p>




<p>First we load the queryBlogs module with the require() function and save the object in the variable queryBlogs (remember ? queryBlogs return an object of functions).</p>




<p>In the route definition we take the request parameters passed with the request and save them in the variables url, year, month and day. Then we access the queryAllBlogs() function defined in the queryBlogs module with queryBlogs.queryAllBlogs(). This function return all blog posts stored in an array. This array returned by the function will be stored in the variable allBlogs. </p>




<p>Then we create if and else if conditions to define the response behavior of our route definition in our application. </p>




<p>The <strong>first if condition</strong> is true in case the requested url is equal to /blog. The following if condition is true when the allBlogs array is empty. Then the response is no posts found res.send(&#8217;no post found&#8216;). When this if condition is true blog posts have been found in the allBlogs array and this array is not empty. In this case all the data from the allBlogs array will be send back to the caller with res.send(allBlogs). </p>




<p>The <strong>first else if condition</strong> is true in case the requested url is equal to /blog/year (i.e. /blog/2019). When this else if condition is true we call the queryBlogsYear() function in our queryBlogs module and pass the allBlogs array as parameter. We call the function using queryBlogs.queryBlogsYear(allBlogs) and store the returned value in the array variable blogsYear. </p>




<p>If the blogsYear array is empty the following if condition is true. This mean no blog posts have been found for the requested year in allBlogs. Then the response is no posts found for this year res.send(&#8217;no post found for this year&#8216;). When this if condition is false blog posts have been found for the requested year and the blogsYear array is not empty. Then all these data from the blogsYear array will be send back to the caller with res.send(blogsYear). </p>




<p>The <strong>second else if condition</strong> is true in case the requested url is equal to /blog/year/month (i.e. /blog/2019/04). When this else if condition is true we call the queryBlogsYearMonth() function in our queryBlogs module and pass the allBlogs array as parameter. We call the function using queryBlogs.queryBlogsYearMonth(allBlogs) and store the returned value in the array variable blogsYearMonth. </p>




<p>If the blogsYearMonth array is empty the following if condition is true. This mean no blog posts have been found for the requested year and month in allBlogs. Then the response is no posts found for this year and month res.send(&#8217;no post found for this year and month&#8216;). When this if condition is false blog posts have been found for the requested year and month and the blogsYearMonth array is not empty. Then all these data from the blogsYearMonth array will be send back to the caller with res.send(blogsYearMonth). </p>




<p>The <strong>third else if condition</strong> is true in case the requested url is equal to /blog/year/month/day (i.e. /blog/2019/04/10). When this else if condition is true we call the queryBlogsYearMonthDay() function in our queryBlogs module and pass the allBlogs array as parameter. We call the function using queryBlogs.queryBlogsYearMonthDay(allBlogs)and store the returned value in the array variable blogsYearMonthDay. </p>




<p>If the blogsYearMonthDay array is empty the following if condition is true. This mean no blog posts have been found for the requested date in allBlogs. Then the response is no posts found for this year and month and day res.send(&#8217;no post found for this year and month and day&#8216;). When this if condition is false blog posts have been found for the requested date and the blogsYearMonth array is not empty. Then all these data from the blogsYearMonthDay array will be send back to the caller with res.send(blogsYearMonthDay). </p>




<p>The <strong>first if condition</strong> is false in case the requested url does not match any of the defined request parameters (/blog/:year?/:month?/:day?). Then the <strong>else response</strong> is res.status(404).send(&#8218;Not Found&#8216;).</p>




<h3 class="wp-block-heading">Summary and Outlook</h3>



<p>In this Part 2 of my node.js series I explained some very important details of Express and how express can be used in web application development. Based on what we already learned about Express in <a href="https://digitaldocblog.com/webserver/nodejs-series-part-1-create-a-simple-web-server-with-nodejs/" title="Node.js series Part 1. Create a Simple Web-Server with Node.js">Part 1</a>, we looked at Express Routing in detail and how you can use middleware in Express relatively easily. With the knowledge we learned, we then built a simple blog web application and thus applied the knowledge.</p>




<p>This blog app has all the data in a file and no HTML frontend or no HTML template rendering is used. Express is ideally suited for the use of a database like MongoDB and also for the use of HTML templates to present the content. In the next <a href="https://digitaldocblog.com/webserver/nodejs-series-part-3-the-simple-express-blog-app-with-mongodb/" title="Node.js series Part 3. The Simple Express Blog App with MongoDB">Part 3</a> of my node.js series I will show you how our blog app uses a MongoDB database instead of the data file. Then we will continue to develop the blog app and implement HTML rendering.</p>




]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Node.js series Part 1. Create a Simple Web-Server with Node.js</title>
		<link>https://digitaldocblog.com/webserver/nodejs-series-part-1-create-a-simple-web-server-with-nodejs/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 07:00:00 +0000</pubDate>
				<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=108</guid>

					<description><![CDATA[In this part 1 of my node.js series I briefly explain the creation of a simple node.js web-server that respond to various http requests. I explain the basics of Node.js&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In this part 1 of my node.js series I briefly explain the creation of a simple node.js web-server that respond to various http requests. I explain the basics of Node.js and install the Express.js framework so that it can be used by the simple web-server.</p>




<h3 class="wp-block-heading">Chapter 1: Under the hood of the simple web-server</h3>



<p><a href="https://nodejs.org/en/"><strong>Node.js</strong></a> is based on JavaScript. JavaScript has always been known as a front-end programming language that is executed in the browser. The code runs in the browser. This has changed since node.js because with node.js JavaScript code is executed on the server side. The code no longer runs in the browser but on the server. Node.js provides the build in http module which make it easy to implement a web-server with basic functionalities. Node.js is a runtime environment in which server-side code can be executed. In this respect, node.js is the basic technology for frameworks like <em>Express.js</em>.</p>




<p><a href="https://expressjs.com/"><strong>Express.js</strong></a> is the most widespread node.js framework. In contrast to the pure node.js http module, <em>Express.js</em> offers extensive options for processing client http requests. <em>Express.js</em> also offers middleware functionalities that can be built in between the request and the response to execute the code build in routes depending on the middleware function. This includes authentication and authorization, logging and much more.</p>




<h3 class="wp-block-heading">Chapter 2: Install node.js and npm</h3>



<p>First of all, it must be ensured that <em>node.js</em> and also <em>npm.js</em> are installed on your system. npm is the node package manager and is absolutely necessary if we develop programs with node.<br/></p>




<p>We should definitely check whether node and npm are already installed on the system. To do this, please enter the following commands on the command line.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node patrick$ node --version
v13.8.0

Patricks-MBP:node patrick$ npm --version
6.13.7

Patricks-MBP:node patrick$ 

</code></pre>



<p>In this case, node is already installed in version 13.8.0 and npm in version 6.13.7 and nothing further needs to be done.</p>




<p>I work with Mac OS and there is the standard for installing command line tools <a href="https://brew.sh/index_de">homebrew</a>. I wrote the article <a href="https://digitaldocblog.com/singleblog?article=1">node.js and npm on Mac OS</a> here on <a href="https://digitaldocblog.com">Digitaldocblog</a> that shows step by step the installation of node and npm on a Mac OS. Other ways to install node.js can be found on [nodejs.org] (https://nodejs.org/en/download/).</p>




<p>Especially if we work with Ubuntu linux, node and npm can be installed using the Advanced Packaging Tool (APT). While on Mac OS the installation of node using homebrew includes npm, node and npm are installed separately on Ubuntu. Simply enter the following commands on the command line on your Ubuntu system (but check before if it is already installed). </p>




<pre class="wp-block-code"><code>#: sudo apt install nodejs

#: sudo apt install npm

</code></pre>



<p>Of course, it is also a basic requirement to install a suitable editor. You can of course also work with text editors like <a href="https://www.nano-editor.org/">nano</a> or <a href="http://ex-vi.sourceforge.net/">vi</a>, but that is certainly very cumbersome. From my point of view, the <a href="https://atom.io/">Atom editor</a> is very suitable for node programming and my first choice.</p>




<p>After that, the following requirements should be met:</p>




<ul class="wp-block-list">
	<li>node and npm installed</li>
	<li>text editor installed (i.e. Atom)<br></li>
</ul>



<h3 class="wp-block-heading">Chapter 3: The basics of node.js</h3>



<p>I will briefly go over here to explain how node.js works. For this I will program a simple webserver with plain node.js and you can see what node already offers for creating a web app.</p>




<p>For this purpose, a separate directory for our first node web-app is created on the development system. This is the place we will store all files and the entire program code and called the <em>application root directory</em>. In my case this is the application root directory <em>node-basic</em>.</p>




<pre class="wp-block-code"><code>Patricks-MBP:2020-03-08 patrick$ mkdir node-basic

Patricks-MBP:2020-03-08 patrick$ cd node-basic

Patricks-MBP:node-basic patrick$ ls -al
total 0
drwxr-xr-x  2 patrick  staff  64 08 Mär 06:05 .
drwxr-xr-x  3 patrick  staff  96 08 Mär 06:05 ..

Patricks-MBP:node-basic patrick$ pwd
/Users/patrick/Software/dev/node/myArticles/2020-03-08/node-basic

Patricks-MBP:node-basic patrick$  

</code></pre>



<p>Change to the application root directory you just created, create a file <em>server.js</em> and open this file using your favorite editor. The file <em>server.js</em> is called the <em>application main file</em> and is the entry point of our node web-application.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ touch server.js

Patricks-MBP:node-basic patrick$ ls -l
total 0

-rw-r--r--  1 patrick  staff  0 08 Mär 18:22 server.js

Patricks-MBP:node-basic patrick$ 

</code></pre>



<h3 class="wp-block-heading">3.1 Simple node web-server using the integrated &#8218;http&#8216; module</h3>



<p>Enter the following code in <em>server.js</em>. You can find the code on my <a href="https://github.com/prottlaender/node-part-1-simple-node-webserver-V1">GitHub Page</a>.</p>




<pre class="wp-block-code"><code>// server.js

// 1. load http module
const http = require('http')

// 2. create the server
const server = http.createServer(function (req, res) {

    // 3. check conditions for requests
    if (req.url == '/') {

        // 4.1 set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });

        // 4.2 set response content
        res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This is my home Page.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
        
        // 4.3 End response
        res.end();

    }
    else if (req.url == "/about") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This is my about Page.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
        res.end();

    }
    else if (req.url == "/impressum") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This is my Impressum Page.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
        res.end();

    }
   else {
      res.writeHead(404, { 'Content-Type': 'text/html' })
      res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This path is not available. Invalid request&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;')
      res.end()
    }
});

// 5. server listen for any incoming requests
server.listen(3000);

console.log('My node.js web server is alive and running at port 3000')


</code></pre>



<p>A webserver is a relatively simple system that processes HTTP requests from a client. node.js contains the <em>http</em> module with which the developer can program http server but also http clients.<br/></p>




<p>So lets see what happens in the code above.</p>




<ol class="wp-block-list">
	<li>The <a href="https://www.w3schools.com/nodejs/obj_http_server.asp">http module</a> is loaded with the require() function and a reference is saved in the variable <em>http</em>. Various functions can be used on the http reference that are provided by the http module.</li>
	<li>On the http reference a server is created with the <a href="https://www.w3schools.com/nodejs/met_http_createserver.asp">http.createServer()</a> function. http.createServer() creates a server object and the reference is saved in the variable <em>server</em>. The server object can listen to ports and receives a <a href="https://www.w3schools.com/nodejs/func_http_requestlistener.asp">requestListener()</a> function as parameter. This function is always executed when the server receives a request from the client and expects 2 parameters such as request and response. These parameters are usually noted with <em>req</em> and <em>res</em>.</li>
	<li><strong>req</strong> is always the first parameter and represent the 	request object. The request object refer to the <a href="https://www.w3schools.com/nodejs/obj_http_incomingmessage.asp">IncomingMessage</a> object. This object has properies and methods like the property <em>url</em> that can be used with <em>req.url</em>.</li>
	<li><strong>res</strong> is always the second parameter and represent the response object. The response object refer to the <a href="https://www.w3schools.com/nodejs/obj_http_serverresponse.asp">ServerResponse</a> object. This object has properties and methods like the method <em>writeHead()</em> that can be used with <em>res.writeHead()</em>.</li>
	<li>In the <strong>if</strong> and <strong>else if</strong> block we compare the requested url <em>req.url</em> with the url we difined in our route (i.e. &#8222;/&#8220; or &#8222;/about&#8220;). For example, if the URL corresponds to &#8222;/about&#8220;, the server should return an about page to the client. If the requested url <em>req.url</em> does not match any of the conditions specified with <em>if</em> and <em>else if</em>, an error message is sent back to the client.</li>
	<li><strong>res.writeHead()</strong>: the function <em>writeHead()</em> sends the http-status code 200 (Ok) as the standard response for successful HTTP requests and the <em>response header</em> back to the client. The response header is an object with the key <em>content-type</em> and the value <em>text/html</em> as here in the example. In case the requested url <em>req.url</em> does not match any of the conditions specified with <em>if</em> and <em>else if</em> writeHead()* sends the http-status code 404 (Not Found).</li>
	<li><strong>res.write()</strong>: The function <em>write()</em> sends a text stream back to the client. In our example <em>write()</em> send HTML that can be parsed by the browser to display a website content.	</li>
	<li><strong>res.end()</strong>: the <em>end()</em> function tells the server that the request has ended.</li>
	<li>At the end of the program, the <em>listen()</em> function is used on the server, which expects the port as the parameter. The port in this example is port 3000. <em>listen()</em> starts the server on port 3000 at the localhost. </li>
	<li>The final statement log a message at the console that the server has been started. <br></li>
</ol>



<h3 class="wp-block-heading">3.2 Code encapsulation using self-developed modules</h3>



<p>In our webserver example we load the <em>node.js integrated http module</em> with the require() function and we used the method createServer() with a requestListener() function that contains the entire server logic.</p>




<p>We write all the code in the <em>server.js</em> application main file which make the code confusing especially when we program more complex applications. </p>




<p>Node offers the possibility to encapsulate code in a separate file. When we have code in a separate file then we speak of a <em>module</em>. Like the integrated http module we load this module into the application main file <em>server.js</em> using the <em>require()</em> function. </p>




<p>With the help of directories you can structure your modules effectively. In this example I want to collect all my modules in a directory called <em>modules</em>. In this directory I create the <em>logic.js</em> file that contain all the server logic.</p>




<p>You can find the code on my <a href="https://github.com/prottlaender/node-part-1-simple-node-webserver-V2">GitHub Page</a>. </p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ ls -l
total 8
-rw-r--r--  1 patrick  staff  1282 08 Mär 05:58 server.js

Patricks-MBP:node-basic patrick$ mkdir modules

Patricks-MBP:node-basic patrick$ ls -l
total 8
drwxr-xr-x  2 patrick  staff    64 08 Mär 07:31 modules
-rw-r--r--  1 patrick  staff  1282 08 Mär 05:58 server.js

Patricks-MBP:node-basic patrick$ touch modules/logic.js

Patricks-MBP:node-basic patrick$ ls -l modules
total 0
-rw-r--r--  1 patrick  staff  0 08 Mär 07:31 logic.js

Patricks-MBP:node-basic patrick$ 

</code></pre>



<p>The server logic that is executed whenever the server receives a request should be in the <em>modules/logic.js</em> file. The <em>modules/logic.js</em> file contains the following code.</p>




<pre class="wp-block-code"><code>// modules/logic.js

const serverlogic = function(req, res) {
    // check conditions for requests
    if (req.url == '/') {

        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });

        // set response content
        res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This is my home Page.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
        // End response
        res.end();

    }
    else if (req.url == "/about") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This is my about Page.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
        res.end();

    }
    else if (req.url == "/impressum") {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This is my Impressum Page.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
        res.end();

    }
    else {
      res.writeHead(404, { 'Content-Type': 'text/html' });
      res.write('&lt;html&gt;&lt;body&gt;&lt;p&gt;This path is not available. Invalid request&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;');
      res.end();
    }
  }

  module.exports = serverlogic;

</code></pre>



<p>The function with all instructions is assigned to the constant <em>serverlogic</em>. At the end of the file, the reference to the function is exported with <em>module.exports</em>. The function serverlogic() is now usable in other files of the application.</p>




<p>In order to integrate the new self-developed module into the <em>server.js</em> file, we use the require function again as follows.</p>




<pre class="wp-block-code"><code>// server.js

// load http integrated node module
const http = require('http')

// load self-developed module serverlogic from modules/logic.js
const serverlogic = require('./modules/logic');

// create the server
const server = http.createServer(serverlogic);

// 5. server listen for any incoming requests
server.listen(3000);

console.log('My node.js web server is alive and running at port 3000')

</code></pre>



<p>With the <em>require()</em> function we load the file <em>modules/logic</em> in the <em>server.js</em> application and assign the constant <em>serverlogic</em>. Now we can use the module in the createServer() method and the server runs exactly as before. </p>




<h3 class="wp-block-heading">3.3 Using third-party modules</h3>



<p>In our webserver example above we see how we can create a simple webserver using the node on-board resources. In our example we include the node.js <em>integrated http module</em>, which has been loaded with the require function and we used methods like createServer() that are provided by this integrated module. And we see how we can encapsulate the server logic to a separate file.</p>




<p>In general the scope of integrated node.js modules such as the <em>http module</em> is very minimal and is limited to the absolutely essential, which means that the node.js core is very compact and stable. The node.js core offers a very mature and stable runtime environment, but there is no comprehensive standard library to develop more complex web-applications easily. Therefore hundreds of thousands different <em>third party modules</em> from the node community are available. </p>




<p><em>Express.js</em> is one of the most used third-party modules to create web-applications. The advantage of a module like Express is that this module contains many methods optimized for the http request handling. When using Express, for example the functions such as writeHead(), write() and end() can be replaced by one single function res.send(). And the node community offers many other third party modules that are tailored to the use of Express.</p>




<p>In order to use a third party module in a web application, it must be installed in the application root directory. The installation is done by the node package manager in the application root directory. Third party modules are also called dependencies. This means the application that lives in the application root directory and is defined by the various js-files contains dependencies of the installed third party modules. </p>




<p>I will therefore first delete the self-developed module so that I only have the application main file server.js in the application root directory.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ ls -al
total 8
drwxr-xr-x  4 patrick  staff  128 08 Mär 18:10 .
drwxr-xr-x  3 patrick  staff   96 08 Mär 06:05 ..
drwxr-xr-x  3 patrick  staff   96 08 Mär 07:31 modules
-rw-r--r--  1 patrick  staff  387 08 Mär 07:51 server.js

Patricks-MBP:node-basic patrick$ rm -r modules

Patricks-MBP:node-basic patrick$ ls -al
total 8
drwxr-xr-x  3 patrick  staff   96 08 Mär 06:07 .
drwxr-xr-x  3 patrick  staff   96 08 Mär 06:05 ..
-rw-r--r--  1 patrick  staff  387 08 Mär 07:51 server.js

Patricks-MBP:node-basic patrick$

</code></pre>



<p>The third party module Express can now be easily installed in the <em>application root directory</em> as follows.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ pwd
/Users/patrick/Software/dev/node/myArticles/2020-03-08/node-basic

Patricks-MBP:node-basic patrick$ npm install express
npm WARN saveError ENOENT: no such file or directory, open '/Users/patrick/Software/dev/node/myArticles/2020-03-08/node-basic/package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open '/Users/patrick/Software/dev/node/myArticles/2020-03-08/node-basic/package.json'
npm WARN node-basic No description
npm WARN node-basic No repository field.
npm WARN node-basic No README data
npm WARN node-basic No license field.

+ express@4.17.1
added 50 packages from 37 contributors and audited 126 packages in 2.215s
found 0 vulnerabilities

Patricks-MBP:node-basic patrick$ ls -al
total 40
drwxr-xr-x   5 patrick  staff    160 08 Mär 06:14 .
drwxr-xr-x   3 patrick  staff     96 08 Mär 06:05 ..
drwxr-xr-x  52 patrick  staff   1664 08 Mär 06:14 node_modules
-rw-r--r--   1 patrick  staff  14240 08 Mär 06:14 package-lock.json
-rw-r--r--   1 patrick  staff    387 08 Mär 07:51 server.js

Patricks-MBP:node-basic patrick$ 

</code></pre>



<p>The third party module Express.js in version 4.17.1 has been installed successfully in the application root directory. Express.js is now available locally in our application perimeter and can therefore be used in the application.</p>




<p>In the application root directory we see the following changes.</p>




<ul class="wp-block-list">
	<li><strong>node_modules</strong>: the <em>node_modules</em> directory is created during the installation. npm stores all locally installed packages there. If you look into the directory you will see that there is currently more than just the Express module installed. This is due to the fact that Express itself requires modules which in turn were taken into account during this installation and were also installed.</li>
	<li><strong>package-lock.json</strong>: The package-lock.json file is always generated automatically when npm changes the directory content in node_modules. The content of the package-lock.json shows the current complete directory tree of all modules and if you want to install an additional module or dependency it is ensured that the installation process creates exactly the directory tree at the end of the existing plus the directory of the newly installed module.<br></li>
</ul>



<p>It is possible to install several modules in this way in order to use them in the application. If you continue installing modules, you will quickly lose track of which modules are installed in which version.</p>




<p>It is then no longer easy to depoloy the application, for example, from a Mac OS developer system to a Linux production system and keep exactly the same version of the modules used. The goal must be to install all the modules used in development in exactly the same way on another system or in another application root directory. Here node offers a possibility to do this with the help of the <em>package.json</em> file.</p>




<p>The <em>package.json</em> file is in your application root directory and list all modules or packages that have been installed in your application root directory. In node it is said that modules are packages and that an application depends on packages. In this respect, the package.json file lists all the packages on which your application depends on. </p>




<p>In order to demonstrate how we use a package.json file when installing the Express package, I will delete the node_modules directorory again and create a <em>package.json</em> file.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ pwd
/Users/patrick/Software/dev/node/myArticles/2020-03-08/node-basic

Patricks-MBP:node-basic patrick$ ls -l
total 40
drwxr-xr-x  52 patrick  staff   1664 08 Mär 06:14 node_modules
-rw-r--r--   1 patrick  staff  14240 08 Mär 06:14 package-lock.json
-rw-r--r--   1 patrick  staff    524 08 Mär 09:34 server.js

Patricks-MBP:node-basic patrick$ rm -r node_modules

Patricks-MBP:node-basic patrick$ ls -l
total 40
-rw-r--r--  1 patrick  staff  14240 08 Mär 06:14 package-lock.json
-rw-r--r--  1 patrick  staff    524 08 Mär 09:34 server.js

Patricks-MBP:node-basic patrick$ touch package.json

Patricks-MBP:node-basic patrick$ ls -l
total 40
-rw-r--r--  1 patrick  staff  14240 08 Mär 06:14 package-lock.json
-rw-r--r--  1 patrick  staff      0 08 Mär 07:19 package.json
-rw-r--r--  1 patrick  staff    524 08 Mär 09:34 server.js

Patricks-MBP:node-basic patrick$

</code></pre>



<p>With the following command using the <em>npm init &#8211;yes</em> I create a default package.json file as follows. This guarantees a correct <em>.json</em> format with a standard structure and <em>node</em> or <em>npm</em> will not throw any error messages with this package.json file when you install packages.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ ls -l
total 48
-rw-r--r--  1 patrick  staff  14240 08 Mär 06:14 package-lock.json
-rw-r--r--  1 patrick  staff    106 08 Mär 07:39 package.json
-rw-r--r--  1 patrick  staff    526 08 Mär 07:40 server.js

Patricks-MBP:node-basic patrick$ npm init --yes
Wrote to /Users/patrick/Software/dev/node/myArticles/2020-03-08/node-
basic/package.json:

{
  "name": "node-basic",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}


Patricks-MBP:node-basic patrick$

</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: With the command <em>npm init &#8211;yes</em> default values are set in the <em>package.json</em> file. For example, the value of <em>name</em> is assigned to the directory name, the <em>version</em> is always 1.0.0 and <em>main</em> is usually index.js unless like in our case npm finds a server.js file that differs from index.js.</p>
</blockquote>



<p>This package.json file can now be adjusted with our preferred editor according to our preferences. My personal preference is to keep the package.json file as simple as possible, so the default content for me is as follows.</p>




<pre class="wp-block-code"><code>{
  "name": "simple_webserver",
  "version": "0.0.1",
  "main": "server.js",
  "author": "Patrick Rottlaender"
}

</code></pre>



<p>Then I install Express.js again using the command <code>npm install express --save</code>.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ ls -l
total 48
-rw-r--r--  1 patrick  staff  14240 08 Mär 06:14 package-lock.json
-rw-r--r--  1 patrick  staff    256 08 Mär 07:44 package.json
-rw-r--r--  1 patrick  staff    526 08 Mär 07:40 server.js

Patricks-MBP:node-basic patrick$ npm install express --save
npm WARN node-basic@1.0.0 No description
npm WARN node-basic@1.0.0 No repository field.

+ express@4.17.1
added 50 packages from 37 contributors and audited 126 packages in 2.895s
found 0 vulnerabilities

Patricks-MBP:node-basic patrick$ ls -l
total 48
drwxr-xr-x  52 patrick  staff   1664 08 Mär 07:46 node_modules
-rw-r--r--   1 patrick  staff  14286 08 Mär 07:46 package-lock.json
-rw-r--r--   1 patrick  staff    306 08 Mär 07:46 package.json
-rw-r--r--   1 patrick  staff    526 08 Mär 07:40 server.js

Patricks-MBP:node-basic patrick$ 

</code></pre>



<p>As you can see, the <em>node_modules</em> directory has also been created, in which the express module and all of its dependencies can now be found. Let&#8217;s take a look at the content of the <em>package.json</em> file, we see that a new object <em>dependency</em> has been added and we see that express in version 4.17.1 exists there.</p>




<pre class="wp-block-code"><code>{
  "name": "simple_webserver",
  "version": "0.0.1",
  "main": "server.js",
  "author": "Patrick Rottlaender",
  "dependencies": {
    "express": "^4.17.1"
  }
}

</code></pre>



<p>A very important point is the spelling of the version of the installed dependency in the package.json file. In our example express was installed in version &#8222;^ 4.17.1&#8220;. The preceding &#8222;^ &#8230;&#8220; tells <em>npm</em> to install a version of at least version 4.17.1 or higher when calling <em>npm install</em>. This means that until the change to a new major version 5, <em>npm</em> would always update to the latest version. This can lead to problems in an application because when versions of dependencies are changed, the code may no longer be compatible and the code must be adapted. </p>




<p>Therefore I always recommend to remove the preceding &#8222;^ &#8230;&#8220; to tell <em>npm</em> that the exact version has to be kept when calling <em>npm install</em>. </p>




<p>The following is the content of the <em>package.json</em> file.</p>




<pre class="wp-block-code"><code>{
  "name": "simple_webserver",
  "version": "0.0.1",
  "main": "server.js",
  "author": "Patrick Rottlaender",
  "dependencies": {
    "express": "4.17.1"
  }
}

</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: It is also possible to tell <em>npm</em> at the time of the installation of a package that the latest version must be installed initially but the entry in the package.json file will be made without the preceding &#8222;^ &#8230;&#8220;. Then <em>npm install</em> does not update the version that is in the package.json file. </p>
</blockquote>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Using the example of the installation of express, the installation would be carried out with the following command: <em>npm install express &#8211;save &#8211;save-exact</em>.</p>
</blockquote>



<p>If we assume we want to install exactly the same packages as dependencies in another directory or even on a different computer, we would proceed as follows. This is exactly the scenario when we have developed and tested an application and now want to bring this application into the production environment.</p>




<ul class="wp-block-list">
	<li>we create a new target application root directory (new target directory)</li>
	<li>we copy the package.json file into the new target directory</li>
	<li>we copy the application files, in our case this is just the file <em>server.js</em> in the new target directory</li>
	<li>we change to the new target directory  </li>
	<li>We run the command <em>npm install</em> without any other option<br></li>
</ul>



<pre class="wp-block-code"><code>Patricks-MBP:node-basic patrick$ pwd
/Users/patrick/Software/dev/node/myArticles/2020-03-08/node-basic

Patricks-MBP:node-basic patrick$ ls -l
total 48
drwxr-xr-x  52 patrick  staff   1664 08 Mär 09:26 node_modules
-rw-r--r--   1 patrick  staff  14300 08 Mär 09:26 package-lock.json
-rw-r--r--   1 patrick  staff    171 08 Mär 09:26 package.json
-rw-r--r--   1 patrick  staff    526 08 Mär 07:40 server.js

Patricks-MBP:node-basic patrick$ cd ..

Patricks-MBP:2020-03-08 patrick$ ls -l
total 0
drwxr-xr-x  6 patrick  staff  192 08 Mär 09:26 node-basic

Patricks-MBP:2020-03-08 patrick$ mkdir express-basic

Patricks-MBP:2020-03-08 patrick$ ls -l
total 0
drwxr-xr-x  2 patrick  staff   64 08 Mär 09:39 express-basic
drwxr-xr-x  6 patrick  staff  192 08 Mär 09:26 node-basic

Patricks-MBP:2020-03-08 patrick$ cp node-basic/package.json express-basic
Patricks-MBP:2020-03-08 patrick$ cp node-basic/server.js express-basic

Patricks-MBP:2020-03-08 patrick$ cd express-basic

Patricks-MBP:express-basic patrick$ ls -l
total 16
-rw-r--r--  1 patrick  staff  163 08 Mär 10:03 package.json
-rw-r--r--  1 patrick  staff  526 08 Mär 09:40 server.js

Patricks-MBP:express-basic patrick$ cat package.json

{
  "name": "simple_webserver",
  "version": "0.0.1",
  "main": "server.js",
  "author": "Patrick Rottlaender",
  "dependencies": {
    "express": "4.17.1"
  }
}

Patricks-MBP:express-basic patrick$ npm install

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN simple_webserver@0.0.1 No description
npm WARN simple_webserver@0.0.1 No repository field.
npm WARN simple_webserver@0.0.1 No license field.

added 50 packages from 37 contributors and audited 126 packages in 1.864s
found 0 vulnerabilities

Patricks-MBP:express-basic patrick$ ls -l
total 48
drwxr-xr-x  52 patrick  staff   1664 08 Mär 10:05 node_modules
-rw-r--r--   1 patrick  staff  14292 08 Mär 10:05 package-lock.json
-rw-r--r--   1 patrick  staff    163 08 Mär 10:03 package.json
-rw-r--r--   1 patrick  staff    526 08 Mär 09:40 server.js

Patricks-MBP:express-basic patrick$  

</code></pre>



<h3 class="wp-block-heading">Chapter 4: The simple webserver using the Express.js module</h3>



<p>We are now working in the following directory. You can find the code on my <a href="https://github.com/prottlaender/node-part-1-simple-express-webserver">GitHub Page</a>.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ pwd
/Users/patrick/Software/dev/node/myArticles/2020-03-08/express-basic

Patricks-MBP:express-basic patrick$ 
</code></pre>



<p>If we now want to use the Express module in our web application, we have to load the express module with the require() function. The express module returns a function and this function is stored in the constant <em>express</em>. When you call the express() function an <em>app object</em> will be returned. This app object will be now stored in the const <em>app</em> and can now be used in the <em>server.js</em> file. The code in server.js is now as follows.</p>




<pre class="wp-block-code"><code>// server.js

// load http module
const http = require('http')

// load the Express module
const express = require('express')

const app = express()

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My express web server is alive and running at port 3000')

</code></pre>



<p>As we can see in the code, we are now using the app as a parameter for the createServer() function. createServer() therefore creates and express web-server. Now lets run the code with node server.js and see what happens.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ node server.js
My express web server is alive and running at port 3000

</code></pre>



<p>Perfect! The express server is running on localhost port 3000. But if we enter <em>http://localhost:3000</em> in the browser we get an error message <em>Cannot GET /</em>. This is actually clear since we have not yet defined any routes in the code that tell the server how to respond to a request for the route &#8222;/&#8220;. </p>




<p>But there is something else interesting: the response of the server with the text <em>Cannot GET /</em> is already a website. That means Express already takes over for us the part of the error handling that we programmed without Express in the code above in a specific instruction.</p>




<p>This becomes even clearer when we issue an http request in the terminal with the help of the curl program.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i http://localhost:3000
HTTP/1.1 404 Not Found
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 139
Date: Sun, 15 Mar 2020 06:15:11 GMT
Connection: keep-alive

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;Error&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;pre&gt;Cannot GET /&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;

Patricks-MBP:express-basic patrick$ 

</code></pre>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: curl is a program to transfer data from and to a server. curl supports some protocols including http. The -i option include the HTTP response headers in the output. The HTTP response headers include i.e. HTTP version, Content-Type, Date etc. </p>
</blockquote>



<p>In the curl output above you can exactly see that the response from the server is a 404 Not Found http code and an html document to display an error HTML document in the browser. This is something that Express do for us. </p>




<p>So now we have to define routes to tell the server what to send in response when a particular route is requested. There are Express functions for certain http verbs like get(), post(), put() or delete() already available in Express. These functions are used on the app, which we referenced in our code with the constant app. So lets change our code as follows.</p>




<pre class="wp-block-code"><code>// server.js

// load http module
const http = require('http')

// load the Express module
const express = require('express')

const app = express()

// define the routes
app.get('/', (req, res) =&gt; {
  res.send('Hello, this is my home Page')
})

app.get('/about', (req, res) =&gt; {
  res.send('Hello, this is my about Page')
})

// create the server
const server = http.createServer(app);

// server listen for any incoming requests
server.listen(3000);

console.log('My express web server is alive and running at port 3000')


</code></pre>



<p>As you see I added a route definition for get(). The http verb functions like get() expect two parameters:</p>




<ol class="wp-block-list">
	<li>the route to be defined</li>
	<li>the http handler which is transferred as a callback function with the parameters req and res. This http handler will give the server the instructions it needs to respond to the request for this particular route. Other routes like /about require a separate route definition.<br></li>
</ol>



<p>We start <em>server.js</em> again and request the routes via the browser with <em>http://localhost:3000</em> and <em>http://localhost:3000/about</em> and find that the response defined in <em>res.send</em> is sent as HTML from the server. Thats good. </p>




<p>With curl and requesting route <em>/about</em> we get the following terminal output.</p>




<pre class="wp-block-code"><code>Patricks-MBP:express-basic patrick$ curl -i http://localhost:3000/about

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 28
ETag: W/"1c-qDZjsFWQH9PGrhmVTBEfY+9a0Fo"
Date: Sun, 15 Mar 2020 05:44:19 GMT
Connection: keep-alive

Hello, this is my about Page

Patricks-MBP:express-basic patrick$

</code></pre>



<p>The curl output now show 202 Ok http code and the html document content <em>Hello, this is my about Page</em>. So its all working fine so far.</p>




<h3 class="wp-block-heading">Summary and Outlook</h3>



<p>In this Part 1 I created a simple node.js web-server that respond to various http requests from a browser. I explained the basics of Node.js such as the installation of node and npm, the use of modules and configuration of the package.json file. Then I installed the Express.js framework as a dependency of my server application and configured it so that it can be used by the simple web-server.</p>




<p>In the following <a href="https://digitaldocblog.com/webserver/nodejs-series-part-2-create-a-simple-blog-app-with-expressjs/" title="Node.js series Part 2. Create a Simple Blog App with Express.js">Part 2</a> of this node.js series I will explain the Express.js framework much more in detail. We will learn something about web api(s) and we will understand how we can use Express as middleware in a web application. And we will create a small blog application. </p>




]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>node.js and npm on Mac OS</title>
		<link>https://digitaldocblog.com/mac/nodejs-and-npm-on-mac-os/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 10 Sep 2019 17:00:00 +0000</pubDate>
				<category><![CDATA[Mac OS]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=61</guid>

					<description><![CDATA[node.js (or simply node) basically is a server side programming language to run JavaScript Code outside the browser. With node a developer can create server side programs in Java Script.&#8230;]]></description>
										<content:encoded><![CDATA[
<p><a href="https://nodejs.org/en">node.js</a> (or simply node) basically is a server side programming language to run JavaScript Code outside the browser. With node a developer can create server side programs in Java Script.</p>



<p>node contain various modules directly compiled into the node package like modules to access the network in asynchrons mode or modules to access the file system. Furthermore other modules can be embedded. These are precompiled files with .node extension or JavaScript modules. To manage these modules for node the <a href="https://docs.npmjs.com">node package manager (npm)</a> exist. The npm package repository has more than 700.000 packages that can be installed with the npm package manager.<br></p>



<h3 class="wp-block-heading">Installation of node and npm</h3>



<p>node can be installed on a Mac with <a href="https://brew.sh/index_de">homebrew</a>. <a href="https://nodejs.org/en">node</a> comes with <a href="https://docs.npmjs.com">npm</a>.</p>



<p>Before node can be installed it must be checked if xcode command line tools are installed on the system.</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ xcode-select -p
/Library/Developer/CommandLineTools
Macbook Pro:~ user$

</code></pre>



<p>The above command return that xcode command line tools are installed on your Mac and show the directory path where xcode command line tools are installed.</p>



<p>In case xcode command line tools are not installed run the following command in shell:</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ xcode-select --install

</code></pre>



<p>Then it must be checked if Homebrew is installed.</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ brew --version
Homebrew 1.7.7
Homebrew/homebrew-core (git revision 45d56; last commit 2018-10-08)
Homebrew/homebrew-cask (git revision 33e4d; last commit 2018-10-09)
Macbook Pro:~ user$

</code></pre>



<p>The above output show Homebrew 1.7.7 is installed on the Mac. In case Homebrew is not istalled so far run the follwoing command from shell:</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

</code></pre>



<p>Check the Homebrew installation.</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ brew doctor
Your system is ready to brew.
Macbook Pro:~ user$

</code></pre>



<p>To start with the node installation run the following command from shell:</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ brew install node

</code></pre>



<p>After installation Homebrew created symlinks for node and npm in <code>/usr/local/bin</code> and symlink to the location where the relevant binaries have been installed.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:~ patrick$ ls -l /usr/local/bin
total 8

....

lrwxr-xr-x  1 patrick  admin   30  5 Jun 09:04 node -&gt; ../Cellar/node/14.4.0/bin/node
lrwxr-xr-x  1 patrick  admin   38  5 Jun 14:22 npm -&gt; ../lib/node_modules/npm/bin/npm-cli.js

....

</code></pre>



<p>We see that node has been installed in</p>



<p><code>/usr/local/Cellar/node/14.4.0/bin/node</code></p>



<p>and npm has been installed in </p>



<p><code>/usr/local/lib/node_modules/npm/bin</code></p>



<h3 class="wp-block-heading">npm package management</h3>



<p>npm install software packages always in <code>node_modules</code> directory. If you have not installed any software oackages with npm so far this directory does not exist and will be created during the installation process.</p>



<p>The installation of a software package with npm will be started with the following command.</p>



<p><code>npm install &lt;package&gt;</code> </p>



<p>You can install software packages as <em>Global Software Packages</em> or as <em>Local Software Packages</em>. </p>



<h3 class="wp-block-heading">Global Software Packages</h3>



<p>If you want to use a software not only within a specific project but in global context on your machine then you provide the <code>-g</code> option in the install command.</p>



<p><code>npm install -g &lt;package&gt;</code></p>



<p>Then npm install this package in a global <code>node_modules</code> directory. </p>



<p><code>{prefix}/lib/node_modules</code></p>



<p>The <code>prefix</code> can be determined as follows</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ npm config get prefix
/usr/local
Macbook Pro:~ user$

</code></pre>



<p>On my machine all global packages are installed under </p>



<p><code>/usr/local/lib/node_modules</code></p>



<p>To list all installed global packages on your machine you can <code>ls -l</code> the global <code>node_modules</code> directory.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:~ patrick$ ls -l /usr/local/lib/node_modules
total 0
drwxr-xr-x  24 patrick  admin  768  5 Jun 14:22 npm
drwxr-xr-x  21 patrick  admin  672  5 Jun 14:21 pm2

</code></pre>



<p>You can also list all global packages with the npm command.</p>



<pre class="wp-block-code"><code>Macbook Pro:~ user$ npm list -g --depth=0
/usr/local/lib
├── firebase-tools@5.0.1
└── npm@6.4.1
Macbook Pro:~ user$
</code></pre>



<p>To maintain your global packages run the following commands.</p>



<p>Check for outdated global packages</p>



<p><code>npm outdated -g --depth=0</code></p>



<p>Update a specific global package</p>



<p><code>npm update -g &lt;package&gt;</code></p>



<p>Update all global packages</p>



<p><code>npm update -g</code></p>



<h3 class="wp-block-heading">Local Software Packages</h3>



<p>Local Software Packages are dependencies of a node project. This mean these software packages are required by the project code to run correctly. </p>



<p>If you want to use a software package only in the context of a node project then you create a separate project subfolder on your system and change to this subfolder with <code>cd</code>. Any software package that will be installed under this subfolder is a dependency of your node project. </p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:test patrick$ pwd
/Users/patrick/Software/dev/node/test

Patricks-Macbook Pro:test patrick$ cd mytestproject

Patricks-Macbook Pro:mytestproject patrick$ pwd
/Users/patrick/Software/dev/node/test/mytestproject

Patricks-Macbook Pro:mytestproject patrick$ 

</code></pre>



<p>Now you are in the <code>mytestproject</code> application root directory. Run the command <code>npm init</code> from the application root directory.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:mytestproject patrick$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install &lt;pkg&gt;` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (mytestproject) 
version: (1.0.0) 
description: This is my Test Project
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: Patrick Rottlaender
license: (ISC) 
About to write to /Users/patrick/Software/dev/node/test/mytestproject/package.json:

{
  "name": "mytestproject",
  "version": "1.0.0",
  "description": "This is my Test Project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "Patrick Rottlaender",
  "license": "ISC"
}


Is this OK? (yes) yes
Patricks-Macbook Pro:mytestproject patrick$ ls -l
total 8
-rw-r--r--  1 patrick  staff  251 14 Jun 08:58 package.json

Patricks-Macbook Pro:mytestproject patrick$

</code></pre>



<p>A package.json file has been created in your application root directory. This package.json file contain meta data about your project. Now we create the index.js file as our main application file for the project.</p>



<p>You can name the main application file as you like. It is only important that under &#8222;main&#8220; in the package.json file the file name match with the main application file name in your project root directory.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:mytestproject patrick$ touch index.js

Patricks-Macbook Pro:mytestproject patrick$ ls -l
total 8
-rw-r--r--  1 patrick  staff    0 14 Jun 09:08 index.js
-rw-r--r--  1 patrick  staff  251 14 Jun 08:58 package.json

Patricks-Macbook Pro:mytestproject patrick$
</code></pre>



<p>Dependencies are installed as local packages from a project root directory running the following command.</p>



<p><code>npm install &lt;package_name&gt; --save</code></p>



<p>npm will then create a <code>node_modules</code> directory under your project root directory and install the local packages there (incl. the dependencies of this new local package if there are any). npm will also create a <code>package-lock.json</code> file containing the current complete directory tree of all dependencies. </p>



<p>The package.json file is adapted and the new local software package is entered there as a dependency.</p>



<p>I have taken the following example 1:1 from the <a href="https://www.taniarascia.com/how-to-install-and-use-node-js-and-npm-mac-and-windows">website of Tanja Rascia</a>. If you want to read more details pls. go to Tanjas website. </p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:mytestproject patrick$ npm install left-pad --save

npm WARN deprecated left-pad@1.3.0: use String.prototype.padStart()
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN mytestproject@1.0.0 No repository field.

+ left-pad@1.3.0
added 1 package from 1 contributor and audited 1 package in 0.974s
found 0 vulnerabilities

Patricks-Macbook Pro:mytestproject patrick$ ls -l
total 16
-rw-r--r--  1 patrick  staff    0 14 Jun 09:08 index.js
drwxr-xr-x  3 patrick  staff   96 14 Jun 09:27 node_modules
-rw-r--r--  1 patrick  staff  366 14 Jun 09:27 package-lock.json
-rw-r--r--  1 patrick  staff  301 14 Jun 09:27 package.json

Patricks-Macbook Pro:mytestproject patrick$ cat package.json
{
  "name": "mytestproject",
  "version": "1.0.0",
  "description": "This is my Test Project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "author": "Patrick Rottlaender",
  "license": "ISC",
  "dependencies": {
    "left-pad": "^1.3.0"
  }
}
Patricks-Macbook Pro:mytestproject patrick$ 
</code></pre>



<p>After this we can write the code in <code>index.js</code> and use the functionality of <code>left-pad</code>. Therefore we must require the dependency at the beginning of the code.</p>



<pre class="wp-block-code"><code>// index.js

const leftPad = require('left-pad') // Require left pad
const output = leftPad('Hello, World!', 15) // Define output

// Send output to the console
console.log(output)

</code></pre>



<p>We run the programm using the following command and get the output on the console. </p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:mytestproject patrick$ node index.js
  Hello, World!
Patricks-Macbook Pro:mytestproject patrick$

</code></pre>



<p>For more information about npm and package management pls. check the getting started section on <a href="https://docs.npmjs.com">npm documentation site</a> and the <a href="https://www.npmjs.com">npm website</a> .</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
