### Create a New Motia Project Source: https://www.motia.dev/docs/getting-started/quick-start Use the Motia CLI to create a new project. This command scaffolds the project and installs dependencies. You can specify a template for quick setup. ```bash npx motia@latest create ``` ```bash # TypeScript starter npx motia@latest create my-app --template starter-typescript # JavaScript starter npx motia@latest create my-app --template starter-javascript # Python starter npx motia@latest create my-app --template starter-python ``` -------------------------------- ### Clone Motia Example Repository Source: https://www.motia.dev/docs/getting-started/build-your-first-motia-app/workflows Clone the example repository to get started with building your first Motia application. This repository contains all the code examples used in the guide. After cloning, navigate into the directory and checkout the 'workflow-orchestrator' branch. ```bash git clone https://github.com/MotiaDev/build-your-first-app.git cd build-your-first-app git checkout workflow-orchestrator ``` -------------------------------- ### Start Motia Development Server Source: https://www.motia.dev/docs/getting-started/quick-start Navigate to your project directory and start the Motia development server using the CLI. This command also launches the Workbench UI. ```bash cd npx motia dev ``` ```bash # Using other package managers pnpm dev yarn dev bun dev ``` -------------------------------- ### Clone and Setup Motia Streaming Example Source: https://www.motia.dev/docs/getting-started/build-your-first-motia-app/streaming-agents Instructions to clone the Motia 'build-your-first-app' repository, checkout the 'stream-ai-agents' branch, install Node.js dependencies, configure the OpenAI API key, and start the development server. ```bash git clone https://github.com/MotiaDev/build-your-first-app.git cd build-your-first-app git checkout stream-ai-agents npm install # Set up your OpenAI API key in .env OPENAI_API_KEY=your_api_key_here npm run dev ``` -------------------------------- ### Install and Build Plugin Project Source: https://www.motia.dev/docs/development-guide/plugins Provides the commands to navigate into the newly created plugin directory, install its dependencies, and build the project. These steps are essential after using the CLI to create a new plugin. ```bash cd my-plugin pnpm install pnpm run build ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://www.motia.dev/docs/examples/github-stars-counter This code snippet shows the basic steps to clone the project repository from GitHub and install the necessary npm dependencies to get started. This is the initial setup required before configuring or running the application. ```bash git clone https://github.com/MotiaDev/github-stars-counter.git cd github-stars-counter npm install ``` -------------------------------- ### Install Dependencies (Shell) Source: https://www.motia.dev/docs/examples/finance-agent Commands to clone the repository and install project dependencies using pnpm or npm. This is a standard setup procedure for Node.js projects. ```shell git clone https://github.com/MotiaDev/motia-examples cd examples/finance-agent pnpm install # or npm install ``` -------------------------------- ### Install Dependencies and Start Motia Workbench Source: https://www.motia.dev/docs/getting-started/build-your-first-motia-app/workflows Install project dependencies using npm and start the Motia Workbench development server. The Workbench provides an interactive environment for building and testing your Motia applications. It will be accessible at http://localhost:3000. ```bash npm install npm run dev ``` -------------------------------- ### Clone and Set Up Motia Project Source: https://www.motia.dev/docs/getting-started/build-your-first-motia-app/ai-agents Clone the example repository for building your first Motia app, navigate into the directory, checkout the 'ai-agents' branch, and install dependencies. Ensure you set up your OpenAI API key in the .env file as it's crucial for agentic workflows. ```bash git clone https://github.com/MotiaDev/build-your-first-app.git cd build-your-first-app git checkout ai-agents npm install OPENAI_API_KEY=your_api_key_here ``` -------------------------------- ### Clone GitHub Integration Repository (Shell) Source: https://www.motia.dev/docs/examples/github-integration-workflow Command to clone the example repository for GitHub integration. This involves using git to download the project files to your local machine. Ensure you have Git installed and configured. ```shell git clone git@github.com:MotiaDev/motia-examples.git cd examples/github-integration-workflow ``` -------------------------------- ### Frontend Setup: Install Motia Client Source: https://www.motia.dev/docs/development-guide/streams Shows the command to install the Motia client library in a frontend project using npm. This is the first step to enable communication with Motia backend services, including real-time stream updates. ```bash npm install motia-client ``` -------------------------------- ### Motia CLI: Pull AI Development Guides Source: https://www.motia.dev/docs/api-reference Installs AI development guides such as AGENTS.md and CLAUDE.md, along with Cursor IDE rules. The `--force` option overwrites existing files. ```shell motia rules pull motia rules pull --force # Overwrite existing files ``` -------------------------------- ### Create New Motia Project with AI Development Guides Source: https://www.motia.dev/docs/ai-development-guide Command to create a new Motia project. This command automatically includes AI development guides in the `.cursor/rules/` directory, making them compatible with major AI coding tools. ```bash npx motia@latest create cd ``` -------------------------------- ### Clone Motia Examples Repository Source: https://www.motia.dev/docs/examples/trello-automation Clones the example repository containing the Trello automation flow. Requires Git to be installed. ```bash git clone git@github.com:MotiaDev/motia-examples.git cd examples/trello-flow ``` -------------------------------- ### Install and Import Motia Plugin Source: https://www.motia.dev/docs/development-guide/plugins Installs a Motia plugin using pnpm and imports it into the Motia configuration. This is the first step to enable plugin functionality in your Motia project. ```bash pnpm add @motiadev/plugin-example ``` ```javascript import examplePlugin from '@motiadev/plugin-example/plugin' export default { plugins: [examplePlugin], } ``` -------------------------------- ### Install Stockfish Engine Source: https://www.motia.dev/docs/product-showcase/chessarena-ai Provides methods for installing the Stockfish chess engine, a critical component for move evaluation. Supports installation via Homebrew, a project-specific installer, or manual download. ```shell # Option A: Using Homebrew (macOS - Recommended) brew install stockfish ``` ```shell # Option B: Using the project installer pnpm install-stockfish # Supported: linux-x86, mac-m1 ``` -------------------------------- ### Start Development Server with Debug Logging Source: https://www.motia.dev/docs/development-guide/observability Command-line instructions for running the Motia development server with standard logging and with debug mode enabled. Debug mode shows all logging levels including debug logs for deep inspection. ```bash npm run dev ``` ```bash npm run dev -- --debug ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://www.motia.dev/docs/product-showcase/chessarena-ai Instructions to clone the chess arena AI repository and install project dependencies using pnpm. This is the initial step for setting up the project locally. ```shell git clone https://github.com/MotiaDev/chessarena-ai.git cd chessarena-ai pnpm install ``` -------------------------------- ### Start Development Server (Shell) Source: https://www.motia.dev/docs/examples/finance-agent Command to run the application in development mode using pnpm. This command starts the local server for the Motia Workbench. ```shell pnpm dev ``` -------------------------------- ### Clone Repository and Install Dependencies (Shell) Source: https://www.motia.dev/docs/examples/ai-deep-research-agent Instructions for cloning the project repository and installing necessary Node.js dependencies using pnpm or npm. ```shell git clone https://github.com/MotiaDev/motia-examples cd examples/ai-deep-research-agent pnpm install # or npm install ``` -------------------------------- ### State Management Example (TypeScript) Source: https://www.motia.dev/docs/concepts/steps Illustrates how to use the 'state' object from the context to persist and retrieve data across Steps. This example shows setting a theme preference and then retrieving it. ```typescript await state.set(traceId, 'preferences', { theme: 'dark' }); const prefs = await state.get(traceId, 'preferences'); ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://www.motia.dev/docs/examples/trello-automation Installs all necessary project dependencies using the pnpm package manager. Assumes Node.js and pnpm are installed. ```bash pnpm install ``` -------------------------------- ### Motia CLI: Install Python Dependencies Source: https://www.motia.dev/docs/api-reference Sets up the Python virtual environment and installs necessary dependencies for your Motia project. This is often automatically run via npm postinstall hooks during development. ```shell motia install npm run dev # Auto-runs motia install via postinstall hook ``` -------------------------------- ### Install Node.js Dependencies (Shell) Source: https://www.motia.dev/docs/examples/github-integration-workflow Command to install the necessary Node.js dependencies for the GitHub integration workflow. This command should be run after cloning the repository and navigating into the project directory. ```shell npm install ``` -------------------------------- ### Start Docker Compose Services Source: https://www.motia.dev/docs/examples/adapter-configuration Command to start the Docker Compose services defined in the `docker-compose.yml` file in detached mode (`-d`). ```bash docker-compose up -d ``` -------------------------------- ### Motia CLI: Start Production Server Source: https://www.motia.dev/docs/api-reference Starts the Motia production server without the Workbench or hot-reloading. This command is used for deploying and running your application in a production environment. ```shell motia start motia start --port 8080 --host 0.0.0.0 ``` -------------------------------- ### Start Motia Workbench Development Server Source: https://www.motia.dev/docs/concepts/workbench Command to start the Motia Workbench development server. This command initiates both the backend server and the Workbench interface. Changes to Steps reload automatically without requiring a manual restart. ```bash npm run dev ``` -------------------------------- ### Set Up Motia Project for Docker Source: https://www.motia.dev/docs/development-guide/cli Initializes the Motia project to be compatible with Docker. This command prepares the necessary configurations for containerizing the application. ```bash npx motia docker setup ``` -------------------------------- ### Configure Environment Variables (Shell) Source: https://www.motia.dev/docs/examples/finance-agent Instructions to copy the example environment file and update it with necessary API keys for Alpha Vantage, SerperDev, and OpenAI. This is crucial for the application's functionality. ```shell cp .env.example .env Update .env with your API keys: ALPHA_VANTAGE_API_KEY=your_alpha_vantage_api_key_here SERPER_API_KEY=your_serper_api_key_here OPENAI_API_KEY=your_openai_api_key_here ``` -------------------------------- ### Create Motia Plugin using CLI Source: https://www.motia.dev/docs/development-guide/plugins Demonstrates the command to quickly scaffold a new Motia plugin using the Motia Command Line Interface. This command initializes a new plugin project with a standard structure and configuration. ```bash pnpm dlx motia create --plugin my-plugin ``` -------------------------------- ### API Trigger Example (TypeScript) Source: https://www.motia.dev/docs/concepts/steps Demonstrates a Motia Step configured as an API trigger. It defines a GET endpoint with a path parameter ':id' and handles the request to fetch user information. ```typescript import { ApiRouteConfig, Handlers } from 'motia' export const config: ApiRouteConfig = { name: 'GetUser', type: 'api', path: '/users/:id', method: 'GET' } export const handler: Handlers['GetUser'] = async (req, { logger }) => { const userId = req.pathParams.id logger.info('Getting user', { userId }) return { status: 200, body: { id: userId, name: 'John' } } } ``` -------------------------------- ### Motia CLI: Create New Project Source: https://www.motia.dev/docs/api-reference Initializes a new Motia project. You can specify a project name and a template, including starter templates for TypeScript, JavaScript, and Python, as well as tutorial-based templates. ```shell npx motia create my-app npx motia create . # Use current directory npx motia create --template motia-tutorial-python my-python-app ``` -------------------------------- ### Labeled Virtual Emits for Connections (TypeScript) Source: https://www.motia.dev/docs/development-guide/flows Defines an API Step with 'virtualEmits' that include labels and conditional properties for enhanced visualization in Workbench. This example shows 'email-sent' and 'email-failed' connections within the 'notifications' flow. ```typescript export const config: ApiRouteConfig = { name: 'SendEmail', type: 'api', path: '/send', method: 'POST', virtualEmits: [ { topic: 'email-sent', label: 'Email delivered' }, { topic: 'email-failed', label: 'Failed to send', conditional: true }, ], flows: ['notifications'] } ``` -------------------------------- ### List All Pets API Endpoint (TypeScript) Source: https://www.motia.dev/docs/getting-started/build-your-first-motia-app/api-endpoints Implements the GET /pets endpoint to retrieve a list of all pets. It utilizes the in-memory store for data retrieval. This example assumes the data is managed by a store, abstracting database interactions. ```typescript import { ApiRouteConfig, Handlers } from 'motia' import { TSStore } from './ts-store' export const config: ApiRouteConfig = { name: 'GetPets', type: 'api', path: '/pets', method: 'GET', flows: ['PetManagement'], } export const handler: Handlers['GetPets'] = async (req, { logger }) => { // In a real application, this would be a database call // e.g., const pets = await db.pets.findMany() const pets = TSStore.list() logger.info('Retrieved all pets', { count: pets.length }) return { status: 200, body: pets } } ``` -------------------------------- ### Define Flows in Step Config (TypeScript) Source: https://www.motia.dev/docs/development-guide/flows Adds a 'flows' array to a Step configuration, grouping related steps into a single workflow visible in Workbench. This example shows a 'CreateResource' API Step belonging to the 'resource-management' flow. ```typescript export const config: ApiRouteConfig = { name: 'CreateResource', type: 'api', path: '/resources', method: 'POST', flows: ['resource-management'] } ``` -------------------------------- ### Deploy Chess Platform using Motia CLI Source: https://www.motia.dev/docs/product-showcase/chessarena-ai Instructions for deploying the chess platform to production using the Motia CLI. Supports deployment with API keys, version names, and environment variables. ```shell # Deploy with version and API key motia cloud deploy --api-key your-api-key --version-name 1.0.0 ``` ```shell # Deploy with environment variables motia cloud deploy --api-key your-api-key \ --version-name 1.0.0 \ --env-file .env.production \ --environment-id your-env-id ``` -------------------------------- ### Invoke Motia Developer Subagent with Claude Code Source: https://www.motia.dev/docs/ai-development-guide Example of how to invoke a specific subagent within Claude Code for Motia development. This command instructs the AI to create an email marketing backend system using the `motia-developer` subagent. ```bash Use the motia-developer subagent to create a email marketing backend system ``` -------------------------------- ### TypeScript: Pass User Data from Middleware to Handler Source: https://www.motia.dev/docs/development-guide/middleware This example demonstrates how middleware can enrich the request object with user data after authentication. It requires extending the `ApiRequest` interface in `api.d.ts` to include the `user` property. The handler can then safely access `req.user`. ```typescript // api.d.ts import 'motia' declare module 'motia' { interface ApiRequest { user?: { id: string; role: string } } } ``` ```typescript const authMiddleware: ApiMiddleware = async (req, ctx, next) => { // Verify token... req.user = { id: '123', role: 'admin' } return next() } export const handler = async (req, ctx) => { // req.user is typed and ready to use if (req.user?.role === 'admin') { return { status: 200, body: { message: 'Welcome Admin' } } } return { status: 403, body: { error: 'Forbidden' } } } ``` -------------------------------- ### Configure Environment Variables (Shell) Source: https://www.motia.dev/docs/examples/github-integration-workflow Shell commands to copy an example environment file and then update it with necessary credentials like GitHub token and OpenAI API key. This step is crucial for the application to authenticate with external services. ```shell cp .env.example .env # Update .env with your_github_token_here and your_openai_api_key_here ``` -------------------------------- ### Customize Step UI with EventNode and Icon (TypeScript) Source: https://www.motia.dev/docs/development-guide/customizing-flows This example demonstrates how to customize a Motia Workbench Step by wrapping the built-in `EventNode` with custom JSX. It adds a description and an image to the default node appearance. This requires the 'motia/workbench' package. ```tsx import { EventNode, EventNodeProps } from 'motia/workbench' import React from 'react' export const Node: React.FC = (props) => { return (
{props.data.description}
) } ``` -------------------------------- ### Configure Environment Variables (Shell) Source: https://www.motia.dev/docs/examples/ai-deep-research-agent Steps to copy the example environment file and update it with required API keys for OpenAI and Firecrawl. ```shell cp .env.example .env # Update .env with your API keys: # OPENAI_API_KEY=your-openai-api-key-here # FIRECRAWL_API_KEY=your-firecrawl-api-key-here ``` -------------------------------- ### Basic State Operations in TypeScript Source: https://www.motia.dev/docs/development-guide/state-management Demonstrates fundamental state operations including set, get, getGroup, delete, and clear methods. This example shows how to store order data in a group, retrieve specific items or all items in a group, and remove data. ```TypeScript export const handler: Handlers['MyStep'] = async (input, { state }) => { // Store an item in a group await state.set('orders', 'order-123', { id: 'order-123', status: 'pending', total: 99.99 }) // Get a specific item const order = await state.get('orders', 'order-123') // Get all items in a group const allOrders = await state.getGroup('orders') // Delete a specific item await state.delete('orders', 'order-123') // Clear entire group await state.clear('orders') } ``` -------------------------------- ### Setup Motia Stream Provider in React App Source: https://www.motia.dev/docs/development-guide/streams Wrap your React application with `MotiaStreamProvider` to enable real-time stream communication. This component requires the WebSocket server address and an authentication token. Ensure the `authToken` is securely obtained, for example, from cookies or local storage. ```tsx import { MotiaStreamProvider } from '@motiadev/stream-client-react' function App() { const authToken = useAuthToken() // e.g. from cookies or local storage return ( {/* Your app */} ) } ``` -------------------------------- ### Run Development Server and Test with cURL (Shell) Source: https://www.motia.dev/docs/examples/ai-deep-research-agent Commands to start the local development server and perform a sample research request using cURL. ```shell # Start the development server: pnpm dev # Access the Motia Workbench at http://localhost:3000 # Make a test request: curl --request POST \ --url http://localhost:3000/research \ --header 'Content-Type: application/json' \ --data '{ "query": "Advancements in renewable energy storage", "depth": 1, "breadth": 1 }' ``` -------------------------------- ### Update Motia AI Development Guides Source: https://www.motia.dev/docs/ai-development-guide Commands to update the AI development guides for your Motia project. `npx motia rules pull` fetches the latest updates, while `npx motia rules pull --force` overwrites existing guides with the latest version. ```bash npx motia rules pull # Update to latest npx motia rules pull --force # Overwrite existing ``` -------------------------------- ### Install Project Dependencies with npm Source: https://www.motia.dev/docs/examples/ai-content-moderation This command installs all the necessary npm packages for the Motia project. Ensure you have Node.js and npm installed before running this. ```bash npm install ``` -------------------------------- ### Configure Environment Variables for Trello Flow Source: https://www.motia.dev/docs/examples/trello-automation Copies the example environment file and updates it with API keys and list IDs for Trello, OpenAI, and Slack. Requires credentials for each service. ```bash cp .env.example .env TRELLO_API_KEY=your_trello_api_key TRELLO_TOKEN=your_trello_token OPENAI_API_KEY=your_openai_api_key OPENAI_MODEL=your_openai_model SLACK_WEBHOOK_URL=your_slack_webhook_url TRELLO_NEW_TASKS_LIST_ID=your_new_tasks_list_id TRELLO_IN_PROGRESS_LIST_ID=your_in_progress_list_id TRELLO_NEEDS_REVIEW_LIST_ID=your_needs_review_list_id TRELLO_COMPLETED_LIST_ID=your_completed_list_id ``` -------------------------------- ### Create Fully Custom Step UI with BaseHandle (TypeScript/React) Source: https://www.motia.dev/docs/development-guide/customizing-flows This example shows a fully custom UI for a Motia Workbench Step using React. It utilizes `BaseHandle` for connection points and prevents the default code viewer from opening on click. This approach offers complete control over the step's appearance and behavior within the Motia flow diagram. ```tsx import React from 'react' import { BaseHandle, Position } from 'motia/workbench' import type { EventNodeProps } from 'motia/workbench' export default function ProcessOrderUI({ data }: EventNodeProps) { // Prevent code viewer from opening when clicked const handleClick = (e: React.MouseEvent) => { e.stopPropagation() e.preventDefault() return false } return (
🍽️ Process Order
{data.name}
Handles food orders
) } ``` -------------------------------- ### Motia CLI: Docker Setup Source: https://www.motia.dev/docs/api-reference Generates a Dockerfile and a .dockerignore file for your Motia project, facilitating containerization and deployment. ```shell motia docker setup ```