.do

MDX.sh

Cloud-based runtime for executable MDXLD documents

MDX.sh

MDX.sh is the cloud-based runtime for executable MDXLD documents - run scripts, components, functions, and tests directly from MDX content.

What is MDX.sh?

MDX.sh executes .mdx content with embedded code:

  • Cloud Runtime: Execute MDX scripts in the cloud
  • Embedded Scripts: Run code blocks marked with conventions
  • Components: Import/export React components
  • Functions: Define and export functions
  • Tests: Run Vitest tests inline
  • API Access: Expose data, content, functions, components, tests via API
  • Preview Integration: Render on mdx.as with different output formats
  • Custom Domains: Deploy to custom domains

Script Conventions

js script - JavaScript Script

Execute JavaScript code blocks:

```js script
console.log('Hello from MDX.sh!')

export const greeting = 'Hello, World!'

export function greet(name) {
  return `Hello, ${name}!`
}
```

Execution:

Response:

Hello from MDX.sh!

ts script - TypeScript Script

Execute TypeScript code blocks:

```ts script
interface User {
  name: string
  email: string
}

export const users: User[] = [
  { name: 'Alice', email: '[email protected]' },
  { name: 'Bob', email: '[email protected]' }
]

export function findUser(email: string): User | undefined {
  return users.find(u => u.email === email)
}

console.log(`Found ${users.length} users`)
```

Execution:

ts test - Vitest Tests

Run Vitest tests inline:

```ts test
import { describe, it, expect } from 'vitest'
import { greet } from './hello'

describe('greet', () => {
  it('should greet by name', () => {
    expect(greet('Alice')).toBe('Hello, Alice!')
  })

  it('should handle empty name', () => {
    expect(greet('')).toBe('Hello, !')
  })
})
```

Run tests:

Response:

{
  "success": true,
  "tests": 2,
  "passed": 2,
  "failed": 0,
  "duration": 23,
  "results": [
    {
      "name": "should greet by name",
      "status": "passed",
      "duration": 12
    },
    {
      "name": "should handle empty name",
      "status": "passed",
      "duration": 11
    }
  ]
}

Component Exports

React Components

Export React components from MDX:

```tsx
export function Hero({ title, subtitle }) {
  return (
    <div className="hero">
      <h1>{title}</h1>
      <p>{subtitle}</p>
    </div>
  )
}

export function Feature({ icon, title, description }) {
  return (
    <div className="feature">
      <div className="icon">{icon}</div>
      <h3>{title}</h3>
      <p>{description}</p>
    </div>
  )
}
```

# Landing Page

<Hero
  title="Build Amazing Products"
  subtitle="Ship faster with MDX.sh"
/>

<Feature
  icon="⚡"
  title="Fast"
  description="Lightning fast execution"
/>

Access components:

# Get component code
curl https://mdx.sh/mystartup.co/components/Hero

# Render component
curl https://mdx.sh/mystartup.co/components/Hero/render \
  -d '{"title": "Custom Title", "subtitle": "Custom Subtitle"}'

Function Exports

Export Functions

Define and export utility functions:

```ts script
export function formatCurrency(amount: number, currency: string = 'USD'): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency
  }).format(amount)
}

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

export async function fetchData(url: string) {
  const response = await fetch(url)
  return response.json()
}
```

Call functions:

# Call formatCurrency
curl https://mdx.sh/mystartup.co/functions/formatCurrency \
  -d '{"args": [1234.56, "USD"]}'

# Response: {"result": "$1,234.56"}

# Call slugify
curl https://mdx.sh/mystartup.co/functions/slugify \
  -d '{"args": ["Hello World!"]}'

# Response: {"result": "hello-world"}

Data Exports

Export Constants

Export data and constants:

```ts script
export const config = {
  apiUrl: 'https://api.mystartup.co',
  version: '1.0.0',
  features: ['analytics', 'auth', 'payments']
}

export const pricing = [
  {
    name: 'Starter',
    price: 29,
    features: ['10 users', '100 GB storage', 'Email support']
  },
  {
    name: 'Pro',
    price: 99,
    features: ['Unlimited users', '1 TB storage', 'Priority support']
  }
]

export const team = [
  { name: 'Alice', role: 'CEO', avatar: '/images/alice.jpg' },
  { name: 'Bob', role: 'CTO', avatar: '/images/bob.jpg' }
]
```

Access data:

Content Access

Get Frontmatter

Access document frontmatter:

Response:

{
  "$type": "LandingPage",
  "$context": "https://schema.org",
  "title": "My Startup",
  "description": "Build amazing products",
  "author": "Jane Doe"
}

