Understanding Templates
tsoa generates route files using Handlebars templates that are framework-specific:- Express:
express.hbs - Koa:
koa.hbs - Hapi:
hapi.hbs
Template Context
The template context includes:Creating Custom Templates
Common Customizations
Add Custom Imports
Add your own imports at the top:Add Request Logging
Log every request:Add Rate Limiting
Apply rate limiting to specific routes:Custom Error Handling
Add custom error handling logic:Add Request Tracing
Add distributed tracing:Handlebars Helpers
Add custom Handlebars helpers for complex logic:helpers.js
Framework-Specific Customizations
Express: Add CORS Headers
Koa: Add Response Time
Hapi: Add Custom Validation
Advanced Patterns
Conditional Middleware
Apply middleware based on route metadata:Route Versioning
Generate Route Documentation
Testing Custom Templates
Validate Generated Code
Template Debugging
Add debug output to see template context:Best Practices
Keep Changes Minimal
Keep Changes Minimal
Only customize what’s necessary. The default templates are well-tested and maintained.
Version Control Templates
Version Control Templates
Keep your custom templates in version control and document changes.
Test Thoroughly
Test Thoroughly
Test all route scenarios after template changes: authentication, file uploads, validation, etc.
Stay Compatible
Stay Compatible
When upgrading tsoa, check if template structure has changed and update your customizations.
Use Comments
Use Comments
Document why you made specific customizations in template comments.
Troubleshooting
Template Syntax Errors
If routes generation fails:- Check Handlebars syntax
- Verify all
{{#if}}blocks are closed with{{/if}} - Ensure
{{#each}}loops are closed with{{/each}} - Validate JSON output with
{{json value}}
TypeScript Errors
If generated code has TypeScript errors:- Check imports are correct
- Verify type annotations
- Ensure proper indentation
- Test with a simple route first
Runtime Errors
If routes fail at runtime:- Verify middleware order
- Check async/await usage
- Validate error handling
- Test with curl or Postman
Examples
Complete Custom Express Template
A minimal custom template:templates/express.hbs
Next Steps
OpenAPI Versions
Learn about OpenAPI specification versions
Advanced Configuration
Explore advanced tsoa configuration