DEV Community

Cover image for Building a Simple Blog Site with Express, EJS, and Middleware: My Learning Journey 🚀
Arkadipta kundu
Arkadipta kundu

Posted on

Building a Simple Blog Site with Express, EJS, and Middleware: My Learning Journey 🚀

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! 🚀

Top comments (0)