Skip to main content

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",
})
logger
LoggerConfig | Logger
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({ ... })
errorHandler
ResultHandler
Custom result handler for routing and parsing errorsDefault: defaultResultHandler
inputSources
Partial<InputSources>
Customize which request properties are merged into input
inputSources: {
  get: ["query", "params"],
  post: ["body", "params", "files"],
}
childLoggerProvider
function
Create a child logger for each request with custom context
childLoggerProvider: ({ parent, request }) =>
  parent.child({ requestId: uuid() })
accessLogger
function | null
Custom access logging function or null to disable
accessLogger: ({ method, path }, logger) =>
  logger.info(`${method} ${path}`)
wrongMethodBehavior
404 | 405
How to respond when wrong HTTP method is used
  • 404: Not Found
  • 405: Method Not Allowed (includes Allow header)
Default: 405
methodLikeRouteBehavior
'method' | 'path'
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 configuration
http: { 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 certificates
https: {
  options: {
    cert: fs.readFileSync("cert.pem"),
    key: fs.readFileSync("key.pem"),
  },
  listen: 443,
}
gracefulShutdown
GracefulShutdownConfig
Graceful shutdown configuration
gracefulShutdown: {
  timeout: 30000,
  events: ["SIGTERM", "SIGINT"],
  beforeShutdown: async () => {
    await db.disconnect();
  },
}
beforeRouting
function
Configure Express app before routing is attached
beforeRouting: ({ app, getLogger }) => {
  app.use("/docs", swaggerUi.serve, swaggerUi.setup(docs));
}
jsonParser
RequestHandler | false
Custom JSON body parser or false to disableDefault: express.json()
formParser
RequestHandler | false
Custom URL-encoded form parser or false to disableDefault: express.urlencoded({ extended: false })
upload
boolean | UploadOptions
Enable file uploads with optional configuration
upload: {
  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 compression
compression: { 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:
app
Express | Router
required
Express application or router instance
import 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