配置项
本页详细列出 VextJS 的所有配置字段、类型、默认值及使用说明。
配置加载机制
VextJS 使用三层配置合并策略,按优先级从低到高:
DEFAULT_CONFIG(框架内置默认值)
↓ 深度合并
src/config/default.ts(项目默认配置)
↓ 深度合并
src/config/${NODE_ENV}.ts(环境配置,如 production.ts)
合并后的配置通过 Object.freeze() 深度冻结,运行时不可修改。
配置文件示例
// src/config/default.ts
export default {
port: 3000,
adapter: 'native',
cors: {
enabled: true,
origins: ['http://localhost:3000'],
},
logger: {
level: 'debug',
},
};
// src/config/production.ts
export default {
port: 8080,
cors: {
origins: ['https://api.example.com'],
},
logger: {
level: 'warn',
},
response: {
hideInternalErrors: true,
},
};
完整配置参考
VextConfig
adapter
底层 HTTP 适配器,支持三种传参方式:
// 方式一:字符串标识(内置 adapter)
export default {
adapter: 'native', // 'native' | 'hono' | 'fastify' | 'express' | 'koa'
};
// 方式二:工厂函数(传入自定义选项)
import { fastifyAdapter } from 'vextjs/adapters/fastify';
export default {
adapter: fastifyAdapter({ bodyLimit: 5 * 1024 * 1024 }),
};
// 方式三:自定义 adapter 实例(实现 VextAdapter 接口)
export default {
adapter: myCustomAdapter,
};
trustProxy
当设置为 true 时:
req.ip 从 X-Forwarded-For 请求头读取第一个 IP
req.protocol 从 X-Forwarded-Proto 请求头读取
部署在 Nginx / 云负载均衡器之后时需开启此选项。
middlewares
路由级中间件白名单声明。只有在此处声明的中间件才能在路由 options.middlewares 中引用。
export default {
middlewares: [
{ name: 'auth' },
{ name: 'admin', options: { role: 'admin' } },
{ name: 'cache', options: { ttl: 60 } },
],
};
Tip
全局中间件(如 CORS、body-parser)由框架自动注册,无需在此声明。此处只声明路由级可选中间件。
VextCorsConfig
跨域资源共享配置。
export default {
cors: {
enabled: true,
origins: ['https://app.example.com', 'https://admin.example.com'],
credentials: true,
maxAge: 86400,
},
};
Warning
origins: ['*'] 与 credentials: true 不能同时使用。需要携带凭证时必须指定具体域名。
全局速率限制配置,基于 flex-rate-limit 实现。
export default {
rateLimit: {
max: 200,
window: 120,
// 按用户 ID 限流(需要 auth 中间件先解析用户)
keyBy: (req) => req.user?.id ?? req.ip,
},
};
keyBy 选项
Tip
路由级可通过 options.override.rateLimit 覆盖全局配置,或设为 false 禁用限流。
VextRequestIdConfig
请求 ID 追踪配置,用于日志关联和分布式链路追踪。
requestId vs traceId
requestId 是 vext 内置的请求唯一标识,traceId 通常指 APM 链路追踪系统(如 OpenTelemetry / Jaeger)生成的追踪 ID。两者有不同的使用场景:
模式一:requestId 充当 traceId(简单场景)
将 requestId 的请求头名改为 x-trace-id,使其与链路追踪头统一,适合不依赖外部 APM 的系统:
import { nanoid } from 'nanoid';
export default {
requestId: {
header: 'x-trace-id', // 从 x-trace-id 读取(网关注入)
responseHeader: 'x-trace-id', // 写回响应头
generate: () => nanoid(), // 可替换为更短的 ID 生成器
},
};
模式二:requestId + APM traceId 并存(企业级场景)
保留 requestId(日志关联),同时通过 config.fetch.propagateHeaders 透传 APM 的 traceparent 头,适合接入 OpenTelemetry / Jaeger 等系统:
export default {
// requestId 保留默认配置(用于日志关联)
requestId: {
header: 'x-request-id',
responseHeader: 'x-request-id',
},
// APM 追踪头通过 propagateHeaders 自动透传到下游服务
fetch: {
propagateHeaders: ['traceparent', 'tracestate'],
},
};
:::tip 选择建议
- 内部系统、简单追踪 → 模式一(改 header 名为
x-trace-id)
- 接入 OpenTelemetry / Jaeger / Datadog → 模式二(保留 requestId,配置 propagateHeaders)
- 详见 请求上下文 → 与分布式追踪的关系
:::
也可通过插件动态替换生成器:
app.setRequestIdGenerator(() => myCustomId());
VextLoggerConfig
结构化日志配置,基于 pino 实现。
export default {
logger: {
level: 'debug',
pretty: true, // 开发环境美化输出
// prettySingleLine: true, // 默认值,额外字段压缩到消息同一行
// prettySingleLine: false, // 恢复多行展开格式
// prettyIgnore: 'pid,hostname,requestId', // 默认值,隐藏 requestId
// prettyIgnore: 'pid,hostname', // 如需在 pretty 模式下显示 requestId
},
};
日志级别优先级(从高到低):
fatal > error > warn > info > debug > trace
设置某个级别后,只输出该级别及更高级别的日志。设为 'silent' 完全静默。
VextShutdownConfig
优雅关闭配置。
收到 SIGTERM / SIGINT 信号后,框架会:
- 停止接受新请求
- 等待飞行中请求完成(不超过
timeout 秒)
- 按 LIFO 顺序执行所有
onClose 钩子
- 退出进程
export default {
shutdown: {
timeout: 30, // 容器环境建议 30 秒
},
};
VextResponseConfig
响应格式配置。
出口包装
启用 wrap: true 时,res.json(data) 自动包装:
{
"code": 0,
"data": { "id": 1, "name": "Alice" },
"requestId": "550e8400-e29b-41d4-a716-446655440000"
}
错误响应格式:
{
"code": 10001,
"message": "用户不存在",
"requestId": "550e8400-e29b-41d4-a716-446655440000"
}
禁用 wrap: false 时,res.json(data) 直接发送原始 data。
隐藏内部错误
hideInternalErrors: true 时,500 错误不暴露 stack trace:
// hideInternalErrors: true
{ "code": -1, "message": "Internal Server Error" }
// hideInternalErrors: false(仅开发环境使用)
{ "code": -1, "message": "Cannot read properties of undefined (reading 'id')", "stack": "..." }
VextBodyParserConfig
请求体解析配置。
export default {
bodyParser: {
maxBodySize: '5mb', // 支持 'kb', 'mb', 'gb' 单位
},
};
禁用后 req.body 始终为 undefined,适用于纯 GET 服务或自定义 body 解析场景。
maxBodySize 支持的格式:
VextAccessLogConfig
访问日志配置,基于洋葱模型 after-middleware 实现。
export default {
accessLog: {
enabled: true,
level: 'info',
skipPaths: ['/health', '/readiness', '/metrics'],
},
};
访问日志输出示例:
POST /api/users 201 12ms req-abc-123 192.168.1.1
记录字段包括:HTTP 方法、路径、状态码、响应时间(ms)、请求 ID、客户端 IP。
VextOpenAPIConfig
OpenAPI 文档自动生成配置。
export default {
openapi: {
enabled: true,
title: 'My API',
version: '1.0.0',
description: '我的 API 文档',
scalar: {
theme: 'default',
darkMode: false,
layout: 'modern',
favicon: '/favicon.svg',
},
servers: [
{ url: 'http://localhost:3000', description: '开发环境' },
{ url: 'https://api.example.com', description: '生产环境' },
],
tags: [
{ name: '用户', description: '用户管理接口' },
{ name: '订单', description: '订单管理接口' },
],
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
},
guardSecurityMap: {
auth: 'bearerAuth',
},
},
};
guardSecurityMap
将路由中间件名称自动映射为 OpenAPI Security Scheme:
// 路由声明中使用 auth 中间件
app.get('/profile', { middlewares: ['auth'] }, handler);
// ↑ OpenAPI 自动推断该路由需要 bearerAuth 认证
securitySchemes
支持的安全方案类型:
VextRequestContextConfig
AsyncLocalStorage 请求上下文配置。
export default {
requestContext: {
enabled: false, // 禁用后可提升 3-8% RPS
},
};
:::warning
禁用后以下功能失效:
- Logger 自动注入
requestId
app.throw() 自动解析请求级 locale
app.fetch() 自动传播 requestId
:::
VextClusterConfig
Cluster 多进程配置。
export default {
cluster: {
enabled: true,
workers: 4,
maxRestarts: 5,
rollingRestart: true,
},
};
也可通过环境变量启用:
VEXT_CLUSTER=1 node dist/index.js
VextCacheConfig
路由级响应缓存全局配置。
export default {
cache: {
enabled: true,
defaultTtl: 120,
maxEntries: 2000,
},
};
路由级缓存通过 RouteOptions.cache 配置,详见 路由缓存指南。
DEFAULT_CONFIG
框架内置默认配置的完整值:
import { DEFAULT_CONFIG } from 'vextjs';
// DEFAULT_CONFIG 的完整内容:
{
port: 3000,
host: '0.0.0.0',
adapter: 'native',
trustProxy: false,
middlewares: [],
cors: {
enabled: true,
origins: ['*'],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
headers: ['Content-Type', 'Authorization', 'X-Request-Id'],
credentials: false,
},
rateLimit: {
enabled: true,
max: 100,
window: 60,
message: 'Too Many Requests',
keyBy: 'ip',
},
requestId: {
enabled: true,
header: 'x-request-id',
responseHeader: 'x-request-id',
},
logger: {
level: 'info',
},
shutdown: {
timeout: 10,
},
response: {
hideInternalErrors: true,
wrap: true,
},
bodyParser: {
enabled: true,
maxBodySize: '1mb',
},
accessLog: {
enabled: true,
level: 'info',
skipPaths: [],
},
openapi: {
enabled: false,
},
requestContext: {
enabled: true,
},
}
VextUserConfig
用户配置的输入类型,所有字段均为可选。由 loadConfig() 合并默认值后生成完整的 VextConfig。
import type { VextUserConfig } from 'vextjs';
const config: VextUserConfig = {
port: 8080,
logger: { level: 'debug' },
};
export default config;
loadConfig
配置加载函数,执行三层合并。
import { loadConfig } from 'vextjs';
const config = await loadConfig({
rootDir: process.cwd(),
env: process.env.NODE_ENV ?? 'development',
});
// config: VextConfig(已合并、已冻结)
通常不需要手动调用,bootstrap() 内部会自动调用 loadConfig()。
环境变量覆盖
部分配置支持通过环境变量覆盖:
PORT=8080 NODE_ENV=production node dist/index.js
类型声明扩展
插件可通过 declare module 为 VextConfig 添加自定义字段:
// types/vext.d.ts
declare module 'vextjs' {
interface VextConfig {
redis?: {
host: string;
port: number;
password?: string;
};
}
}
之后在配置文件中使用将获得完整的类型提示:
// src/config/default.ts
export default {
redis: {
host: 'localhost',
port: 6379,
},
};