Overview
Thecontenttype middleware validates and enforces Content-Type headers on requests. It ensures requests have the expected content type and can set default content types for responses.
Use it when you need:
- JSON-only API endpoints
- Form submission validation
- Content-Type enforcement
- Default response types
Installation
Quick Start
Functions
Request Validation
Response Headers
Examples
Require JSON
Require Form Data
Multiple Content Types
Set Default Content-Type
Set Response Content-Type
Per-Route Configuration
Combined Request/Response
API Reference
Functions
Behavior
- Only validates POST, PUT, PATCH requests (methods with bodies)
- Compares media type only, ignores parameters (charset, boundary)
- Returns 415 Unsupported Media Type on validation failure
Common Content Types
Technical Details
Implementation Overview
The contenttype middleware provides Content-Type validation and enforcement through a set of middleware functions that operate on request and response headers.Request Validation (Require, RequireJSON, RequireForm)
The validation middleware follows these steps:
- Method Filtering: Only validates requests with body content (POST, PUT, PATCH). GET, DELETE, and other methods bypass validation.
- Header Extraction: Retrieves the Content-Type header from the incoming request.
-
Media Type Parsing: Extracts the base media type by:
- Finding the semicolon separator (if present)
- Stripping parameters (charset, boundary, etc.)
- Trimming whitespace from the result
- Case-Insensitive Matching: Compares the extracted media type against allowed types using case-insensitive comparison.
-
Error Response: Returns HTTP 415 (Unsupported Media Type) if:
- Content-Type header is missing (for methods that require it)
- The media type doesnβt match any allowed types
Default Content-Type (Default)
Sets a default Content-Type header on the request if none is present. This middleware:
- Checks if the Content-Type header exists
- Sets the header to the specified default value if missing
- Preserves existing headers without modification
Response Content-Type (SetResponse)
Sets the Content-Type header on the response. This middleware:
- Unconditionally sets the response Content-Type header
- Executes before the handler processes the request
- Can be combined with request validation middleware
Key Design Decisions
- Parameter Stripping: Media type parameters are ignored during validation, allowing
application/json; charset=utf-8to matchapplication/json - Method-Specific: Only methods with request bodies are validated
- Fail-Fast: Validation happens before the handler executes
- Composable: Multiple middleware can be chained for complex scenarios
Best Practices
- Use
RequireJSON()for REST APIs - Use
RequireForm()for traditional forms - Set response Content-Type for consistency
- Combine
Default()withRequire()to provide fallback behavior - Apply validation at the router group level for route-specific rules