Skip to main content
You can extend the ContextExtend interface to add custom data to the Context for your project.

Context Extension Overview

Type Extension

TypeScript type extension Autocomplete support

Middleware

Request preprocessing Custom data injection

Validation Logic

Auth/permission checks Business rule application

Common Data

Session, tenant, etc. Request-scoped data

Type Extension

Custom User Type

Custom Context Fields

Use TypeScript’s Declaration Merging to extend the ContextExtend interface. Base fields such as request, reply, user, session, and locale are already included in the Context type, so you don’t need to redeclare them here. This enables IDE autocomplete and type checking.

Injecting Data with Middleware

Auth Middleware

Tenant Middleware

Locale Middleware

Request ID Middleware

Registering Middleware

Practical Usage Examples

Multi-tenant API

Permission-based Access Control

Internationalized Messages

Automated Audit Logging

Organization/Department Filtering

Context-based Caching

Cautions

Cautions when using custom Context: 1. Define type extensions early in the project 2. Middleware execution order matters 3. Treat Context data as immutable 4. Consider encrypting sensitive information 5. Prevent memory leaks (avoid storing large data)

Next Steps

SonamuContext

Understanding Context structure

Getting Context

Using Sonamu.getContext()

@api Decorator

API basic usage

Middleware

Request preprocessing