Building a Simple Blog Site with Express, EJS, and Middleware: My Learning Journey ๐Ÿš€

Arkadipta kundu - Sep 15 - - Dev Community

To wrap up everything Iโ€™ve learned about Express.js, EJS, and middleware, I decided to build a mini project: a blog site! This isnโ€™t your typical blog โ€” thereโ€™s no database involved (yet!), so posts disappear once the server is restarted. But it was a fantastic way to apply what Iโ€™ve been learning, and I picked up a few new things along the way. ๐Ÿ™Œ

Project Overview

The goal of this project was to create a blog web application using Node.js, Express.js, and EJS. This app allows users to create, view, update, and delete blog posts. Since I didnโ€™t focus on styling this time (so please donโ€™t judge me ๐Ÿ˜…), my main effort went into making the functionality work.

Hereโ€™s a quick breakdown of the features:

  1. Post Creation: Users can create new blog posts.
  2. Post Viewing: The home page displays all created posts.
  3. Post Update/Delete: Users can edit or delete any existing post.

How I Built the Blog Project

Letโ€™s dive into the process of building this project:

1. Project Initialization

I started by setting up a basic Node.js project:

  • Initialized the project with npm init.
  • Installed the necessary dependencies: express, ejs, and body-parser.

2. Project Structure

Hereโ€™s the project structure I used:

my-blog
โ”œโ”€โ”€ public
โ”‚   โ””โ”€โ”€ styles.css  # (no fancy styles here, just plain functionality)
โ”œโ”€โ”€ views
โ”‚   โ”œโ”€โ”€ create.ejs  # Form for creating new posts
โ”‚   โ””โ”€โ”€ index.ejs   # Displays all posts
โ”œโ”€โ”€ app.js          # Main application file
โ”œโ”€โ”€ package.json
Enter fullscreen mode Exit fullscreen mode

3. Server Setup

In app.js, I set up the Express server and configured EJS as the templating engine:

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

// Middleware for parsing form data
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(path.join(path.dirname(''), 'public')));

// Set EJS as the templating engine
app.set('view engine', 'ejs');
app.set('views', path.join(path.dirname(''), 'views'));
Enter fullscreen mode Exit fullscreen mode

4. Creating Routes

Next, I set up the following routes to handle the main functionality:

  • Home Route (/): Displays all blog posts.
  • Create Route (/create): Renders the form for adding a new blog post.
  • Delete Route (/delete): Removes a specific blog post.
  • Update Route (/update): Allows users to update a specific post.

Hereโ€™s how the routes work:

let posts = [];

// Display all posts
app.get('/', (req, res) => {
    res.render('index', { posts });
});

// Show form to create a post
app.get('/create', (req, res) => {
    res.render('create');
});

// Add a new post
app.post('/create', (req, res) => {
    const { title, content } = req.body;
    posts.push({ title, content });
    res.redirect('/');
});

// Delete a post
app.post('/delete', (req, res) => {
    const { index } = req.body;
    posts.splice(index, 1);  // Removes the post at the specified index
    res.redirect('/');
});

// Update an existing post
app.post('/update', (req, res) => {
    const { index, title, content } = req.body;
    posts[index] = { title, content };  // Updates the post
    res.redirect('/');
});
Enter fullscreen mode Exit fullscreen mode

What I Learned from This Project

  1. Setting EJS as the Templating Engine: I figured out how to configure Express to use EJS for all my templates:
   app.set('view engine', 'ejs');
   app.set('views', path.join(path.dirname(''), 'views'));
Enter fullscreen mode Exit fullscreen mode

This tells Express to automatically look for .ejs files inside the views folder whenever I render a template.

  1. Using splice() for Array Manipulation: The splice() function became my best friend for updating and deleting posts from the posts array. Hereโ€™s how I used it to remove a post at a specific index:
   posts.splice(index, 1);
Enter fullscreen mode Exit fullscreen mode

Itโ€™s super handy when working with arrays in JavaScript, especially when you need to remove or replace elements.


Challenges and Fun Moments

  • Styling? Whatโ€™s That?

    • As I mentioned earlier, I put zero effort into the styling. The focus here was on making everything work! So, if you look at the code, you wonโ€™t see a beautifully styled site. But functionality first, right? ๐Ÿ˜…
  • Figuring Out Route Logic:

    • At first, I struggled a bit with setting up the update and delete routes. But after a few tries , I got it working .
  • Form Parsing:

    • Setting up middleware to handle form submissions was something new for me. Using body-parser made handling form data a breeze. It parses both URL-encoded and JSON data.

The Final Result

The blog app is a simple yet functional tool that allows users to:

  • Create new blog posts,
  • View all posts on the home page,
  • Edit or delete posts as needed.

Since thereโ€™s no database, all the posts are stored in-memory, which means they disappear once the server is restarted. Itโ€™s a good starting point, and later, Iโ€™ll add a database to make the posts persist!

You can check out the full code here: GitHub - Blog Project


Wrapping Up

This project helped me solidify my understanding of Express.js, EJS, and middleware. Itโ€™s not a fancy project, but it was a fun way to put my learnings into practice and create something functional.

Here are some key takeaways:

  • Setting up EJS as a templating engine is easy and makes dynamic content generation straightforward.
  • Using routes to handle create, update, and delete operations was a great way to learn about HTTP methods.
  • splice() is a handy function for manipulating arrays when working with posts or data.

If you're also learning Express, EJS, or middleware, I highly recommend trying out small projects like this. Youโ€™ll learn a ton by building something practical!

Whatโ€™s Next?

  • Iโ€™ll probably add a database like MongoDB next, so the blog posts persist between sessions. But for now, Iโ€™m happy with what Iโ€™ve built.

If you have any questions or thoughts, feel free to drop a comment below! Letโ€™s keep learning and building together! ๐Ÿš€

. . . . . . . .
Terabox Video Player