While it is possible to render static websites from a server, this approach has many limitations, including code duplication and a lack of flexibility — particularly when it comes to reading data from a database. Fortunately, Express.js includes a template engine that allows us to generate dynamic HTML pages from our server-side applications.
A template engine operates in a straightforward manner: you create a template and pass variables into it using the appropriate syntax. The variables declared in your template file are then assigned values at the appropriate route to render the template. As the template is rendered, these are compiled in real-time.
In this blog, we will cover:
- What is Express.js?
- Frameworks built on Express.js
- Using template engines with Express.js
- Hands-on
- Conclusion
What is Express.js?
Express is a lightweight and adaptable Node.js web application framework that offers a comprehensive set of features for web and mobile applications. Creating a robust API is quick and easy with a plethora of HTTP utility methods and middleware at your disposal. Express adds a thin layer of fundamental web application features without interfering with the Node.js features you already know and love. Express is the foundation of many popular frameworks.
Frameworks built on Express.js
Express is the foundation of several popular Node.js frameworks, including:
- Feathers: Create real-time prototypes in minutes and production-ready apps in days.
- ItemsAPI: Search backend for Express and Elasticsearch-based web and mobile applications.
- KeystoneJS: is a website and API application framework/CMS with an auto-generated React.js admin interface.
- Poet: is a lightweight Markdown blog engine that includes instant pagination, tag and category views, and more.
- Kraken: A scalable and secure layer that provides structure and convention to Express.
- LoopBack: is a Node.js framework that allows you to quickly create dynamic end-to-end REST APIs.
- Sails: is a Node.js MVC framework for developing practical, production-ready apps.
- Hydra-Express: Hydra-Express is a lightweight library that makes it easier to build Node.js Microservices with Express.js.
- Blueprint: a solid framework for developing APIs and backend services.
- Locomotive: A powerful Node.js MVC web framework from the creators of Passport.js.
- graphql-yoga: A powerful GraphQL server that is also simple and light.
- Express Gateway: A fully featured and extensible API Gateway built on Express.
- Dinoloop: Typescript-powered Rest API Application Framework with Dependency Injection.
- Kites: A Web Application Framework Based on Templates.
- FoalTS: is an elegant and all-encompassing Node.js web framework built on TypeScript.
- NestJS: is a forward-thinking Node.js framework for developing efficient, scalable, and enterprise-grade server-side applications on top of TypeScript and JavaScript (ES6, ES7, ES8).
- Expressive Tea: is a small framework for creating modulable, clean, fast, and descriptive server-side applications using TypeScript and Express.
Using template engines with Express.js
You can use static template files in your application thanks to a template engine. The template engine replaces variables in a template file with actual values at runtime and converts the template into an HTML file that is sent to the client. This method makes it easier to create an HTML page.
Pug, Mustache, and EJS are some popular template engines that work with Express. The Express application generator’s default language is Jade, but it also supports several others.
Hands-on
In this hands-on, we will see how we can perform a basic session-based authentication in Express.js. We will start by creating a new folder on the local machine. Initializing different commands, we will create a package.json file for package installations using git bash. Post that, adding the required packages, we will run npm install to install those packages in the directory.
On successful installation, we will create a new main source file that will contain the required routes and a middleware function to check if the user is successfully logged in or not. We will start by importing the required packages into the source file. Then we will define a port number on which the server will run. Post that, we will create the jade files for a signup, login, and welcome page (that will contain the UI for those pages). Adding the forms for those UI pages, we will then create a route for loading the signup page and create a post request action for storing the users and creating a session for the newly signed up user. Post that, we will create a middleware function that will check if the user is logged in or not (if the session still exists or is destroyed).
Then, by adding a middleware in the route for loading the welcome page, we will start the server and check if the signup process and session creation process is working as expected. Then we will add the routes and the required checks for login and logout. Finally, we will test out the entire authentication process by signing up, logging in, logging out, entering invalid credentials, etc.
Required installations for the process
Create a new folder on your local machine.
Open git bash in that folder and run the command npm init
. Select the package name and the following attributes.
Finally, press enter for the final configuration.
Open the newly created folder in a code editor and you’ll notice a package.json file created.
Open that file and add a new key with the name dependencies and add the following packages with its versions in that key in an object format.
Open git bash or a normal code editor and run the command:
npm install
On success, you’ll find the package-lock.json file created in that directory.
Create a new file in the directory named index.js and open that file.
Import the following packages in the index.js file. The one’s that we just installed.
Set the views directory to look for the jade files that we will be using for the UI layout.
Then we will be using the body-parser to enclose our requests. To use a session, you can keep a secret key of your choice.
Then we’ll be defining a port number using the following variable on which our server will be running.
Now, let’s run the server and test if it’s working as expected. Run the following command:
node index.js
On success, you’ll see the following output.
Create a new variable initializing it to an empty array to store the users.
In the directory, create a new folder with the name views. This will contain the jade files for the UI layout.
Create new file signup.jade. Open that file.
Add the following content to that file. This is the signup form and the action that is to be performed on signing up.
Create a new file login.jade. Open that file.
Add the following content in that file which is the login template for the UI and the action that is to be performed.
Create a new file with the name welcomePage.jade. Open that file.
Add the following content to that file. This page will be loaded once we log in successfully.
Now, let’s create a route for signup. We can do so with the below code. On hitting the URL with /signup, it will load the signup.jade file.
app.get('/signup', function (req, res) {
res.render('signup');
});
Now, run the code with the below command.
node index.js
Once the server starts, hit the URL as shown in the image below. You will see the signup.jade file with the UI loaded.
Create a new function with the name checkLogin that will check whether the user is logged in or not.
Adding a new route with the path welcomePage. This will load the welcomePage.jade file once the login is succesful.
If there’s any error, it will navigate us back to the login page.
Use the below command to restart the server.
node index.js
Hit the URL in that browser to load the signup.jade file.
Enter a user id and password for a user and click on Submit.
On success, you will see the below page loaded on the UI.
Create a route for login to load the login.jade file (the Login UI).
Add the post method for the login request. This will check if the user id and password exist or not and will direct us to the welcome page accordingly.
Restart the server running the below command.
node index.js
Hit the following URL in a browser and you will see the Login UI loaded.
Navigate back to the code editor and add a route for logout. This will thereby destroy the session and log a user out.
Restart the server using the below command.
node index.js
Hit the URL again on signup.
Add credentials to be able to create a new user. Click on Submit.
You will be navigated to the welcome page. Now, click on Logout.
Clicking on logout will destroy the session and will log you out. Now, if you hit the URL on the welcome page, you won’t be able to view the page since you have logged out.
In the console, you’ll get to see if you have been successfully logged out or not.
Now, since we have already created a new user, we can use those credentials and log in. Navigate to the login page hitting the URL. First, we will check if entering the wrong credentials gives us the error or not.
Then, enter the valid credentials for the newly created user.
On hitting submit, you will be successfully logged in as shown in the image below. Hit the Logout button.
You will be navigated back to the login page and the session will then be destroyed.
In the console, you’ll get to see whether you have been successfully logged out or if there were any errors.
Conclusion
In this hands-on, we saw how we can perform a session-based authentication in Express.js. We started by creating a new folder on the local machine. Initializing different commands, we created a package.json file for package installations using git bash.
Post that, adding the required packages, we executed npm install to install those packages in the directory. On successful installation, we created a new main source file that consisted of the required routes and a middleware function to check if the user is successfully logged in or not.
We then imported the required packages into the source file. Then we defined a port number on which the server was running. Post that, we created the jade files for a signup, login, and welcome page (that consisted of the UI for those pages). Adding the forms for those UI pages, we then created a route for loading the signup page and created a post request action for storing the users and creating a session for the newly signed up user.
Post that, we created a middleware function that would check if the user is logged in or not (if the session still exists or is destroyed). Then, adding a middleware in the route for loading the welcome page, we started the server and checked if the signup process and session creation process were working as expected. Then we added the routes and the required checks for login and logout.
Finally, we tested out the entire authentication process by signing up, logging in, logging out, entering invalid credentials, etc. We will come up with more such use cases in our upcoming blogs.
Meanwhile …
If you are an aspiring Express.js Developer and want to explore more about the above topics, here are a few of our blogs for your reference:
- How to fetch contents of JSON files stored in Amazon S3 using Express.js and AWS SDK?
- How to perform PDF operations using HummusJS and Express?
Stay tuned to get all the updates about our upcoming blogs on the cloud and the latest technologies.
Keep Exploring -> Keep Learning -> Keep Mastering
At Workfall, we strive to provide the best tech and pay opportunities to kickass coders around the world. If you’re looking to work with global clients, build cutting-edge products and make big bucks doing so, give it a shot at workfall.com/partner today!