Home  >  Blog  >   General  > 

ExpressJS Tutorial

ExpressJS evolved as a leading backend framework for web application development. Since it provides a wide range of functionality, it has become the top option for application development among developers all over the world. This Express.js tutorial will walk you through all the essential topics of the Express to help you get started with it.

Rating: 4.7
  
 
433
  1. Share:
General Articles

One of the first steps in building any web application is choosing a powerful backend technology. Although a few technological trends are gaining popularity, there can never be a one-size-fits-all solution. A backend technology may be adopted depending on the type of company, the development methodologies, and the target market. 

To help you out, we have detailed one of the leading backend technologies - ExpressJS. Based on its standard features and functionality, this tutorial will give you a complete insight into the fundamentals of ExpressJS.

So, let's get started!

Express JS Tutorial - Table of Contents

If you want to enrich your career and become a professional in Express JS, then enroll in "Express JS Training". This course will help you to achieve excellence in this domain.

What is ExpressJS?

ExpressJS or Express is an open-source and free server-side framework for Node.js. It was written in Javascript and is included in the MEAN, MEVN, and MERN stacks. Express provides middleware packages, routing capabilities, template code, and plugins for simplified web development.

Here are some market usage statistics for Express as a backend technology -

  • Express is the tenth most popular framework among the top 10,000 websites, according to BuiltWith research.
  • According to SimilarTech, Express is used to create about 245,657 websites worldwide.
  • Express is ranked fourth among the top 5 backend frameworks for 2021, according to a Statistics & Data study.

Popular apps that use Express as a backend technology include:

  • To speed up Twitter Lite, the company switched to Node.js Express.
  • Uber used Express to create its Bedrock base web server and optimize the Middleware for security, internationalization, and other connectors for their infrastructure.
  • Accuweather used Express to provide APIs for app integration.
  • IMDB also used the Express features to produce APIs that developers could incorporate into their applications.

Express.JS History

TJ Holowaychuk developed the ExpressJS framework. ExpressJS's GitHub source states that the initial release occurred on May 22, 2010. Version 0.12

In June 2014, StrongLoop acquired project management rights. IBM said in January 2016 that ExpressJS would now be under the control of the Node.js Foundation incubator after purchasing StrongLoop in September 2015.

Express.JS Features

Let's see some exciting features of ExpressJS:

  • Faster server-side Development: ExpressJS supports various valuable features of Node.js that you can use in the form of functions, which reduces the time of coding and increases development speed.
  • Routing: ExpressJS supports a highly advanced routing mechanism that allows preserving the web page's state with the help of its URLs.
  • Middleware: Middleware is responsible for the systemic organization of various functions of Express. It is a part of the program that handles requests and has access to the application's request-response cycle.
  • Templating: The inbuilt templating engines allow you to develop dynamic content on the web pages by building HTML templates on the server.
  • Debugging: Debugging is a crucial aspect of web application development. Express makes debugging easier by identifying where precisely the bugs are.

MindMajix Youtube Channel

Express JS Installation

To install Express, first, you must ensure that Node.js is installed in your system. After that, create a project directory to hold your application's project dependencies and make that your working directory. 

Use the below command to create a package.json file for your application.

$ npm init

This command drives you to numerous things like the name and version of your app. For now, you can simply hit RETURN to accept the defaults for most of them with the following exception:

entry point: (index.js).

Now, you can install Express globally using the following command:

$ npm install express

If you wish to install Express temporarily and not add it to the dependencies list, use the below command:

npm install Express --no-save.

Now that you are done with the installation of Express JS. Let's get into the fundamental concepts of the Express framework.

ExpressJS Fundamental Concepts

1. Routing

In Express JS, Routing determines an application's response to the client's request to a specific endpoint, a URI (or path), and a specific HTTP request method.

Each route contains one or more handler functions and is executed when the route is matched.

Following is the structure of Routing:

app.METHOD(PATH, HANDLER)

Where:

  • The app is an express's instance.
  • METHOD is an HTTP request method
  • PATH is a server's path
  • HANDLER is a callback function executed when the matching route is found.

You can use four HTTP methods within the request. These methods help in identifying the function made by the user. Let's learn about each HTTP method in detail:

  • GET: The HTTP GET method helps retrieve information from the server using a given URI. The GET requests only retrieve data without causing any other effect on the data.
  • POST: The HTTP POST request method sends data to a server or updates a resource.
  • PUT: The HTTP PUT request method helps accept the data enclosed within the request as an alteration to the current object specified by the URL.
  • DELETE: This method requests the server to delete a particular resource from the destination.