Get Content

Access markdown content:

Response:

# My Startup

We build amazing products...

Get Rendered HTML

Get rendered HTML output:

Response:

<h1>My Startup</h1>
<p>We build amazing products...</p>

API Reference

List Exports

List all exports from a document:

Response:

{
  "scripts": ["hello", "users"],
  "components": ["Hero", "Feature"],
  "functions": ["formatCurrency", "slugify", "fetchData"],
  "data": ["config", "pricing", "team"],
  "tests": ["hello"]
}

Execute Script

Execute a named script:

Call Function

Call an exported function:

curl -X POST https://mdx.sh/mystartup.co/functions/greet \
  -H "Content-Type: application/json" \
  -d '{"args": ["Alice"]}'

Response:

{
  "result": "Hello, Alice!"
}

Render Component

Render an exported component:

curl -X POST https://mdx.sh/mystartup.co/components/Hero/render \
  -H "Content-Type: application/json" \
  -d '{
    "props": {
      "title": "Welcome",
      "subtitle": "To our platform"
    }
  }'

Response:

<div class="hero">
  <h1>Welcome</h1>
  <p>To our platform</p>
</div>

Run Tests

Run all tests:

Run specific test:

Import Support

Import from npm

Import packages from npm:

```ts script
import { format } from 'date-fns'
import { z } from 'zod'
import _ from 'lodash'

export function formatDate(date: Date): string {
  return format(date, 'MMMM dd, yyyy')
}

export const userSchema = z.object({
  name: z.string(),
  email: z.string().email()
})

export function uniqueBy<T>(array: T[], key: keyof T): T[] {
  return _.uniqBy(array, key)
}
```

Import from Other MDX Files

Import from other MDX documents:

```ts script
import { formatCurrency } from 'https://mdx.sh/utils.do/currency'
import { Hero } from 'https://mdx.sh/components.do/hero'

export function displayPrice(amount: number): string {
  return formatCurrency(amount, 'USD')
}
```

Import Local Components

Import from same document:

```tsx
function Button({ children, onClick }) {
  return (
    <button onClick={onClick} className="btn">
      {children}
    </button>
  )
}

export function Hero() {
  return (
    <div>
      <h1>Welcome</h1>
      <Button onClick={() => alert('Clicked!')}>
        Get Started
      </Button>
    </div>
  )
}
```

Preview Integration

Render on MDX.as

MDX.sh documents can be previewed on mdx.as:

Output Formats

MDX.sh content can be rendered in different formats:

# Render as landing page
open https://mdx.as/landing-page/mystartup.co

# Render as site
open https://mdx.as/site/mystartup.co

# Render as documentation
open https://mdx.as/docs/mystartup.co

# Render as agent
open https://mdx.as/agent/mystartup.co

Custom Domains

Deploy to custom domains:

# Configure custom domain
curl -X POST https://mdx.sh/mystartup.co/domains \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"domain": "www.mystartup.com"}'

# Access via custom domain
open https://www.mystartup.com

Scheduling

Cron Jobs

Schedule script execution:

```ts script
// Run daily at midnight
export const schedule = '0 0 * * *'

export async function backupData() {
  const data = await fetchAllData()
  await uploadToS3(data)
  console.log('Backup completed')
}
```

Configure schedule:

curl -X POST https://mdx.sh/mystartup.co/schedule \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "script": "backupData",
    "schedule": "0 0 * * *"
  }'

Webhooks

Trigger scripts via webhooks:

```ts script
export async function onWebhook(payload: any) {
  console.log('Webhook received:', payload)

  // Process webhook
  if (payload.event === 'user.created') {
    await sendWelcomeEmail(payload.user.email)
  }

  return { success: true }
}
```

Register webhook:

curl -X POST https://mdx.sh/mystartup.co/webhooks \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "url": "https://mdx.sh/mystartup.co/webhooks/onWebhook",
    "events": ["user.created", "user.updated"]
  }'

Environment Variables

Access Environment Variables

Use environment variables in scripts:

```ts script
const apiKey = process.env.API_KEY
const dbUrl = process.env.DATABASE_URL

export async function fetchUsers() {
  const response = await fetch(`${dbUrl}/users`, {
    headers: {
      'Authorization': `Bearer ${apiKey}`
    }
  })
  return response.json()
}
```

Set environment variables:

curl -X POST https://mdx.sh/mystartup.co/env \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "API_KEY": "sk_live_...",
    "DATABASE_URL": "postgres://..."
  }'

Secrets Management

Store Secrets

