Cookies Management, Routing and Template Engine in ExpressJS

Last updated on Jan 18 2023
Prabhas Ramanathan

Table of Contents

Express.js Cookies Management

What are cookies

Cookies are small piece of information i.e. sent from a website and stored in user’s web browser when user browses that website. Every time the user loads that website back, the browser sends that stored data back to website or server, to recognize user.

Install cookie

You have to acquire cookie abilities in Express.js. So, install cookie-parser middleware through npm by using the following command:

Import cookie-parser into your app.

1. var express = require('express'); 
2. var cookieParser = require('cookie-parser'); 
3. var app = express(); 
4. app.use(cookieParser());

Define a route:

Cookie-parser parses Cookie header and populate req.cookies with an object keyed by the cookie names.
Let’s define a new route in your express app like set a new cookie:

1. app.get('/cookie',function(req, res){ 
2. res.cookie('cookie_name' , 'cookie_value').send('Cookie is set'); 
3. }); 
4. app.get('/', function(req, res) { 
5. console.log("Cookies : ", req.cookies); 
6. });

Browser sends back that cookie to the server, every time when it requests that website.

Express.js Cookies Example

File: cookies_example.js

1. var express = require('express'); 
2. var cookieParser = require('cookie-parser'); 
3. var app = express(); 
4. app.use(cookieParser()); 
5. app.get('/cookieset',function(req, res){ 
6. res.cookie('cookie_name', 'cookie_value'); 
7. res.cookie('company', ' tecklearn'); 
8. res.cookie('name', 'sonoo'); 
9. 
10. res.status(200).send('Cookie is set'); 
11. }); 
12. app.get('/cookieget', function(req, res) { 
13. res.status(200).send(req.cookies); 
14. }); 
15. app.get('/', function (req, res) { 
16. res.status(200).send('Welcome to tecklearn!'); 
17. }); 
18. var server = app.listen(8000, function () { 
19. var host = server.address().address; 
20. var port = server.address().port; 
21. console.log('Example app listening at http://%s:%s', host, port); 
22. });

Set cookie:

Now open http://127.0.0.1:8000/cookieset to set the cookie:

n 1

Get cookie:
Now open http://127.0.0.1:8000/cookieget to get the cookie:

Express.js Routing

Routing is made from the word route. It is used to determine the specific behavior of an application. It specifies how an application responds to a client request to a particular route, URI or path and a specific HTTP request method (GET, POST, etc.). It can handle different types of HTTP requests.
Let’s take an example to see basic routing.
File: routing_example.js

1. var express = require('express'); 
2. var app = express(); 
3. app.get('/', function (req, res) { 
4. console.log("Got a GET request for the homepage"); 
5. res.send('Welcome to tecklearn!'); 
6. }) 
7. app.post('/', function (req, res) { 
8. console.log("Got a POST request for the homepage"); 
9. res.send('I am Impossible! '); 
10. }) 
11. app.delete('/del_student', function (req, res) { 
12. console.log("Got a DELETE request for /del_student"); 
13. res.send('I am Deleted!'); 
14. }) 
15. app.get('/enrolled_student', function (req, res) { 
16. console.log("Got a GET request for /enrolled_student"); 
17. res.send('I am an enrolled student.'); 
18. }) 
19. // This responds a GET request for abcd, abxcd, ab123cd, and so on 
20. app.get('/ab*cd', function(req, res) { 
21. console.log("Got a GET request for /ab*cd"); 
22. res.send('Pattern Matched.'); 
23. }) 
24. var server = app.listen(8000, function () { 
25. var host = server.address().address 
26. var port = server.address().port 
27. console.log("Example app listening at http://%s:%s", host, port) 
28. }) 


You see that server is listening.

This can read the pattern like abcd, abxcd, ab123cd, and so on.
Next route http://127.0.0.1:8000/abcd

n 2

Next route http://127.0.0.1:8000/ab12345cd

n 3

Express.js Template Engine

What is a template engine

A template engine facilitates you to use static template files in your applications. At runtime, it replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. So this approach is preferred to design HTML pages easily.
Following is a list of some popular template engines that work with Express.js:
• Pug (formerly known as jade)
• mustache
• dust
• atpl
• eco
• ect
• ejs
• haml
• haml-coffee
• handlebars
• hogan
• jazz
• jqtpl
• JUST
• liquor
• QEJS
• swig
• templayed
• toffee
• underscore
• walrus
• whiskers
In the above template engines, pug (formerly known as jade) and mustache seems to be most popular choice. Pug is similar to Haml which uses whitespace. According to the template-benchmark, pug is 2x slower than Handlebars, EJS, Underscore. ECT seems to be the fastest. Many programmers like mustache template engine mostly because it is one of the simplest and versatile template engines.

Using template engines with Express

Template engine makes you able to use static template files in your application. To render template files you have to set the following application setting properties:
• Views: It specifies a directory where the template files are located.
For example: app.set(‘views’, ‘./views’).
• view engine: It specifies the template engine that you use. For example, to use the Pug template engine: app.set(‘view engine’, ‘pug’).
Let’s take a template engine pug (formerly known as jade).

Pug Template Engine

Let’s learn how to use pug template engine in Node.js application using Express.js. Pug is a template engine for Node.js. Pug uses whitespaces and indentation as the part of the syntax. Its syntax is aesy to learn.

Install pug