The following example illustrates the usage of all HTTP methods:

var express = require('express');
const app = express();
app.use(ExpressJSon());

app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.post('/', (req, res) => {
  res.send('Got a POST request')
})
app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user')
})
app.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user')
})

2. Middleware

In Express, Middleware functions are the functions that have access to the response object (res) and request object (req), along with the following function in the application's request-response cycle.

The following function is a function that, when invoked, operates the Middleware succeeding the existing Middleware.

The Middleware performs the following tasks:

  • Code execution
  • Perform modifications to the response and request objects.
  • End applications request-response cycle.
  • Call the succeeding Middleware existing in the cycle.

The below image illustrates the elements of a middleware function call:

Middleware Function Call

An Express application can use the following types of Middleware:

  • Application-level Middleware
  • Third-party Middleware
  • Error-handling Middleware
  • Built-in Middleware
  • Router-level Middleware
  • Application-level Middleware

You can use application-level Middleware to access an app object's instance using the app.use() and app.METHOD() functions, where METHOD is the HTTP request method that handles middleware functions like GET, POST, or PUT in lowercase.

The following examples depict a middleware function with no mount path. For every request made by the app, this function is executed.

const express = require('express')
const app = express()

app.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
})

The below example displays a middleware function mounted on the /user/:id path.

app.use('/user/:id', (req, res, next) => {
  console.log('Request Type:', req.method)
  next()
})
  • Router-level Middleware

This Middleware works exactly as application-level Middleware, except it is bound to an instance of Express.Router().

const router = express.Router()

Router-level middleware is loaded using the router.use() and router.METHOD() functions.

The following is an example of Router-level Middleware:

const express = require('express')
const app = express()
const router = express.Router()

// a middleware function with no mount path. This code is executed for every request to the router
router.use((req, res, next) => {
  console.log('Time:', Date.now())
  next()
})

// a middleware sub-stack shows request info for any HTTP request to the /user/:id path
router.use('/user/:id', (req, res, next) => {
  console.log('Request URL:', req.originalUrl)
  next()
}, (req, res, next) => {
  console.log('Request Type:', req.method)
  next()
})
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', (req, res, next) => {
  // if the user ID is 0, skip to the next router
  if (req.params.id === '0') next('route')
  // otherwise, pass control to the next middleware function in this stack
  else next()
}, (req, res, next) => {
  // render a regular page
  res.render('regular')
})

// handler for the /user/:id path renders a special page
router.get('/user/:id', (req, res, next) => {
  console.log(req.params.id)
  res.render('special')
})

// mount the router on the app
app.use('/', router)
  • Error-Handling Middleware

In Express, error-handling Middleware contains four arguments. 

Example of error-handling Middleware:

app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})
  • Built-in Middleware

Following are the built-in middleware functions of Express:

  • express.static serves static assets such as images, HTML files, etc.
  • ExpressJSon analyzes incoming requests with JSON payloads.
  • Express.urlencoded parses inbound requests that include payloads encoded with the URL.
  • Third-party Middleware

To give Express apps more functionalities, use third-party Middleware.

Install the Node.js module, then load it into your project at the router or application level.

$ npm install cookie-parser

The following example demonstrates how to install and load the cookie-parsing using Middleware:

const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')

// load the cookie-parsing Middleware
app.use(cookieParser())

3. Template Engines

The template engine's primary function is enabling the application's status template file usage. It replaces variables with actual values in a template file and modifies the template into an HTML file transferred to the client. This approach makes designing HTML pages easier.

Mustache, Pug, and EJS are some popular template engines that work with Express. By default, the Express generator uses Jade, along with others.

Template Engines

Learn Top ExpressJS Interview Questions and Answers that help you grab high-paying jobs

4. Error Handling

The process of catching and processing errors synchronously and asynchronously in Express is called Error Handling. By default, Express comes with support for the error handler, so you don't need to write your own to get started.

In Express, Middleware manages error handling. Compared to other middleware functions, the error handling middleware must have four arguments instead of three – err, req, res, next.

Let's see an example of how to send a response to any error -

app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!')
});

5. Debugging

To log information about route matches, application mode, middleware functions, and more internally, Express employs the debug module.

You can set the debugging environment using the following command -

$ DEBUG=express:* node index.js

By default, running this command generates the following output:

