Building a Node.js Middle Tier for Web Architecture: Concepts, Benefits, and Koa Implementation
This article explains the role of a middle tier in web systems, describes middleware concepts, outlines the advantages of using Node.js as a middle layer, and provides a step‑by‑step Koa‑based implementation with code examples and deployment considerations.
Introduction
Since its release in 2009, Node.js has been adopted by many large companies (Alibaba, Tencent, Baidu, JD, etc.) as a middle‑tier solution. This article introduces the knowledge needed to build a web‑architecture middle tier based on Node.js.
1. Middle Tier and Middleware
1.1 What is a Middle Tier?
The middle tier (or application server layer) sits between the web client and the database, typically hosting the web server and instantiating business objects. It encapsulates business rules that can be changed frequently and operates independently of the core application logic.
1.1.1 Node.js as a Middle Tier Pattern
When a client requests a website, the request first reaches the Node.js server, which forwards it to backend services, obtains data, renders a view with a template engine, and returns the final HTML page to the client.
1.2 Load Balancer – Nginx
Nginx is a high‑performance web server and reverse proxy that is commonly used as a software load balancer. It distributes traffic across multiple servers, reduces pressure on any single server, and provides failover capabilities.
2. What is Middleware?
2.1 Middleware Concept
Middleware is independent system software that enables distributed applications to share resources across different technologies. In Node.js, middleware encapsulates the handling of HTTP request details (logging, IP filtering, parsing, authentication, etc.) so developers can focus on business logic.
Express is a minimalist framework built from routing and middleware; an Express app works by invoking a chain of middleware functions.
2.2 Core Implementation of Middleware
A basic middleware has the following signature:
const middleware = (req, res, next) => {
// TODO
next()
}2. Significance of the Middle Tier
Node.js uses an event‑driven, non‑blocking I/O model, making it lightweight and efficient for data‑intensive real‑time applications. Adding a middle tier (often called BBF – Backend‑for‑Frontend) separates the view layer from the traditional backend, allowing the frontend to control rendering and interface logic.
2.1 What the Node.js Middle Tier Can Do
Proxy: solve cross‑origin issues in development and forward requests in production.
Cache: handle cache close to the frontend.
Rate limiting: apply limits per route or interface.
Logging: simplify problem location across client and server.
Monitoring: suitable for high‑concurrency request handling.
Authentication: implement single‑responsibility auth checks.
Routing: manage page routing logic.
Server‑side rendering: support SSR, template output, pre‑rendering, etc.
2.2 Benefits of the Node.js Middle Tier
Customizable interfaces improve frontend capability and speed up iteration.
Frontend engineers use JavaScript, reducing learning cost.
Full‑stack skill growth for frontend developers.
2.3 Advantages of the Middle Tier
Functional separation reduces load on individual components.
Reusable validation and logic across systems and terminals.
Single data validation point avoids duplicate checks.
Front‑end focuses on rendering, improving performance and user experience.
3. Implementation of the Middle Tier
Below is a simple Koa‑based middle tier implementation.
3.1 Backend API Example
The backend provides an endpoint that returns different status codes based on username/password.
3.2 Front‑end Page Setup
The front‑end uses EJS for server‑side rendering. Main files: app.js , admin.js , admin.ejs .
3.2.1 Project Structure
3.2.2 app.js
const Koa = require('koa');
// 路由
const Router = require('koa-router');
// 模板引擎
const ejs = require('koa-ejs');
// 数据解析
const body = require('koa-bodyparser');
// 静态文件
const static = require('koa-static');
const path = require('path');
const app = new Koa();
ejs(app,{
root:path.resolve(__dirname,"template"),
layout:false,
viewExt:"ejs",
cache:false,
debug:false
});
const router = new Router();
app.use(body());
router.get("/",ctx => { ctx.body = '主页'; })
router.use("/admin", require("./router/admin"));
app.use(static('./static'));
app.use(router.routes());
app.listen(3000);3.2.3 admin.ejs (login page)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>我是管理页面</title>
<script src="/js/jquery.min.js"></script>
</head>
<body>
<p>用户:<input type="text"></p>
<p>密码:<input type="password"></p>
<button>提交</button>
<script>
$(function(){
$('button').click(function(){
var username = $(':text').val();
var password = $(':password').val();
$.ajax({
url:'/admin/login',
method:'post',
data:{ username, password },
success(data){ console.log(data); }
})
})
})
</script>
</body>
</html>3.3 admin.js (router logic)
const Router = require('koa-router');
const axios = require('axios');
const querystring = require('querystring');
const router = new Router();
router.get('/', async ctx => { await ctx.render('admin/admin') })
router.post('/login', async ctx => {
const { username, password } = ctx.request.body;
const { data } = await axios({
url: 'http://localhost/login/check.php',
method: 'post',
data: { username, password },
transformRequest: [ data => querystring.stringify(data) ]
})
if (data.code !== 1) {
return ctx.body = { code: 401, message: '未经授权' };
}
ctx.body = { code: 200, message: '校验成功' };
});
module.exports = router.routes();The front‑end wraps the backend response, presenting user‑friendly messages while keeping the backend focused on core logic.
4. Conclusion
Middle tiers are increasingly adopted by large enterprises, allowing front‑end teams to handle caching, load balancing, and even some backend responsibilities. While Node.js is a popular choice due to its JavaScript ecosystem, other languages like PHP can also serve as middle tiers.
By introducing a middle layer, front‑end developers gain the ability to create custom APIs, reduce dependency bottlenecks, and accelerate product development.
TAL Education Technology
TAL Education is a technology-driven education company committed to the mission of 'making education better through love and technology'. The TAL technology team has always been dedicated to educational technology research and innovation. This is the external platform of the TAL technology team, sharing weekly curated technical articles and recruitment information.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.