Execute the following command to install pug template engine:
1. npm install pug –save
Pug template must be written inside .pug file and all .pug files must be put inside views folder in the root folder of Node.js application.
Note: By default Express.js searches all the views in the views folder under the root folder. you can also set to another folder using views property in express. For example: app.set(‘views’,’MyViews’).
The pug template engine takes the input in a simple way and produces the output in HTML. See how it renders HTML:

Simple input:

1. doctype html
2. html
3. head
4. title A simple pug example
5. body
6. h1 This page is produced by pug template engine
7. p some paragraph here.

Output produced by pug template:

1. <!DOCTYPE html> 
2. <html> 
3. <head> 
4. <title>A simple pug example</title> 
5. </head> 
6. <body> 
7. <h1>This page is produced by pug template engine</h1> 
8. <p>some paragraph here.</p> 
9. </body> 
10. </html>

Express.js can be used with any template engine. Let’s take an example to deploy how pug template creates HTML page dynamically.
See this example:

Create a file named index.pug file inside views folder and write the following pug template in it:

1. doctype html
2. html
3. head
4. title A simple pug example
5. body
6. h1 This page is produced by pug template engine
7. p some paragraph here.

File: server.js

1. var express = require('express'); 
2. var app = express(); 
3. //set view engine 
4. app.set("view engine","pug") 
5. app.get('/', function (req, res) { 
6. res.render('view.pug', index); 
7. res.render('index'); 
8. }); 
9. var server = app.listen(5000, function () { 
10. console.log('Node server is running..'); 
11. });

So, this brings us to the end of blog. This Tecklearn ‘Cookies Management ,Routing and Template Engine in ExpressJS’ blog helps you with commonly asked questions if you are looking out for a job in NodeJS Programming. If you wish to learn NodeJS and build a career in NodeJS Programming domain, then check out our interactive, Node.js Training, that comes with 24*7 support to guide you throughout your learning period.

Node.js Training

About the Course

Tecklearn’s Node.js certification training course familiarizes you with the fundamental concepts of Node.js and provides hands-on experience in building applications efficiently using JavaScript. It helps you to learn how to develop scalable web applications using Express Framework and deploy them using Nginx. You will learn how to build applications backed by MongoDB and gain in-depth knowledge of REST APIs, implement testing, build applications using microservices architecture and write a real-time chat application using Socket IO. Accelerate your career as a Node.js developer by enrolling into this Node.js training.

Why Should you take Node.js Training?

• As per Indeed.com data, the average salary of Node.js developer is about $115000 USD per annum.
• IBM, LinkedIn, Microsoft, GoDaddy, Groupon, Netflix, PayPal, SAP have adopted Node.js – ITJungle.com
• There are numerous job opportunities for Node.js developers worldwide. The job market and popularity of Node.js is constantly growing over the past few years.

What you will Learn in this Course?

Introduction to Node.js

• What is Node.js?

• Why Node.js?
• Installing NodeJS
• Node in-built packages (buffer, fs, http, os, path, util, url)
• Node.js Modules
• Import your own Package
• Node Package Manager (NPM)
• Local and Global Packages

File System Module and Express.js

• File System Module
• Operations associated with File System Module
• JSON Data
• Http Server and Client
• Sending and receiving events with Event Emitters
• Express Framework
• Run a Web Server using Express Framework
• Routes
• Deploy application using PM2 and Nginx

Work with shrink-wrap to lock the node module versions

• What is shrink-wrap
• Working with npmvet
• Working with outdated command
• Install NPM Shrinkwrap

Learn asynchronous programming

• Asynchronous basics
• Call-back functions
• Working with Promises
• Advance promises
• Using Request module to make api calls
• Asynchronous Commands

Integration with MongoDB and Email Servers

• Introduction to NoSQL Databases and MongoDB
• Installation of MongoDB on Windows
• Installation of Database GUI Viewer
• Inserting Documents
• Querying, Updating and Deleting Documents
• Connect MongoDB and Node.js Application
• Exploring SendGrid
• Sending emails through Node.js application using SendGrid

REST APIs and GraphQL

• REST API
• REST API in Express
• Postman
• MongoDB Driver API
• Express Router
• Mongoose API
• GraphQL
• GraphQL Playground

Building Node.js Applications using ES6

• ES6 variables
• Functions with ES6
• Import and Export withES6
• Async/Await
• Introduction to Babel
• Rest API with ES6
• Browsing HTTP Requests with Fetch
• Processing Query String
• Creating API using ES6
• Building Dashboard API
• Creating dashboard UI with EJS
• ES6 Aside: Default Function Parameters
• Data Validation and Sanitization

User Authentication and Application Security

• Authentication
• Types of Authentication
• Session Vs Tokens
• JSON Web Tokens
• Bcrypt
• Node-local storage

Understand Buffers, Streams, and Events

• Using buffers for binary data
• Flowing vs. non-flowing streams
• Streaming I/O from files and other sources
• Processing streams asynchronously
• File System and Security

Build chat application using Socket.io

• Getting Started
• Adding Socket.io To Your App
• Exploring the Front-end
• Sending Live Data Back & Forth
• Creating the Front-end UI
• Showing Messages In App
• Working with Time
• Timestamps
• Show Message Time In Chat App
• Chat application Project

Microservices Application

• Why Microservices?
• What is Microservices?
• Why Docker?
• What is Docker?
• Terminologies in Docker
• Child Processes
• Types of child process

 

0 responses on "Cookies Management, Routing and Template Engine in ExpressJS"

Leave a Message

Your email address will not be published. Required fields are marked *