Overview
The createConfig() function creates a configuration object that controls the behavior of your Express Zod API server. It accepts a configuration object and returns a validated config ready for use with createServer() or attachRouting().
import { createConfig } from "express-zod-api";
const config = createConfig({
http: { listen: 8090 },
cors: true,
logger: { level: "debug" },
});
Signature
function createConfig(options: CommonConfig & (ServerConfig | AppConfig)): Config
Configuration Options
The configuration object accepts options from three categories:
Common Options
These options are available in all configurations:
cors
boolean | HeadersProvider
required
Enable CORS and optionally customize headers// Simple enable
cors: true
// Custom headers
cors: ({ defaultHeaders, request, endpoint, logger }) => ({
...defaultHeaders,
"Access-Control-Max-Age": "5000",
})
Built-in logger configuration or custom logger instance// Built-in logger
logger: { level: "debug", color: true, depth: 2 }
// Custom logger (Winston, Pino, etc)
logger: winston.createLogger({ ... })
Custom result handler for routing and parsing errorsDefault: defaultResultHandler
Customize which request properties are merged into inputinputSources: {
get: ["query", "params"],
post: ["body", "params", "files"],
}
Create a child logger for each request with custom contextchildLoggerProvider: ({ parent, request }) =>
parent.child({ requestId: uuid() })
Custom access logging function or null to disableaccessLogger: ({ method, path }, logger) =>
logger.info(`${method} ${path}`)
How to respond when wrong HTTP method is used
404: Not Found
405: Method Not Allowed (includes Allow header)
Default: 405
How to treat routing keys that look like HTTP methodsDefault: "method"
Show the Express Zod API logo on startupDefault: true
Server Options
Use these options when creating a standalone server:
http
{ listen: number | string | ListenOptions }
HTTP server configurationhttp: { listen: 8090 }
http: { listen: "/var/run/app.sock" }
http: { listen: { port: 8090, host: "0.0.0.0" } }
https
{ options: ServerOptions, listen: number | string | ListenOptions }
HTTPS server configuration with TLS certificateshttps: {
options: {
cert: fs.readFileSync("cert.pem"),
key: fs.readFileSync("key.pem"),
},
listen: 443,
}
Graceful shutdown configurationgracefulShutdown: {
timeout: 30000,
events: ["SIGTERM", "SIGINT"],
beforeShutdown: async () => {
await db.disconnect();
},
}
Configure Express app before routing is attachedbeforeRouting: ({ app, getLogger }) => {
app.use("/docs", swaggerUi.serve, swaggerUi.setup(docs));
}
Custom JSON body parser or false to disableDefault: express.json()
Custom URL-encoded form parser or false to disableDefault: express.urlencoded({ extended: false })
Enable file uploads with optional configurationupload: {
limits: { fileSize: 1024 * 1024 * 5 }, // 5MB
limitError: createHttpError(413, "File too large"),
beforeUpload: ({ request }) => {
if (!isAuthorized(request)) throw createHttpError(403);
},
}
compression
boolean | CompressionOptions
Enable GZIP/Brotli compressioncompression: { threshold: "1kb", level: 6 }
queryParser
'simple' | 'extended' | function
Query string parser
"simple": Node’s querystring module
"extended": qs module with nested objects
- Custom function:
(str) => qs.parse(str, { comma: true })
Default: "simple"
App Options
Use when attaching to an existing Express application:
Express application or router instanceimport express from "express";
const app = express();
const config = createConfig({
app,
cors: true,
logger: { level: "info" },
});
Examples
Minimal Configuration
import { createConfig } from "express-zod-api";
const config = createConfig({
http: { listen: 8090 },
cors: false,
});
Production Configuration
import { createConfig } from "express-zod-api";
import winston from "winston";
import createHttpError from "http-errors";
const config = createConfig({
https: {
options: {
cert: fs.readFileSync("/etc/ssl/cert.pem"),
key: fs.readFileSync("/etc/ssl/key.pem"),
},
listen: 443,
},
cors: ({ defaultHeaders }) => ({
...defaultHeaders,
"Access-Control-Allow-Origin": process.env.ALLOWED_ORIGIN,
}),
logger: winston.createLogger({
level: "info",
format: winston.format.json(),
transports: [new winston.transports.File({ filename: "api.log" })],
}),
upload: {
limits: { fileSize: 10 * 1024 * 1024 },
limitError: createHttpError(413, "File exceeds 10MB limit"),
},
compression: { threshold: "1kb", level: 6 },
gracefulShutdown: {
timeout: 30000,
beforeShutdown: async () => {
await db.disconnect();
await redis.quit();
},
},
});
With Existing Express App
import express from "express";
import { createConfig } from "express-zod-api";
const app = express();
// Add your own middleware
app.use("/health", (req, res) => res.send("OK"));
const config = createConfig({
app,
cors: true,
logger: { level: "debug" },
});
See Also