> ## Documentation Index
> Fetch the complete documentation index at: https://hyrex.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Quick Start

> Get started with the Hyrex TypeScript SDK

Get up and running with Hyrex in minutes.

## Prerequisites

* Node.js 16 or higher
* PostgreSQL 12+ (for FOSS) or Hyrex Cloud account

## 1. Install Hyrex

```bash theme={null}
npm i @hyrex/hyrex
```

## 2. Initialize a New Project

Use the interactive `hyrex init` command to set up a new project:

```bash theme={null}
npx @hyrex/hyrex init
```

This will guide you through:

* Choosing a project name
* Selecting deployment mode (Cloud or PostgreSQL)
* Configuring environment variables
* Creating project files

For manual database initialization (PostgreSQL mode only):

```bash theme={null}
export HYREX_DATABASE_URL="postgresql://user:password@localhost/dbname"
hyrex init-db hyrex-app.ts
```

## 3. Project Structure

After running `hyrex init`, you'll have:

```
your-project/
├── .env                # Environment configuration
├── .env.example        # Example environment configuration
├── .gitignore          # Git ignore file
├── app.ts              # Task definitions
├── hyrex-app.ts        # Hyrex app configuration
├── package.json        # Dependencies and scripts
├── tsconfig.json       # TypeScript configuration
└── README.md           # Project documentation
```

Example `app.ts`:

```typescript theme={null}
import { HyrexRegistry } from '@hyrex/hyrex';
import { getHyrexContext } from '@hyrex/hyrex';

export const hy = new HyrexRegistry();

// Define a simple hello world task
const helloWorldTask = hy.task({
    name: 'helloWorld',
    config: {
        queue: 'default',
        timeoutSeconds: 30,
    },
    func: async (input: { name?: string }) => {
        const ctx = getHyrexContext();
        const name = input.name || 'World';
        
        console.log(`Task ID: ${ctx.taskId}`);
        console.log(`Hello, ${name}! Welcome to Hyrex!`);
        
        // Simulate some work
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        return {
            message: `Successfully greeted ${name}`,
            timestamp: new Date().toISOString(),
            taskId: ctx.taskId
        };
    }
});
```

Example `hyrex-app.ts`:

```typescript theme={null}
import { HyrexApp } from '@hyrex/hyrex';
import { hy as appRegistry } from './app';

const hyrexApp = new HyrexApp({ 
    name: "My Cool App"
});

hyrexApp.addRegistry(appRegistry);
hyrexApp.init();
```

## 4. Send Tasks

Queue tasks for execution:

```typescript theme={null}
// In app.ts, add at the bottom:
if (process.argv.includes('--submit')) {
    helloWorldTask.send({ name: 'TypeScript User' })
        .then(taskId => {
            console.log(`Task submitted with ID: ${taskId}`);
            process.exit(0);
        })
        .catch(error => {
            console.error('Failed to submit task:', error);
            process.exit(1);
        });
}
```

Then run:

```bash theme={null}
npm run submit
# or
ts-node app.ts --submit
```

## 5. Run Workers

Start workers to process tasks:

```bash theme={null}
# Single worker
hyrex run-worker hyrex-app.ts

# Multiple workers (e.g., 4 workers)
hyrex run-worker hyrex-app.ts 4

# With specific queue pattern (glob patterns)
hyrex run-worker hyrex-app.ts --queue "data-*"

# With lifespan limit (seconds)
hyrex run-worker hyrex-app.ts --lifespan 3600
```

## 6. Monitor Tasks

<Tabs>
  <Tab title="Hyrex Cloud">
    Visit your dashboard at [hyrex.io/cloud](https://hyrex.io/cloud) to monitor tasks in real-time.
  </Tab>

  <Tab title="FOSS">
    Run Hyrex Studio locally:

    ```bash theme={null}
    hyrex studio

    # With verbose logging
    hyrex studio --verbose
    ```

    Open [https://local.hyrex.studio](https://local.hyrex.studio) in your browser.
  </Tab>
</Tabs>

## Complete Example

```typescript theme={null}
// app.ts
import { HyrexRegistry } from '@hyrex/hyrex';
import { getHyrexContext, HyrexKV } from '@hyrex/hyrex';

export const hy = new HyrexRegistry();

// Define a task with input validation
interface ProcessDataInput {
    fileUrl: string;
    outputFormat: 'json' | 'csv' | 'parquet';
}

const processDataTask = hy.task({
    name: 'processData',
    config: {
        queue: 'data-processing',
        maxRetries: 3,
        timeoutSeconds: 300
    },
    func: async (input: ProcessDataInput) => {
        const ctx = getHyrexContext();
        console.log(`Processing ${input.fileUrl} in task ${ctx.taskId}`);
        
        // Store progress in KV store
        await HyrexKV.set(`task-${ctx.taskId}-status`, 'downloading');
        
        // Simulate processing
        await new Promise(resolve => setTimeout(resolve, 3000));
        
        await HyrexKV.set(`task-${ctx.taskId}-status`, 'completed');
        
        return {
            status: 'completed',
            outputUrl: `s3://output/${ctx.taskId}.${input.outputFormat}`,
            processedAt: new Date().toISOString()
        };
    }
});

// Submit example
if (process.argv.includes('--submit')) {
    processDataTask.send({
        fileUrl: 'https://example.com/data.csv',
        outputFormat: 'json'
    }).then(taskId => {
        console.log(`Task queued with ID: ${taskId}`);
    });
}

export { processDataTask };
```

## NPM Scripts

The generated `package.json` includes helpful scripts:

```json theme={null}
{
  "scripts": {
    "worker": "hyrex run-worker hyrex-app.ts",
    "worker:multi": "hyrex run-worker hyrex-app.ts 4",
    "init-db": "hyrex init-db hyrex-app.ts",
    "submit": "ts-node app.ts --submit"
  }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Tasks" icon="list-check" href="/docs/reference/typescript/tasks">
    Learn about task configuration
  </Card>

  <Card title="Workflows" icon="diagram-project" href="/docs/reference/typescript/workflows">
    Build complex workflows
  </Card>
</CardGroup>
