Introduction to Egg.js and Quick Start
🎯 Introduction
By the end of this article, you will understand what Egg.js is and how it differs from Express and Koa. You will also create a project with the official scaffolding tool, start the server, and build your first endpoint—a first step toward enterprise Node.js development.
🧱 What Is Egg.js?
Egg.js is a Node.js web framework built on Koa, open sourced and maintained by Alibaba's team and commonly used for enterprise applications.
Its guiding principle is convention over configuration. The framework defines where files belong, how they are named, and which objects expose their code. Put your code in the expected locations, and Egg loads and connects it automatically.
ctx you use in Egg is Koa's ctx.✨ Why Choose Egg.js?
Express and Koa offer considerable flexibility: a single file can start a server. That freedom also means ten developers can produce ten directory structures, making team conventions harder to maintain.
Egg.js takes a different approach by turning common engineering practices into conventions:
- Consistent directory structure: Routes, controllers, business logic, and middleware each have a designated location, so any Egg project feels familiar.
- Built-in capabilities: Security checks, request body parsing, logging, and other common features work out of the box, without assembling your own libraries.
- Easier teamwork: Shared conventions keep code consistent and help new team members get started quickly.
Think of Express and Koa as an empty plot where you can build anything. Egg is a furnished apartment: the layout is ready, so you can move in and start working.
🛠 Scaffold a Project
Egg provides an official scaffolding tool that generates a standard project with one command. This article and course were written and verified with Node.js v22 LTS and egg 3.x (3.34.0 at the time of writing).
Open a terminal, navigate to the directory where you want to create the project, and run:
npm init egg --type=simple
The tool asks for the template type (simple), project name, description, author, and other details. While learning, you can press Enter to accept the defaults, then wait for the dependencies to finish installing.
Once setup finishes, enter the project directory and start the server:
cd egg-example
npm run dev
The message egg started on http://127.0.0.1:7001 confirms that the server is running. Open http://127.0.0.1:7001 in your browser to see hi, egg.
npm run dev starts development mode, which restarts the server automatically when you change code. You do not need to stop and restart it manually. The default port is 7001.🧱 Explore the Directory Structure
Open the generated project and look at its main files and directories:
egg-example
├── app
│ ├── router.js # Routes: map URLs to handlers
│ ├── controller # Controllers: receive requests and send responses
│ ├── service # Business logic: process application data and operations
│ ├── middleware # Custom middleware
│ └── extend # Framework extensions: add methods to built-in objects
├── config
│ ├── config.default.js # Default configuration
│ └── plugin.js # Plugin configuration
└── package.json
This is convention over configuration in practice. Place files in the expected locations and export them as required; Egg loads them at startup without manual require calls to assemble the application.
🛠 Your First Endpoint
The scaffold includes an example. Open app/controller/home.js:
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
}
module.exports = HomeController;
Now look at the route in app/router.js:
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
};
Together, these files tell Egg to handle GET / with the index method in app/controller/home.js and return content through ctx.body.
Let's turn it into a JSON endpoint:
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = {
message: 'Hello, Egg.js',
};
}
}
module.exports = HomeController;
Save the file and refresh the browser to see the JSON response. When you assign an object to ctx.body, Egg serializes it as JSON automatically, including the appropriate Content-Type.
require and module.exports), following the framework's conventions. Earlier courses used ESM; this difference is expected. Follow the official conventions when writing Egg code.❓ Questions and Answers
Q1: How are Egg.js and Koa related?
Egg is built on Koa. Think of it as Koa with established conventions and additional capabilities. Koa's ctx, middleware, and onion model all apply in Egg.
Q2: Is Egg worth learning if I already know Express or Koa?
Express and Koa work well for small projects. In medium and large projects with multiple developers, Egg's shared conventions reduce coordination costs. Egg is also a common requirement in enterprise job listings.
Q3: Why does Egg use CommonJS instead of ESM?
This is a longstanding convention in Egg, whose automatic loading mechanism is based on CommonJS. Follow the official examples with require and module.exports; it does not affect what you learn.
Q4: Do I need to restart the server after changing code?
Development mode, started with npm run dev, watches files and restarts automatically. Save your changes and refresh the browser.
🧪 Exercise
Add an info method to home.js that returns your name and the date you are studying. Register it as GET /info in router.js.
class HomeController extends Controller {
async index() {
// Keep the existing code unchanged
}
async info() {
const { ctx } = this;
// Write your code here
}
}
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
// Write your code here
};
🎉 You have your first Egg.js project running! Next, we will explore routes and controllers, including how to read request parameters and return consistent responses.
