
Express.js tutorial: About the framework and how to use it
Express.js is a framework made for Node.js that allows you to easily and quickly create web applications using Javascript. Express.js is a free and open-source project made in 2017 by the OpenJS foundation and it is lightweight which makes it more environmentally friendly compared to other frameworks.
In this article, we will look at what Express.js is, how to install it, how to create your first project plus many more interesting subjects.
What is Express.js?
Express JS is a framework made for Node JS, and it is making your development process faster and easier. It is one of the smaller frameworks because they only included the necessary functions instead of filling it up with lots of stuff you will never need. Because Express JS is lightweight, we categorize it as being one of the more environmentally friendly frameworks you can use for your project and it also makes it faster.
Express JS makes development faster and more simple compared to writing code in plain Node JS. The framework is helping to simplify tasks such as writing middleware, routing, templating, and debugging.
How to install Express.js in your Node.js project.
Installing Express JS in your Node JS project is both fast and easy. Here we will guide you through the installation and you can simply copy/paste the code below.
Installing Express JS in your project:
First, you have to create a project you can import and use Express JS in. Open your terminal and write the following:
mkdir myapp cd myapp
Create a package.json file
Next, we need to start a new project and we do that by creating a package.json file using the following command. When creating your package.json you set your entry point to “index.js”:
npm init
Install and import Express.js
Now that we have an empty project we can install and import express.js in our project. Copy and paste the first line below in your terminal to install the package.
npm install express --save
Now you simply need to import express into your project. You can do that by adding the following line to the top of your index.js file.
const express = require('express');
How to create a "Hello world" example using Express.js.
To get you started with Express JS we will go through the easy Hello World project which is the same across different frameworks. The purpose of this is to give you a general idea of the minimal code needed to get started.
To start with you open up the index.js file you created earlier for your server. This file is going to contain your server code and it is here you will import express.
const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!') }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) });
At the beginning of the code snippet, we are importing express so it can be used in our project. Next, after we are running express JS and storing it in a variable so we can use it. We are also deciding on a port which our project will be running on.
Below our imports and declarations, we are writing our first route which will be taking us to “/“ root. Once we go to the root of our project we will be sent a text saying Hello world.
At the very bottom of our project, we are telling Express JS to listen for events on the port we specified earlier. If you now run “node index.js” in your terminal you should be able to go to localhost:3000 and see it says “Hello world”.
Handling static files in Express.js
Handling static files is easy, and in this section, we will be looking at how you can add static files to your project. In most cases, you will at some point be handling static files whether it is stylesheets, scripts, files, or pictures.
In our example, we have built a structure for our project where we have a “Public” folder in the root. Inside of this folder, we have another one called images and another called stylesheets. To be able to access these in Express JS we need to add one line to our code:
app.use(express.static('public'));
The line above is telling Express JS that we should be able to access static content inside the public folder. Now you should be able to access your files like the example below describes:
http://localhost:3000/images/kitten.jpg http://localhost:3000/css/style.css http://localhost:3000/js/app.js
Routing in Express.js
Routing in Express JS is easy and quick to get started with. With routing we mean handling HTTP requests such as GET, POST, PUT and DELETE. A route in Express JS is made up of your app, then the method, then the path, and last but not least the handler.
Here is an example where we've called our Express JS web application "app", and we are trying to send a text as a response to a GET request.
app.get("/", function (req, res) { res.send("Hello World!"); });
We can also create a simple POST request where we send back a text stating that we have received the request:
app.post("/post-request", function (req, res) { res.send("Got a POST request at /post-request"); });
The two examples above is showing in a simple way how we with only a little code can handle requests coming from the frontend. In a real-world example where the user has filled in a form, we would be looking at the req.body parameter to get the content sent from the client instead of simply sending back a message saying we received the request.
In a bit more advanced example where we receive a first and last name, email address, and a message we could be doing the following to get the data and use it in a function:
app.post("/post-request", function (req, res) { const { firstName, lastName, email, message } = req.body; res.send(`We have received the following values: ${firstName}, ${lastName}, ${email}, and ${message}`); });
In the example above we are saving the values from the req.body parameter and sending it back to the client. By getting the values from the req.body parameter we can use it for functions such as contact forms, newsletter signups, creating blog posts, etc.
How to create and add middleware in Express.js
Middleware functions are powerful and easy to implement in Express JS. A middleware function could for example take care of checking whether a logged-in user has the right to certain functions or upload an image.
The following example is a middleware code that will check if a user is logged in. If a user is logged in we will proceed and use the code written in the route, but if a user is not logged in we will redirect them to the login page:
middlewareObj.isLoggedIn = function(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect("/login"); };
We can implement and call this function in a route using the following example. What is happening is that we receive a request, call the middleware code, and then continue depending on whether a user is logged in or not.
router.get("/api/getsystemmessages", middleware.isLoggedIn, async (req, res) => { try { const systemMessages = await SystemMessage.find(); res.send(systemMessages); } catch(err) { console.log("Error happened"); } });
To read more in detail about middlewares, how they work and how to implement them, please check out this article from Express: https://expressjs.com/en/guide/writing-middleware.html.
Express.js is more environmentally friendly
Express JS is one of the more lightweight frameworks made for Node JS. It comes with a bunch of cool features but instead of being filled with unnecessary bloat, they choose that you have to install what you need.
The approach of adding what you need makes this framework more lightweight and hopefully more environmentally friendly compared to other frameworks. It is hard to determine whether something is more environmentally friendly than something else, but we believe that less is more.
You can read more about lightweight HTTP frameworks for Node JS in this article: https://sustainablewww.org/principles/5-most-lightweight-and-eco-friendly-node-js-framework-http-servers.
Wrapping up
So, in this article, we talked about what Express JS is and how you can use it with Node JS. We talked about how to install the framework, how to handle both GET and POST routes, and how to write and use simple middleware functions.
By the end of this article, you should have gotten a general understanding of what Express JS is and how to use it in your next project. If you have anything you believe should be added to this article or corrected, please don't hesitate to contact us via our contact page.
Author
Michael Andersen
I am a self-taught and highly passionate web developer currently living in Sweden, where I use my skills to make the internet a better place through ethical and sustainable web design.

Michael Andersen
I am a self-taught and highly passionate web developer currently living in Sweden, where I use my skills to make the internet a better place through ethical and sustainable web design.