Claude
Skills
Sign in
Back

hasura-graphql-engine

Included with Lifetime
$97 forever

Complete guide for Hasura GraphQL Engine including instant GraphQL APIs, permissions, authentication, event triggers, actions, and production deployment

Backend & APIshasuragraphqlpermissionsauthenticationevent-triggersactionsremote-schemaspostgres

What this skill does


# Hasura GraphQL Engine Mastery

A comprehensive skill for building production-ready GraphQL APIs with Hasura. Master instant API generation, granular permissions, authentication integration, event-driven architectures, custom business logic, and remote schema stitching for modern applications.

## When to Use This Skill

Use Hasura GraphQL Engine when:

- Building GraphQL APIs rapidly without writing backend code
- Need instant CRUD APIs from existing PostgreSQL databases
- Implementing granular row-level and column-level security
- Building real-time applications with GraphQL subscriptions
- Integrating multiple data sources (databases, REST APIs, GraphQL services)
- Creating event-driven architectures with database triggers
- Extending GraphQL with custom business logic via Actions
- Implementing authentication and authorization at the API layer
- Building admin panels, dashboards, or internal tools quickly
- Migrating from REST to GraphQL without rewriting backend
- Needing production-ready features (caching, rate limiting, monitoring)
- Building multi-tenant SaaS applications with role-based access

## Core Concepts

### Instant GraphQL API Generation

Hasura's primary value proposition is **automatic GraphQL API generation** from your database schema:

- **Table Tracking**: Point Hasura at PostgreSQL tables to instantly get queries, mutations, and subscriptions
- **Relationship Detection**: Automatically infers foreign key relationships as GraphQL connections
- **Type Safety**: Database schema translates directly to GraphQL types
- **Zero Code**: No resolver writing, no ORM configuration, no boilerplate
- **Real-time by Default**: Every query automatically has a subscription counterpart

**How it works:**
1. Connect Hasura to your PostgreSQL database
2. Track tables in the Hasura Console
3. GraphQL API is immediately available with:
   - `query` - Fetch data with filtering, sorting, pagination
   - `mutation` - Insert, update, delete operations
   - `subscription` - Real-time data updates via WebSockets

### Metadata-Driven Architecture

Hasura is **metadata-driven**, not code-driven:

- **Metadata**: JSON/YAML configuration defining your API
- **Declarative**: Define what you want, not how to implement it
- **Version Control**: Metadata files can be committed to Git
- **CLI Migration**: Hasura CLI manages metadata and migrations
- **Programmatic Control**: Metadata API for automation

**Key metadata components:**
- Table tracking and relationships
- Permission rules
- Remote schemas
- Actions
- Event triggers
- Custom functions

### Permission System

Hasura's **permission system** is its most powerful feature, enabling fine-grained access control:

- **Role-Based**: Define permissions per GraphQL operation per role
- **Row-Level Security**: Control which rows users can access
- **Column-Level Security**: Hide sensitive columns from specific roles
- **Session Variables**: Dynamic permissions based on JWT claims or webhook data
- **Check Constraints**: Boolean expressions determining access

**Permission Types:**
- `select` - Read permissions
- `insert` - Create permissions
- `update` - Modify permissions
- `delete` - Remove permissions

### Authentication Integration

Hasura **delegates authentication** to your auth service but **handles authorization**:

- **JWT Mode**: Validate JWT tokens containing user claims
- **Webhook Mode**: Call webhook to get session variables
- **Session Variables**: `x-hasura-role`, `x-hasura-user-id`, custom claims
- **Multi-Provider**: Support Auth0, Firebase, Cognito, custom auth

**Auth Flow:**
1. User authenticates with your auth service (Auth0, Firebase, custom)
2. Auth service issues JWT with Hasura claims
3. Client sends JWT in Authorization header
4. Hasura validates JWT and extracts session variables
5. Permissions evaluated using session variables
6. GraphQL query executed with appropriate access control

### Event Triggers

**Event Triggers** enable event-driven architectures by invoking webhooks on database changes:

