Create Express Server with ejs templating Engine
Tags: javascript, express, ejs, api
Published: 2021-08-01 13:26:54

In today's simple application we will learn to create a simple server using the express node js application framework. In this app, we will also learn how to serve html and style your apps with plain javascript using ejs templating engine. There is a variety of javascript templating engines available on the web however I personally prefer to use ejs because of it's simpler syntax and easy understandability but you can use whichever you like the most.
Detailed documentation about ejs can be found [here](https://ejs.co/)

So, let's begin our app by creating an empty main.js file and installing the required dependencies, but first we need to create the package.json file using the command below:
```javascript
npm init -y
``` 
Next, install express and ejs into your app:
```javascript
npm install express ejs
```

Now, we will write the express boiler plate code in our main.js file in order to create our server:
```javascript
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}`)
})
```
The above code will make the server run at port:3000 and send a 'Hello World' message on home route which is denoted by '/'
In this manner, we can create as many routes as we want for our application. In this demo application, we will only create a home route and an About route in the following manner:

```javascript
const express = require("express");
const app = express();
const path = require("path");

app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => {
res.send("Welcome to the Home page")
});

app.get("/about", () => {
res.send("Welcome to the About Us page")
})

app.listen(3000, (req, res) => {
  console.log("server is running");
});

```
Now, let's move to creating a pets object in the home route which we want to render on the home page of our app, but we don't just want to show a javascript object on the home page, instead we want a beautiful application to be displayed and to achieve this purpose we will create a "views" folder in our project directory and create a home.ejs file where we can write the desired html for our pets object from the main.js file to be displayed on home page of our app.
First, I will update the home route on main.js file to render the pets object:
```javascript
app.get("/", (req, res) => {
  res.render("home", {
    pets: [
      {
        name: "Meowsalot",
        description:
        "From the tiny Rusty-spotted cat of Sri Lanka to the massive Siberian tiger of the Russian Far East, there are 40 species of wild cats in the world, and each of them is as beautiful as it is unique.Most of us know lions, tigers, jaguars and leopards, but what are all the other types of wild cats out there? If you consider yourself a cat person or simply curious about these charismatic animals, read on to meet the family. They are the most loved and cute species found on the land.",
        species: "cat",
        image: "https://540934-1733880-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2020/05/Eurasian-lynx-AdobeStock_246336076-1024x683.jpg"
      },
      { name: "Barksalot", 
      description: "Dogs are the most variable mammal on earth with around 450 globally recognized dog breeds.[10] In the Victorian era, directed human selection developed the modern dog breeds, which resulted in a vast range of phenotypes. Most breeds were derived from small numbers of founders within the last 200 years, and since then dogs have undergone rapid phenotypic change and were formed into today's modern breeds due to artificial selection imposed by humans.",
      species: "dog" ,
    image: "https://upload.wikimedia.org/wikipedia/commons/e/e0/Dog_niemiecki_%C5%BC%C3%B3%C5%82ty_LM980.jpg"},
    ],
  });
});
```

Next, I will set our app to use the ejs views engine:
```javascript
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
```
Here, I will also create a public folder in the root of our app, and create a style.css file there to include the necessary styling for our app. Also, don't forget to set the app to use the assets from public folder as follows:
```javascript
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
```
Now, let's move to the home.ejs file where we will call our pets object and render it in the form of a mix of html and javascript:
```javascript
<body>
<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about">About Us</a></li>
    </ul>
</nav>

    <h1>Welcome to the Home Page</h1>
<div class="container">
  
        <% pets.forEach(pet => { %>
            <li>
                <h2><%= pet.name %> </h2>
                <p>(<%= pet.species %>)</p>
            <img src= "<%= pet.image %>"/>
            <p class="text"><%=pet.description %></p>
            </li>
                <% }) %>
    
   
</div>
   
</body>
```
Remember, to start using ejs, you have to use the <% symbol and also end it by %> and in the middle you can use plain old html. On all those instances where you're making use of any variable or evaluating something you will also include an = sign like this <%=
I have linked both the home.ejs and about.ejs to our style.css file present in the public folder to do the necessary styling required for our application. You can find all the styles [here](https://github.com/NasreenKhalid/Express_ejs_Server_App/blob/master/public/style.css)
Below is the finished look of the application:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sl8xpjcfsaunm5u59wv4.png)

You can navigate to Home page and About Us page from the navbar present at the top.
Complete code of the application can be found [here](https://github.com/NasreenKhalid/Express_ejs_Server_App)

That's all folks, hope you find this app relevant and useful.
Happy coding...