Skip to main content

Parameter Decorators

Parameter decorators provide a convenient way to inject user session information directly into your controller methods. InversifyJS HTTP Better Auth provides framework-specific decorators that extract and parse authentication data from incoming requests.

Available Decorators

@Controller('/api')
class UserController {
@ApplyMiddleware(betterAuthMiddlewareServiceIdentifier)
@Get('/profile')
public async getProfile(
@ExpressUserSession() session: UserSession<BetterAuthOptions>,
): Promise<UserSession<BetterAuthOptions>> {
return session;
}
}
Required middleware

You must apply betterAuthMiddlewareServiceIdentifier middleware to any controller relying on session decorators or apply betterAuthMiddlewareServiceIdentifier as global middleware.

Return Types

All decorators return either:

  • UserSession<TOptions> - When a valid session is found
  • null - When no valid session is found

Handling Authenticated Users

@Controller('/api')
class UserController {
@ApplyMiddleware(betterAuthMiddlewareServiceIdentifier)
@Get('/user-info')
public async getUserInfo(
@HonoUserSession() session: UserSession<BetterAuthOptions>,
): Promise<{ id: string; email: string; name: string }> {
return {
email: session.user.email,
id: session.user.id,
name: session.user.name,
};
}
}

Handling Optional Authentication

@Controller('/api')
class OptionalAuthController {
@ApplyMiddleware(betterAuthMiddlewareServiceIdentifier)
@Get('/optional-auth')
public async optionalAuth(
@HonoUserSession() session: UserSession<BetterAuthOptions> | null,
): Promise<{ authenticated: boolean; userId?: string }> {
if (session === null) {
return { authenticated: false };
}

return {
authenticated: true,
userId: session.user.id,
};
}
}

Error Handling

If the Better Auth middleware is not applied, the decorators will throw an error during request processing. Always ensure the middleware is properly configured:

@Controller('/api')
export class BadController {
@Get('/profile')
public async getProfile(
@HonoUserSession() session: UserSession<BetterAuthOptions>, // Error!
): Promise<UserSession<BetterAuthOptions>> {
return session;
}
}

// ✅ This works - middleware properly applied
@ApplyMiddleware(betterAuthMiddlewareServiceIdentifier)
@Controller('/api')
export class GoodController {
@Get('/profile')
public async getProfile(
@HonoUserSession() session: UserSession<BetterAuthOptions>,
): Promise<UserSession<BetterAuthOptions>> {
return session;
}
}