Creating a personal blog is a great way to share your thoughts, ideas, and projects with the world. In this tutorial, we'll walk through building and deploying a blog application using Node.js and Express.
Prerequisites
Before starting, ensure you have the following:
- Node.js installed on your machine
- Basic understanding of JavaScript
- A code editor (like VS Code)
Step 1: Set Up Your Project
Open your terminal and create a new directory for your blog. Navigate to it and initialize a new Node.js project:
mkdir my-personal-blog
cd my-personal-blog
npm init -y
This creates a package.json file, where all your project dependencies will reside.
Step 2: Install Necessary Packages
Next, you’ll need to install Express and some other helpful packages:
npm install express body-parser ejs mongoose dotenv
- express handles your server logic.
- body-parser helps parse incoming request bodies.
- ejs is a templating engine for rendering HTML.
- mongoose interacts with MongoDB for data management.
- dotenv manages environment variables.
Step 3: Set Up Your Server
Create a new file called server.js and set up a basic Express server:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 5000;
mongoose.connect('mongodb://localhost/my-blog', { useNewUrlParser: true, useUnifiedTopology: true });
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.send('Welcome to My Personal Blog');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This simple setup initiates an Express server that listens for requests.
Step 4: Define Your Database Schema
Create a folder named models and add a file named Post.js for your blog posts schema:
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: String,
content: String,
createdAt: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Post', postSchema);
Step 5: Create Blog Routes
Add routes to create and display posts. In your server.js, include the following:
const Post = require('./models/Post');
app.get('/posts', async (req, res) => {
const posts = await Post.find();
res.render('posts', { posts });
});
app.post('/posts', async (req, res) => {
const newPost = new Post({ title: req.body.title, content: req.body.content });
await newPost.save();
res.redirect('/posts');
});
Step 6: Create Views
Create a views folder, and within it create posts.ejs which renders your posts:
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>My Blog Posts</h1>
<form action="/posts" method="POST">
<input type="text" name="title" placeholder="Title" required>
<textarea name="content" placeholder="Content" required></textarea>
<button type="submit">Add Post</button>
</form>
<ul>
<% posts.forEach(post => { %>
<li><h2><%= post.title %></h2><p><%= post.content %></p></li>
<% }) %>
</ul>
</body>
</html>
Step 7: Test Your Application
Start your server:
node server.js
Open your browser and navigate to http://localhost:5000. You should see your personal blog!
Step 8: Deploy Your Blog
Now that your blog is up and running, consider deploying it using platforms like Heroku or Vercel. Follow their guides on how to deploy Node.js applications.
Conclusion
Congratulations! You’ve built and deployed a personal blog using Node.js and Express. This project sets a solid foundation for exploring more advanced features like user authentication, comments, or even media uploads in the future. Happy coding!