Skip to main content

Message Metadata

Message metadata allows you to attach custom information to messages at the message level. This is useful for tracking timestamps, model information, token usage, user context, and other message-level data.

Overview

Message metadata differs from data parts in that it’s attached at the message level rather than being part of the message content. While data parts are ideal for dynamic content that forms part of the message, metadata is perfect for information about the message itself.

Getting Started

Here’s a simple example of using message metadata to track timestamps and model information:

Defining Metadata Types

First, define your metadata type for type safety:

Sending Metadata from the Server

Use the messageMetadata callback in toUIMessageStreamResponse to send metadata at different streaming stages:
To enable type-safe metadata return object in messageMetadata, pass in the originalMessages parameter typed to your UIMessage type.

Accessing Metadata on the Client

Access metadata through the message.metadata property:
For streaming arbitrary data that changes during generation, consider using data parts instead.

Common Use Cases

Message metadata is ideal for:
  • Timestamps: When messages were created or completed
  • Model Information: Which AI model was used
  • Token Usage: Track costs and usage limits
  • User Context: User IDs, session information
  • Performance Metrics: Generation time, time to first token
  • Quality Indicators: Finish reason, confidence scores

See Also