Store sensitive data securely:

curl -X POST https://mdx.sh/mystartup.co/secrets \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "STRIPE_SECRET_KEY": "sk_live_...",
    "JWT_SECRET": "..."
  }'

Access in scripts:

```ts script
const stripeKey = process.env.STRIPE_SECRET_KEY
const jwtSecret = process.env.JWT_SECRET
```

Logging

Console Logs

Access console output:

Structured Logging

Use structured logging:

```ts script
export function processOrder(orderId: string) {
  console.log({
    level: 'info',
    message: 'Processing order',
    orderId,
    timestamp: new Date().toISOString()
  })

  try {
    // Process order
    console.log({
      level: 'info',
      message: 'Order completed',
      orderId
    })
  } catch (error) {
    console.error({
      level: 'error',
      message: 'Order failed',
      orderId,
      error: error.message
    })
  }
}
```

Monitoring

Metrics

Access execution metrics:

# Get metrics
curl https://mdx.sh/mystartup.co/metrics

# Response
{
  "executions": {
    "total": 1234,
    "success": 1200,
    "failed": 34
  },
  "duration": {
    "avg": 45,
    "p50": 40,
    "p95": 120,
    "p99": 250
  },
  "scripts": {
    "hello": { "executions": 500, "avg_duration": 23 },
    "users": { "executions": 734, "avg_duration": 67 }
  }
}

Health Check

Check runtime health:

curl https://mdx.sh/mystartup.co/health

# Response
{
  "status": "healthy",
  "uptime": 1234567,
  "version": "1.0.0",
  "lastExecution": "2024-01-15T12:00:00Z"
}

Security

Authentication

Protect endpoints with authentication:

```ts script
export const auth = {
  required: true,
  roles: ['admin', 'user']
}

export async function protectedFunction() {
  // Only accessible with valid token
  return { secret: 'data' }
}
```

Call with auth:

curl https://mdx.sh/mystartup.co/functions/protectedFunction \
  -H "Authorization: Bearer $TOKEN"

Rate Limiting

Configure rate limits:

```ts script
export const rateLimit = {
  requests: 100,
  window: '1m'
}

export function publicApi() {
  return { data: 'public' }
}
```

Deployment

Deploy to Production

Deploy MDX.sh document:

# Deploy
curl -X POST https://mdx.sh/mystartup.co/deploy \
  -H "Authorization: Bearer $TOKEN"

# Response
{
  "status": "deployed",
  "url": "https://mdx.sh/mystartup.co",
  "version": "1.0.1",
  "timestamp": "2024-01-15T12:00:00Z"
}

Rollback

Rollback to previous version:

curl -X POST https://mdx.sh/mystartup.co/rollback \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"version": "1.0.0"}'

Versions

List versions:

curl https://mdx.sh/mystartup.co/versions

# Response
[
  {
    "version": "1.0.1",
    "deployed": "2024-01-15T12:00:00Z",
    "active": true
  },
  {
    "version": "1.0.0",
    "deployed": "2024-01-14T10:00:00Z",
    "active": false
  }
]

Examples

Complete Example

---
$type: LandingPage
$context: https://schema.org
title: My Startup
description: Build amazing products
---

```ts script
// Configuration
export const config = {
  apiUrl: 'https://api.mystartup.co',
  version: '1.0.0'
}

// Utility functions
export function formatPrice(amount: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  }).format(amount)
}

// Data
export const pricing = [
  { name: 'Starter', price: 29 },
  { name: 'Pro', price: 99 }
]

// API endpoint
export async function subscribe(email: string) {
  const response = await fetch(`${config.apiUrl}/subscribe`, {
    method: 'POST',
    body: JSON.stringify({ email })
  })
  return response.json()
}
```

```tsx
// Components
export function Hero({ title, subtitle }) {
  return (
    <div className="hero">
      <h1>{title}</h1>
      <p>{subtitle}</p>
    </div>
  )
}

export function PricingCard({ plan }) {
  return (
    <div className="card">
      <h3>{plan.name}</h3>
      <p>{formatPrice(plan.price)}</p>
    </div>
  )
}
```

```ts test
import { describe, it, expect } from 'vitest'
import { formatPrice } from './script'

describe('formatPrice', () => {
  it('formats USD correctly', () => {
    expect(formatPrice(29)).toBe('$29.00')
  })
})
```

# My Startup

<Hero
  title="Build Amazing Products"
  subtitle="Ship faster with our platform"
/>

## Pricing

{pricing.map(plan => (
  <PricingCard key={plan.name} plan={plan} />
))}

Resources