Configuration and Middleware
🎯 Introduction
By the end of this article, you will understand config.default.js, write and register custom middleware that logs request duration, and explain Egg's built-in CSRF checks and how to handle them during API debugging.
🧱 Configuring config.default.js
Egg configuration lives in the config directory, starting with config.default.js. Open the generated file:
module.exports = appInfo => {
const config = {};
// Cookie signing key; use a unique key for each project
config.keys = appInfo.name + '_my_secret_key';
// Middleware to register; we will use this later
config.middleware = [];
// Custom configuration available throughout the application
config.myAppName = 'egg-demo';
return config;
};
The file exports a function that receives application information as appInfo and returns a configuration object. Read custom options through this.config or ctx.app.config:
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = this.config.myAppName;
}
}
module.exports = HomeController;
🧱 Environment-Specific Configuration
Development and production often need different settings, such as ports and log levels. Egg lets environment-specific files override config.default.js:
config
├── config.default.js # Default configuration shared across environments
└── config.prod.js # Production overrides
module.exports = () => {
const config = {};
// Settings that apply only in production
config.logger = {
level: 'WARN',
};
return config;
};
At startup, Egg merges configuration for the current environment. Environment-specific values override matching defaults. For now, understanding this mechanism is enough; editing config.default.js is sufficient for everyday development.
🧱 What Is Middleware?
Middleware is a step in the request processing chain. It runs shared logic before or after a controller, such as logging, measuring duration, or handling errors consistently.
The onion model from the Koa course applies here: a request passes through middleware layers to reach the controller, then the response travels back through those layers in reverse. Egg middleware follows Koa's approach, with a conventional directory location.
🛠 Writing Custom Middleware
By convention, custom middleware goes in app/middleware. Let's create response_time.js to measure request duration:
// options contains configuration; app is the application instance
module.exports = (options, app) => {
return async function responseTime(ctx, next) {
const start = Date.now();
// Code before await next() runs on the way in
await next();
// Code after await next() runs on the way out
const cost = Date.now() - start;
if (cost > options.limit) {
console.log(`Slow request: ${ctx.method} ${ctx.url} took ${cost}ms`);
}
};
};
The structure has two functions: the outer function receives configuration and the application instance, and the inner function is standard middleware. Use await next() as the boundary between incoming request logic and outgoing response logic.
🛠 Registering Middleware and Configuring options
Creating the file is not enough; register it in config.default.js:
module.exports = appInfo => {
const config = {};
config.keys = appInfo.name + '_my_secret_key';
// Register middleware: response_time.js maps to responseTime
config.middleware = ['responseTime'];
// Options use the middleware name as their key and are passed as options
config.responseTime = {
limit: 10,
};
return config;
};
Save the file and visit a few endpoints. The terminal logs requests taking longer than 10ms:
Slow request: GET /users took 25ms
response_time.js) to camelCase names (responseTime). Use the camelCase name for both registration and configuration.⚠️ Built-in Security and CSRF Checks
Egg includes the egg-security plugin with several protections enabled by default. CSRF validation directly affects how we test endpoints.
By default, requests such as POST, PUT, and DELETE need a CSRF token to prevent cross-site request forgery. Sending a POST request directly with curl or an API client may therefore produce 403 missing csrf token.
For local learning and debugging, you can temporarily disable this check:
config.security = {
csrf: {
enable: false,
},
};
❓ Questions and Answers
Q1: Why does config.default.js export a function?
A function receives appInfo, including the application name and environment, so configuration can use dynamic values—for example, building config.keys from the application name. Exporting an object is also supported, but a function is more flexible.
Q2: In what order does middleware run?
Middleware runs in the order of config.middleware: earlier entries run first on the way in and last on the way out, following the onion model. Built-in middleware such as bodyParser runs before custom middleware.
Q3: How can middleware apply only to certain paths?
Add match or ignore to its options. For example, config.responseTime = { match: '/api', limit: 10 } applies it only to paths starting with /api.
Q4: What other security defaults remain after disabling CSRF checks?
Protections include XSS filtering and security response headers. These provide built-in safeguards; keep their defaults while learning rather than disabling them casually.
🧪 Exercise
Write and register request_log middleware that logs one line after each request in the format GET /users -> 200 (method, path, and status code).
module.exports = (options, app) => {
return async function requestLog(ctx, next) {
// Write your code here
};
};
// Register the requestLog middleware here
🎉 You now know how to configure Egg and use middleware! Next, we will add parameter validation with a plugin and create a consistent response format with extensions.