- **Database Events**: INSERT, UPDATE, DELETE triggers
- **Reliable Delivery**: At-least-once delivery with retries
- **Payload**: Old and new row data in JSON
- **Async Processing**: Long-running tasks, external integrations
- **Use Cases**: Send emails, sync to Elasticsearch, update cache, trigger workflows

### Actions

**Actions** extend Hasura with custom business logic:

- **Custom Mutations**: Define GraphQL mutations handled by your code
- **Custom Queries**: Add custom query logic beyond database access
- **REST Integration**: Call REST APIs from GraphQL
- **Type Safety**: Define input/output types in GraphQL SDL
- **Handler**: Your HTTP endpoint receives GraphQL variables

**Common use cases:**
- Payment processing
- Complex validations
- Third-party API calls
- Custom algorithms
- File uploads
- Email sending

### Remote Schemas

**Remote Schemas** enable schema stitching by merging external GraphQL APIs:

- **Schema Stitching**: Unify multiple GraphQL services
- **Type Extension**: Extend types with fields from remote schemas
- **Permissions**: Apply role-based permissions to remote schemas
- **Namespace**: Isolate remote schemas to avoid conflicts
- **Use Cases**: Microservices, legacy GraphQL APIs, third-party services

### Real-Time Subscriptions

Hasura provides **native GraphQL subscriptions**:

- **Live Queries**: Automatically push updates when data changes
- **WebSocket Protocol**: Efficient bi-directional communication
- **Multiplexing**: Optimize subscriptions for many concurrent clients
- **Filtering**: Subscribe to specific subsets of data
- **Polling Fallback**: HTTP-based streaming for restricted networks

## Permission System Deep Dive

### Row-Level Security

Row-level security uses **boolean check expressions** to filter accessible rows:

**Example: Users can only see their own data**
```json
{
  "check": {
    "user_id": {
      "_eq": "X-Hasura-User-Id"
    }
  }
}
```

**Example: Multi-tenant data isolation**
```json
{
  "check": {
    "tenant_id": {
      "_eq": "X-Hasura-Tenant-Id"
    }
  }
}
```

**Example: Complex access rules**
```json
{
  "check": {
    "_or": [
      {
        "user_id": {
          "_eq": "X-Hasura-User-Id"
        }
      },
      {
        "is_public": {
          "_eq": true
        }
      }
    ]
  }
}
```

### Column-Level Security

Control which columns are visible per role:

**Example: Hide sensitive user fields**
```yaml
select:
  columns:
    - id
    - username
    - email
    # password_hash is hidden
    # created_at is hidden
```

**Example: Different views for different roles**
```yaml
# Admin role sees all columns
select:
  columns: "*"

# User role sees limited columns
select:
  columns:
    - id
    - username
    - profile_picture
```

### Insert Permissions

Control what data can be inserted:

**Example: Set user_id from session**
```json
{
  "check": {
    "user_id": {
      "_eq": "X-Hasura-User-Id"
    }
  },
  "set": {
    "user_id": "X-Hasura-User-Id"
  }
}
```

**Example: Validate ownership before insert**
```json
{
  "check": {
    "project": {
      "owner_id": {
        "_eq": "X-Hasura-User-Id"
      }
    }
  }
}
```

### Update Permissions

Control which rows can be updated and what values can be set:

**Example: Update own data only**
```json
{
  "filter": {
    "user_id": {
      "_eq": "X-Hasura-User-Id"
    }
  },
  "check": {
    "user_id": {
      "_eq": "X-Hasura-User-Id"
    }
  },
  "set": {
    "updated_at": "now()"
  }
}
```

**filter**: Which rows can be selected for update
**check**: Validation after update completes
**set**: Automatically set column values

### Delete Permissions

Control which rows can be deleted:

**Example: Delete own data only**
```json
{
  "filter": {
    "user_id": {
      "_eq": "X-Hasura-User-Id"
    }
  }
}
```

## Authentication Integration

### JWT Mode Configuration

Configure Hasura to validate JWT tokens:

**Environment Variable:**
```bash
HASURA_GRAPHQL

Related in Backend & APIs