Plugins and Extensions
🎯 Introduction
By the end of this article, you will understand Egg's plugin system, add parameter validation with egg-validate, and extend framework objects with methods that provide a consistent response format.
🧱 What Are Plugins?
Egg itself is lightweight; many capabilities are assembled as plugins. The bodyParser and security features you have already used are built-in plugins.
A plugin is a reusable package of functionality. Developers publish packages to npm; we install and enable them to use their capabilities. The process has two steps:
- Install the plugin package with
npm install. - Enable it in
config/plugin.js.
Let's try a common use case: parameter validation.
🛠 Validating Parameters with egg-validate
After receiving a request body, an endpoint should first check that required values are present and have the correct types. Instead of writing many if statements, use declarative rules with egg-validate.
The following examples were verified with Node.js v22 LTS, egg 3.x, and egg-validate 2.0.2. Install the plugin:
npm install egg-validate
Then enable it in config/plugin.js:
module.exports = {
validate: {
enable: true,
package: 'egg-validate',
},
};
This adds a validate method to ctx. Declare validation rules in the controller:
class UserController extends Controller {
async create() {
const { ctx } = this;
// Validate ctx.request.body by default: name must be a string and age a number
ctx.validate({
name: { type: 'string', required: true },
age: { type: 'number', required: true },
});
const user = await ctx.service.user.create(ctx.request.body);
ctx.status = 201;
ctx.body = user;
}
}
Try sending a curl request without age:
curl -X POST http://127.0.0.1:7001/users \
-H 'Content-Type: application/json' \
-d '{"name":"Gang"}'
Failed validation throws a 422 error, so subsequent code does not run. To return a custom error format, catch it with try/catch:
async create() {
const { ctx } = this;
try {
ctx.validate({
name: { type: 'string', required: true },
age: { type: 'number', required: true },
});
} catch (err) {
ctx.status = 422;
ctx.body = { message: 'Missing or invalid parameters' };
return;
}
// Continue after successful validation
}
🧱 What Are Extensions?
Plugins bring in packaged functionality; extensions let you add methods to built-in framework objects yourself. Egg supports extending these common objects through files in app/extend:
| File | Extended object | Typical use |
|---|---|---|
| application.js | app | Globally shared methods or data |
| context.js | ctx | Utilities available to each request |
| helper.js | ctx.helper | Helpers for views and responses |
| request.js | ctx.request | Request-related extensions |
| response.js | ctx.response | Response-related extensions |
A commonly used extension file is helper.js. We will use it to solve a practical problem: keeping response formats consistent.
🛠 Creating a Consistent Response Format
All endpoints in a project should return a consistent format to simplify frontend handling. A common convention is:
{ "code": 0, "data": {}, "message": "ok" }
A code of 0 indicates success; a nonzero value indicates failure. Rather than repeat this structure in every endpoint, wrap it in helper methods:
module.exports = {
// Success response
success(data = null, message = 'ok') {
this.ctx.body = { code: 0, data, message };
},
// Failure response
fail(message = 'Operation failed', code = 1) {
this.ctx.body = { code, data: null, message };
},
};
Calling these helpers from a controller is straightforward:
class UserController extends Controller {
async show() {
const { ctx } = this;
const user = await ctx.service.user.findById(ctx.params.id);
if (!user) {
ctx.status = 404;
ctx.helper.fail('User not found');
return;
}
ctx.helper.success(user);
}
}
this refers to the extended object itself. Inside a helper, use this.ctx to access the context, set responses, and read configuration.🛠 Extending the Context
Let's add another useful property to ctx: a check for Ajax requests. Create app/extend/context.js:
module.exports = {
// Define a getter so callers can read ctx.isAjax as a property
get isAjax() {
return this.get('X-Requested-With') === 'XMLHttpRequest';
},
};
You can now use ctx.isAjax in any controller or service. An extension exports a plain object, which Egg merges into the corresponding framework object.
❓ Questions and Answers
Q1: How do plugins differ from middleware?
Middleware handles one step in the request chain. A plugin is a complete package that can include middleware, extensions, configuration, scheduled tasks, and more. It is a larger unit of organization.
Q2: What data does ctx.validate check?
By default, it checks ctx.request.body. Pass a second argument to validate other data, such as ctx.validate(rules, ctx.query).
Q3: Can extension methods conflict with built-in methods?
Yes. A matching name overrides the existing method and can cause subtle bugs. Choose application-specific names such as success and fail, and avoid existing properties such as body and status.
Q4: Should reusable logic go in a helper or a service?
Services encapsulate business logic involving data and rules. Helpers contain request and response utilities, such as formatting output and standardizing responses. When unsure, put business logic in services and presentation utilities in helpers.
🧪 Exercise
- Add a
page(list, total)helper that returns the paginated format{ code: 0, data: { list, total }, message: 'ok' }.
module.exports = {
// Keep the existing success and fail implementations
page(list, total) {
// Write your code here
},
};
- Add validation to
createrequiringnameto contain between 2 and 10 characters. Hint: rules supportminandmax.
ctx.validate({
// Write your code here
});
🎉 You now know how to use plugins and extensions! Next, we will combine everything you have learned to build a complete RESTful user management API.
Configuration and Middleware
Configure Egg.js for different environments, write and register custom middleware, and understand its built-in security features.
RESTful API Practice
Combine routes, controllers, services, validation, and a consistent response format to build a complete RESTful user management API.
