Understanding Caddy Modules
Modules are the building blocks of Caddy’s extensible architecture. Every module:- Implements the
Moduleinterface - Has a unique ModuleID (namespace)
- Provides a constructor function
- Gets compiled into Caddy as a Go package
Caddy modules are compile-time extensions, not runtime plugins. They must be compiled into the binary.
The Module Interface
Every Caddy module must implement theModule interface from modules.go:54:
ModuleInfo struct contains:
Module Lifecycle
When a module is loaded by a host module, the following sequence occurs:1
Module Instantiation
ModuleInfo.New() is called to get a new instance of the module.2
Configuration Unmarshaling
The module’s configuration is unmarshaled into that instance from JSON.
3
Provisioning
If the module implements
Provisioner, the Provision() method is called.4
Validation
If the module implements
Validator, the Validate() method is called.5
Type Assertion
The module is type-asserted to the interface expected by the host module (e.g.,
caddyhttp.MiddlewareHandler).6
Cleanup
When the context is canceled, if the module implements
CleanerUpper, its Cleanup() method is called.Module Registration
Modules must be registered during the init phase usingRegisterModule() from modules.go:138:
Creating Your First Module
Here’s a complete example of an HTTP handler module based on the tracing module atmodules/caddyhttp/tracing/module.go:15:
Module Configuration
JSON Configuration
Modules are configured using JSON. The struct tags control how configuration is unmarshaled:Strict Unmarshaling
Caddy uses strict JSON unmarshaling frommodules.go:342 to catch configuration errors:
Best Practices
Common Module Types
HTTP Handlers
Implementcaddyhttp.MiddlewareHandler:
http.handlers.*
HTTP Matchers
Match requests based on criteria. Namespace:http.matchers.*
TLS Certificate Loaders
Load TLS certificates from various sources. Namespace:tls.certificates.*
Storage Backends
Implementcertmagic.Storage for storing TLS certificates.
Namespace: caddy.storage.*
Config Adapters
Convert other config formats to Caddy JSON. Namespace:caddy.config_adapters.*
Apps
Top-level applications that Caddy runs. Namespace: empty (e.g.,http, tls)
Working with Context
TheContext passed to Provision() provides:
- Logger:
ctx.Logger()returns a*zap.Logger - Module loading:
ctx.LoadModule()loads nested modules - App access:
ctx.App("appName")gets app instances - Module info:
ctx.Module()returns current module info
Next Steps
Plugin Tutorial
Follow a step-by-step tutorial to build a complete plugin
Module Namespaces
Learn about the module namespace system
Custom Builds
Build Caddy with your custom modules
Contributing
Contribute your module to Caddy