Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/MotiaDev/motia/llms.txt

Use this file to discover all available pages before exploring further.

Overview

Triggers define when and how steps are executed. Motia supports five types of triggers: HTTP requests, queue messages, cron schedules, state changes, and stream events.

Functions

http

Creates an HTTP trigger for API endpoints.
function http<TOptions extends ApiOptions<any> | undefined = undefined>(
  method: ApiRouteMethod,
  path: string,
  options?: TOptions,
  condition?: TriggerCondition
): ApiTrigger<TOptions extends ApiOptions<infer S> ? S : undefined>
method
ApiRouteMethod
required
HTTP method: 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', or 'HEAD'.
path
string
required
The API route path (e.g., /users/:id).
options
ApiOptions<TSchema>
Configuration options for the HTTP trigger.
bodySchema
StepSchemaInput
Zod schema or JSON schema for request body validation.
responseSchema
Record<number, StepSchemaInput>
Response schemas indexed by status code.
queryParams
readonly QueryParam[]
Expected query parameters.
middleware
readonly ApiMiddleware[]
Array of middleware functions.
condition
TriggerCondition
Optional condition function to determine if trigger should execute.
return
ApiTrigger
An HTTP trigger configuration object.

Example

import { step, http } from 'motia'
import { z } from 'zod'

export default step({
  name: 'create-user',
  triggers: [
    http('POST', '/users', {
      bodySchema: z.object({
        name: z.string(),
        email: z.string().email()
      }),
      responseSchema: {
        200: z.object({ id: z.string(), name: z.string() }),
        400: z.object({ error: z.string() })
      }
    })
  ]
}, async (input, ctx) => {
  const { name, email } = ctx.getData()
  // Create user...
  return { status: 200, body: { id: '123', name } }
})

api (Deprecated)

Note: Use http() instead. This function will be removed in a future version.
function api<TOptions extends ApiOptions<any> | undefined = undefined>(
  method: ApiRouteMethod,
  path: string,
  options?: TOptions,
  condition?: TriggerCondition
): ApiTrigger<TOptions extends ApiOptions<infer S> ? S : undefined>

queue

Creates a queue trigger for asynchronous message processing.
function queue<TOptions extends QueueOptions<any> | undefined = undefined>(
  topic: string,
  options?: TOptions,
  condition?: TriggerCondition
): QueueTrigger<TOptions extends QueueOptions<infer S> ? S : undefined>
topic
string
required
The queue topic name to subscribe to.
options
QueueOptions<TSchema>
Configuration options for the queue trigger.
input
StepSchemaInput
Zod schema or JSON schema for message validation.
infrastructure
Partial<InfrastructureConfig>
Infrastructure configuration for the queue.
handler
Partial<HandlerConfig>
Handler resource configuration.
ram
number
RAM allocation in MB.
cpu
number
CPU allocation.
timeout
number
Timeout in seconds.
queue
Partial<QueueConfig>
Queue configuration.
type
'fifo' | 'standard'
Queue type.
maxRetries
number
Maximum retry attempts.
visibilityTimeout
number
Visibility timeout in seconds.
delaySeconds
number
Delay before processing in seconds.
condition
TriggerCondition
Optional condition function to filter messages.
return
QueueTrigger
A queue trigger configuration object.

Example

import { step, queue } from 'motia'
import { z } from 'zod'

export default step({
  name: 'process-payment',
  triggers: [
    queue('payments', {
      input: z.object({
        orderId: z.string(),
        amount: z.number(),
        currency: z.string()
      }),
      infrastructure: {
        handler: { ram: 512, timeout: 30 },
        queue: { type: 'fifo', maxRetries: 3 }
      }
    })
  ]
}, async (input, ctx) => {
  const payment = ctx.getData()
  // Process payment...
})

cron

Creates a cron trigger for scheduled tasks.
function cron(
  expression: string,
  condition?: TriggerCondition
): CronTrigger
expression
string
required
Cron expression (e.g., '0 0 * * *' for daily at midnight).
condition
TriggerCondition
Optional condition to determine if task should run.
return
CronTrigger
A cron trigger configuration object.

