Let's Just Blog-106


Web Development with ExpressJS?
Following Let's Just Blog-105, and git hub repo letjustblog-mean we learned how to spin a appserver and use angular attribute to serve web page. In this blog, we will dig a bit deeper into the features of expressJS for serving HTML content and enable different routes. We will rely on templating engine like PUG, EJS to serve dynamic content.

Housekeeping Tasks for Express App
1) Create a Node App with npm init. Install the Express module.
npm install express --save

2) Import the express module with the require function. Create the Express App with express function.
const express = require('express');
const app = express();

2) Install other modules to enable the express App. We will also use Express Router to enable elegant routing in the Express App.
const bodyParser = require('body-parser');
const router = express.Router();

3) Create a server using http node module and pass the express app as a parameter to createserver method. However you can also call listen function directly on the express app.
var server = http.createServer(app);
server.listen(port);

4) Express is a routing and middleware framework that act as a series of middleware function calls. Middleware functions have access to the request object(req), response object(res) and next() in the application request - response cycle.
app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

4) Express generator is easy way to scaffold an Express App, which uses default templating engine as Pug, but there is EJS, which is more natural for JS developers and handlebars. With view engine setup as ejs, render method on res object will serve the index page in the views directory and pass the object specified in the second parameter to enable dynamic views.
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

Understanding Web MVC Approach?
[Model, View, Controller], an architectural style to glue the DOM with the data with controllers being the intermediary has been the basis for many front end frameworks.


MVC is composed of three components:
Model - It is where is data objects are managed, and with the ever growing API ecosystem, data received in JSON is stored as Javascript Objects.

View - It is what is presented to the user and how users interact with the app.

Controller - It is the decision maker and the glue between model and view. The controller updates the view when the model changes. It also adds event listeners to the view and updates the model when the user manipulates the view.


Design Approach for an Express App

In scalable architecture, we design in layers, for example UI, APIs, Services/Integration and Persistence tiers. In simplified prototypical design, we can create UI with template engine like EJS, API & Service with routes and controllers, and persistence with single node No-SQL instance.

Seeding Phase
a) Instantiate a Node server and install the required modules [express, body-parser, ejs, mongoose, nodemon]

b) Create an express app, set the view engine as EJS and serve the index page with the root route. One can create reusable partials for Header, Footer and Navigation.

Planning Phase
a) A product view of the app will allow you to iterate with MVC pattern. Let's just say that starting feature is to allow the application to add and view product. We understand that we will need the product document as model and controller functions to create (POST) and retrieve (GET) products.

b) We also should start designing the full CRUD feature for product model to support the technical view, as admin functions will require the Edit & Delete feature on the product model.

Prototyping Phase
a) EJS views should be inline with wireframes, controller with CRUD functions should be architected within design guidelines and model has to tested with database connectivity.

b) We should also test the integrated view with few products, create additional routes for edit & delete functions and start designing for logging and error handling functions.

c) We have to also start prototyping user functions like cart & order features, which may require modeling additional collections, adding additional objects / arrays in the existing product collection.

d) In my opinion, I think we need to prototype with NoSQL database like MongoDB even though the data resides in relational database. We can leverage node modules like mongoose that provides the ODM for MongoDB, and there is also sequelize that provides the ORM for MySQL in Node ecosystem.


Web Signup and Authentication
a) We understand that web operates with request-response stateless principle, which means each request from the browser to our Node / Express server is an independent request. Traditional web authentication relies on cookies and sessions to keep user login across requests and destroys the session when user logs out. We can use node modules like express-session to develop authentication module in express app.

const session = require('express-session'); 
const MongoDBStore = require('connect-mongodb-session')(session);

const store = new MongoDBStore({
  uri: MONGODB_URI,
  collection: 'sessions'
});

app.use(
  session({
    secret: 'my secret',
    resave: false,
    saveUninitialized: false,
    store: store
  })
);

b) In the signup flow, we have to create the user in the backend DB, and can use bcryptjs node module to hash the password before save the user to the collection. During the login flow, we can then find the user with an email, use bcryptjs compare method to match the password, and set the authentication flag for successful login which can used in the views to control access.

c) Features like Route protection and CSRF are required for hardening the authentication module.

c.1) One of the ways we can enable route protection is to check for authentication flag before we render the view and if the view has to be protected, we redirect the user to the login view if session doesn't have the authentication flag.

c.2) We can leverage the cusrf node module to enable cross-site-request-forgery protection, and after we register the csrf protection on express app, all views are required to send the csrf token to validate the authenticity and requests from fake sites will be rejected by our express app.

d) Robust authentication module requires features like Resetting Password, post & delete method on route is accessible by authorized users.

Comments