$ DEBUG=express:* node ./bin/www
 express:router:route new / +0ms
 express:router:layer new / +1ms
 express:router:route get / +1ms
 express:router:layer new / +0ms
 express:router:route new / +1ms
 express:router:layer new / +0ms
 express:router:route get / +0ms
 express:router:layer new / +0ms
 express:application compile etag weak +1ms
 express:application compile query parser extended +0ms
 express:application compile trust proxy false +0ms
 express:application booting in development mode +1ms
 express:router use / query +0ms
 express:router:layer new / +0ms
 express:router use / expressInit +0ms
 express:router:layer new / +0ms
 express:router use / favicon +1ms
 express:router:layer new / +0ms
 express:router use / logger +0ms
 express:router:layer new / +0ms

6. Scaffolding

While working with REST APIs, to accomplish any specific task, you must have seen that you need to work with various kinds of files such as CSS, HTML, etc. But managing and maintaining such files becomes a hassle. 

Thus Express provides a solution called Scaffolding. It allows us to create a structure for a web app and manage the files in proper directories. You can use Scaffolding to create a skeleton for an Express application. Yeoman, Express-generator, etc., are some of the tools supported by Express.

Now, let's understand how to create an essential structure for an application.

Using express-generator

Before you use the express-generator, you need to install it. Use the following code in the command prompt for the same.

npm install -g express-generator

Now Express-generator is ready to create the project skeleton. Enter the below command.

express

Once you hit enter, you can see the following output displayed in the below screenshot.

Express JS Output

7. Cookies

Small files or data sent to the client with a server request and stored on the client side are called cookies. Cookies help us in keeping track of users' actions.

Below are the various uses of the cookies - 

  • Personalization
  • Session management,
  • User tracking.

In Express, cookie-parser Middleware is needed to use cookies.

Use the following code to install it -

npm install --save cookie-parser

Cookie-parser is a middleware that parses the cookie attached to the client request object. Use the following code to use the index.js file.

var cookieParser = require('cookie-parser');
app.use(cookieParser());

To fill req.cookies with an object keyed by the cookie names, cookie-parser first parses the Cookie header. Let's define a new route in your Express app so that we may set a new cookie like this:

var express = require('express');
var app = express();

app.get('/', function(req, res){
   res.cookie('name', 'express').send('cookie set'); //Sets name = express
});

app.listen(3000);

Just open your browser, launch the console, and type to verify whether or not your cookie has been set.

console.log(document.cookie);

You will see the following output (you might have more cookies set due to browser extensions) -

"name = express"

Every time the browser queries the server, cookies are also sent. In a route, add the following code to view cookies from your server on the server console.

console.log('Cookies: ', req.cookies);

You will get the output below the next time you send a request to this route.

Cookies: { name: 'express' }

8. Sessions

Since HTTP is stateless, you must figure out how to preserve user data across requests to connect any two queries. Data transfer between clients and servers is accomplished using cookies and URL parameters. Though you may read them, they are on the client side. Sessions cover this topic in detail. For all subsequent requests, the client uses the ID you provide. Information about the client is stored on the server associated with this ID.

Use the following code to install the Express session since it is required.

npm install --save express-session

We will set up the Middleware for the session and cookie-parser. MemoryStore, the standard store for storing sessions, will be used in this example. Never use this in a setting that is in production. The session middleware takes care of everything, including establishing the session cookie and constructing the session object in the request object.

We will have their session information on file whenever we receive a request from the same client again. The session object can have additional features added. We'll establish a view counter for a client in the following example.

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

app.use(cookieParser());
app.use(session({secret: "Shh, its a secret!"}));

app.get('/', function(req, res){
   if(req.session.page_views){
      req.session.page_views++;
      res.send("You visited this page " + req.session.page_views + " times");
   } else {
      req.session.page_views = 1;
      res.send("Welcome to this page for the first time!");
   }
});
app.listen(3000);

The code above sets up a new session for the user and assigns them a cookie whenever they visit the website.

Conclusion

With this, we have come to the end of this ExpressJS tutorial. We hope we have explained ExpressJS's core concepts from the ground up.

Let us know if you have any questions by leaving a comment below.

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Express JS TrainingAug 05 to Aug 20
Express JS TrainingAug 08 to Aug 23
Express JS TrainingAug 12 to Aug 27
Express JS TrainingAug 15 to Aug 30
Last updated: 04 August 2023
About Author
Remy Sharp
Madhuri Yerukala

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

Recommended Courses

1 /15