Example

import { step, cron } from 'motia'

export default step({
  name: 'daily-report',
  triggers: [cron('0 9 * * *')] // Every day at 9 AM
}, async (input, ctx) => {
  ctx.logger.info('Generating daily report')
  // Generate report...
})

state

Creates a state change trigger.
function state(condition?: TriggerCondition): StateTrigger
condition
TriggerCondition
Optional condition to filter state changes.
return
StateTrigger
A state trigger configuration object.

Example

import { step, state } from 'motia'

export default step({
  name: 'on-user-change',
  triggers: [state((input, ctx) => {
    return input.group_id.startsWith('user:')
  })]
}, async (input, ctx) => {
  if (ctx.is.state(input)) {
    const { old_value, new_value } = input
    ctx.logger.info('User state changed', { old_value, new_value })
  }
})

stream

Creates a stream event trigger.
function stream(
  streamName: string,
  optionsOrCondition?: StreamOptions | TriggerCondition
): StreamTrigger
streamName
string
required
The name of the stream to subscribe to.
optionsOrCondition
StreamOptions | TriggerCondition
Either options object or condition function.
groupId
string
Specific group ID to filter events.
itemId
string
Specific item ID to filter events.
condition
TriggerCondition
Condition function to filter events.
return
StreamTrigger
A stream trigger configuration object.

Example

import { step, stream } from 'motia'

export default step({
  name: 'on-message',
  triggers: [
    stream('chat', {
      groupId: 'room-123',
      condition: (input, ctx) => {
        if (ctx.is.stream(input)) {
          return input.event.type === 'create'
        }
        return false
      }
    })
  ]
}, async (input, ctx) => {
  if (ctx.is.stream(input)) {
    const message = input.event.data
    // Handle new message...
  }
})

Types

ApiRouteMethod

type ApiRouteMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD'

TriggerCondition

type TriggerCondition<TInput = unknown> = (
  input: TriggerInput<TInput>,
  ctx: FlowContext<never, TriggerInput<TInput>>
) => boolean | Promise<boolean>

ApiTrigger

type ApiTrigger<TSchema extends StepSchemaInput | undefined = any> = {
  type: 'http'
  path: string
  method: ApiRouteMethod
  bodySchema?: TSchema
  responseSchema?: Record<number, StepSchemaInput>
  queryParams?: readonly QueryParam[]
  middleware?: readonly ApiMiddleware<any, any>[]
  condition?: TriggerCondition
}

QueueTrigger

type QueueTrigger<TSchema extends StepSchemaInput | undefined = any> = {
  type: 'queue'
  topic: string
  input?: TSchema
  condition?: TriggerCondition
  infrastructure?: Partial<InfrastructureConfig>
}

CronTrigger

type CronTrigger = {
  type: 'cron'
  expression: string
  input?: never
  condition?: TriggerCondition
}

StateTrigger

type StateTrigger<TSchema extends StepSchemaInput | undefined = any> = {
  type: 'state'
  condition?: TriggerCondition<InferSchema<TSchema>>
}

StreamTrigger

type StreamTrigger<TSchema extends StepSchemaInput | undefined = any> = {
  type: 'stream'
  streamName: string
  groupId?: string
  itemId?: string
  condition?: TriggerCondition<InferSchema<TSchema>>
}

TriggerConfig

type TriggerConfig = 
  | QueueTrigger 
  | ApiTrigger 
  | CronTrigger 
  | StateTrigger 
  | StreamTrigger

QueryParam

interface QueryParam {
  name: string
  description: string
}

ApiMiddleware

type ApiMiddleware<TBody = unknown, TEnqueueData = never> = (
  req: MotiaHttpArgs<TBody>,
  ctx: FlowContext<TEnqueueData, MotiaHttpArgs<TBody>>,
  next: () => Promise<ApiResponse | void>
) => Promise<ApiResponse | void>

Build docs developers (and LLMs) love