If you’re building a back-end using JavaScript, there are high chances you’re going to use express.js. Express is a web framework in the node.js which is used by plenty of developers to simplify web application development.
What is Express.js?
It is a simple and easy to use web application framework used for node.js. This helps developers to build server-side web application and API efficiently. It is used for managing some complex tasks such as handling requests, managing routes, using middleware and make back-end development more efficient and faster. It acts like a helper library which makes server-side development much easier.
Why Express.js?
- It is a minimal framework which makes web development more simplified by providing multiple features.
- It makes handling of multiple routes for different web pages very simple.
- Express.js is an easy to learn framework which also makes easy for us to set-up an API.
- Express.js an unopinionated framework which means you don’t have to follow certain set of rules to build your web application. It makes your code look more organized and make it flexible and easy to use.
- It provides various middleware packages via npm.
What you have to do is:
- Install the package
- Instantiate the express app
- Set it to listen to a port.
How to instal Express.js?
- Install Node.js
- Firstly, we will install Node.js on our system to use Express.js.
- Visit the official website ‘nodejs.org’ to install node
- After installing Npde.js, check the version of Node.js installed using command prompt.

- Create a new Node.js project
- Go to the command prompt and create a directory for your express.js project using (mkdir project_name) command.

- Change the directory in which you want to instal express.js by command i.e. cd ExpressProject.

- Open the ExpressProject folder in vs code by right clicking on it.

- Go to the upper left-hand corner and click on the menu icon and choose new terminal.

- Initializing the Node.js project
- Use ‘npm init’ command in the terminal to create a package.json file for our applications.

- This will further ask you some details and we will click on enter to proceed further.
- This is how package.json file is successfully created.

- We will create index.js file which is the entry point of the project.

- Install Express.js
- Now, install express in ExpressProject directory and save it in the dependencies list.


- Go to the package.json file and you will see the version of express installed.

Writing our first Express.js Program:
- Write the code shown below in index.js file.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World !!');
});
app.listen(4000);
Understanding the code:
- Const express = require(‘express’): This expression has imported the Express.js module.
- Const app = express(): Calls the express function “express()” and puts new Express application inside the app variable (to start a new Express application).
- app.get(route, callback): This app.get() function tells what to do when a get request at the given route is called.
The get method takes 2 arguments:
- Route (URL Path): This is defined as location where the request is being sent.
- Call Back function (Request Handler): This function runs when the route is accessed.
- res.send(): This function takes an object as input and it sends this to the requesting client. Here we are sending the string “Hello World!”.
- app.listen(3000): This function binds and listens for connections on the specified host and port. Port is the only required parameter here. Serve is also being started at this point of time.

Running the Express server
- To run this application, we have to open the terminal and run ‘node index.js’ command.

- Open the browser and type ‘localhost:4000/’ to see the output.

Express.js Routing: Handling different Routes
Client server architecture is closely linked with routing, as it determines how URL request from the client reaches the appropriate server and how the responses are sent back to the client accordingly.

Routing is a process which defines how an application responds to a client request to a particular endpoint, which is a URL and a specific HTTP request method.
We will create routes for different pages using GET method.
Code:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World !!');
});
app.get('/about', (req, res) => {
res.send('Hello from about page !!');
});
app.get('/contact', (req, res) => {
res.send('Hello from contact page !!');
});
app.get('*', (req, res) => {
res.send('404 Error Not Found');
});
app.listen(4000);


- In the above code, we have created a single handler function for each route. But, each route can have more than one handler functions, which are executed when the route is matched.
- If we try to access a Route in express.js that has not been create yet, it will show some error. This is because the particular route is not defined in the server.
For example:

- If we want to display customized message for undefined routes, we have to make some modification in the code only.
app.get('*', (req, res) => {
res.send('404 Error Not Found');
});

Generating query strings
Query string is defined as the part of URL which contains additional information in key value pairs. These are generated using ‘?’.
- Query parameters are being accessed using ‘req.query’.
app.get('/search', (req, res) => {
console.log("Data sent by client: ", req.query); //This will be reflected on the console screen.
res.send('Hello from search page !!');
});
- This code defines the GET routes that listens the requests from the search endpoint.


Using Middleware in Express.js
Middleware is a function or program that will run between the time when the server gets the request and the time when the server sends the request out to the client.
When we click refresh, we are sending a request to the server and this app.get processes the request.
app.get('/', (req, res) => { // Route for home page
res.send('Hello World !!');
});
Middleware is one of the core features of express.js. It plays an important role in handling routing, requests and responses.
Middleware are functions that do have access to request object, the response object, and the next middleware function in the request-response cycle.
They are invoked by Express.js routing layer. Get the top react js interview questions
Middleware is a handler function that is being create inside use() function.
mIddleware in express.js contains three parameters:
- Req(Request Object)
- Res(Response Object)
- Next( next function)
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is First Middleware.');
next(); //This is used to forward our request to next route/Middleware function.
res.end('Stopped'); // This is used to end the response.
});
app.get('/', (req, res) => {
res.send('Hello World !!');
});
app.listen(4000);
- When next() function is used: The request is forwarded to next route.

- Res.end(): This command is used to end the response and do not want to forward the request.

Error Handling in Express
Whenever there is some error occurs in an application, we need to go through the error handling process. While working with the node environment and express.js, we will not be able to go through the traditional try-catch block method for the error handling.
There are two possible ways to handle the incoming errors at runtime.
- You can go for node error handling concept.
- You can also implement the error handling in express through the middle wares.
Firstly, we need to create a basic express server.
All the middle wares would be having request, response and next () as parameters. But if we are using middleware for error handling, we’d be adding one more argument here that is the “err.”
const express = require('express');
const app = express();
app.get('/', function(req, res){
var err = new Error("Something went wrong"); // Creates an error
next(err); //This passes the error to error-handling middleware
});
app.use(function(err, req, res, next) {
res.status(500); //Internal server error
res.send("oops,Something went wrong") //This will send an error message to the user.
});
app.listen(4000);
Whenever a user visit “/”, an error is created and it will be sent to the next middleware.
Trying your hand at a new skill is not always easy. You might face difficulties while learning new concepts, but with consistency, practice and dedicated resources, you will develop better understanding of them. Express.js is a great choice for beginners who want to excel in MERN STACK development. Now, you have enough understanding of the topic and it’s the time to put all your knowledge into practical.
If you are looking for expert guidance and structured courses, we offer both offline and online courses for web development as well as some dedicated Mern stack development course in Delhi and online MERN stack course with express js which will help you land a you job faster. These courses provide you an expert guidance, hands on experience with real life scenarios and a perfect curriculum to follow.