Understanding Microservices Architecture: A Hands-On Blog with Authentication
Hey there, fellow developers! 🚀 I'm thrilled to take you on an exciting journey into the world of microservices architecture. But hold on, we won't bore you with theory and jargon. Instead, we'll dive right into the deep end with a real example - building a blog with user authentication.
Imagine having a blog that's not just any blog, but a cutting-edge, microservices-powered blog. If you've ever been curious about what the hype around microservices is all about, or if you've been itching to learn how to break down your monolithic app into smaller, more manageable pieces, this is the place to be.
Get ready to go from "I have no idea how this works" to "Hey, I can actually build a microservices app!" Join me as we explore the ins and outs of microservices architecture in a fun, friendly, and hands-on way. So, let's strap in, grab your favorite beverage, and let's begin the adventure of understanding microservices by building our very own 'Blog with Authentication' masterpiece.
We'll have two microservices: one for managing user authentication (Auth Service) and another for handling blog posts (Blog Service). We'll use a lightweight framework like Express.js for simplicity.
Setting up the project structure:
Create a folder for your project and two subfolders for each microservice: auth-service and blog-service.
mkdir blog-app-microservices
cd blog-app-microservices
mkdir auth-service
mkdir blog-service
Setting up the Auth Service:
In the auth-service folder, you'll need to set up user authentication. We'll use JWT for simplicity.
auth-service/index.js:
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = 'your-secret-key';
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Perform authentication (replace with your authentication logic)
if (username === 'user' && password === 'password') {
const token = jwt.sign({ username }, secretKey);
res.json({ token });
} else {
res.status(401).json({ message: 'Authentication failed' });
}
});
app.listen(3001, () => {
console.log('Auth Service is running on port 3001');
});
Setting up the Blog Service:
In the blog-service folder, you can create endpoints to manage blog posts.
blog-service/index.js
const express = require('express');
const app = express();
app.use(express.json());
// Sample in-memory database for blog posts
const blogPosts = [];
app.get('/posts', (req, res) => {
res.json(blogPosts);
});
app.post('/posts', (req, res) => {
const { title, content } = req.body;
const post = { title, content };
blogPosts.push(post);
res.status(201).json(post);
});
app.listen(3002, () => {
console.log('Blog Service is running on port 3002');
});
Connecting Auth and Blog Services:
To connect these services, you can use API calls and JWT authentication. In the Blog Service, you can verify JWT tokens before allowing access to certain routes. This ensures that only authenticated users can create or view blog posts. Here's a simplified example:
blog-service/index.js:
app.post('/posts', (req, res) => {
const { title, content, token } = req.body;
// Verify the token
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'Unauthorized' });
}
const post = { title, content, author: decoded.username };
blogPosts.push(post);
res.status(201).json(post);
});
});
Running the Microservices:
You can start both services in separate terminals:
cd auth-service
node index.js
cd blog-service
node index.js
Interacting with the Services:
You can interact with the services using HTTP requests. For example, you can use tools like curl or Postman to test the API endpoints.
- Register and login users in the Auth Service to obtain JWT tokens.
- Use these tokens to access the protected routes in the Blog Service.
This is a very simplified example of a microservices architecture for a blog app with authentication in Node.js. In a real-world scenario, you would need to add more features, error handling, and security measures. Additionally, you might want to consider using a reverse proxy, service discovery, and containerization for deployment