Core Concepts

Messages

Understanding messages and event handling in Bubble Tea.

Messages are events in Bubble Tea. Everything that happens in your app—keypresses, mouse clicks, timers, I/O results—comes as a message.

Built-in Messages

Bubble Tea provides several built-in message types:

Custom Messages

Define your own message types for application-specific events:

// Simple message
type tickMsg time.Time

// Message with data
type userLoadedMsg struct {
    user User
}

// Error message
type errMsg struct {
    err error
}

func (e errMsg) Error() string {
    return e.err.Error()
}

Type Switches

Handle messages with a type switch:

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
    switch msg := msg.(type) {
    case tea.KeyPressMsg:
        // Handle keyboard
    case tea.MouseMsg:
        // Handle mouse
    case tea.WindowSizeMsg:
        // Handle resize
    case tickMsg:
        // Handle custom tick
    case userLoadedMsg:
        m.user = msg.user
    case errMsg:
        m.err = msg.err
    }
    return m, nil
}

Message Flow

graph TD
    A[User Input] --> B[Runtime]
    C[Commands] --> B
    D[Subscriptions] --> B
    B --> E[Update]
    E --> F[New Model]
    F --> G[View]
Messages are the only way data enters your Update function. This makes your application predictable and easy to debug.