Sistem Hooks

Kuasai Claude Code Hooks — 13 event siklus hidup, 3 jenis handler, 10+ resep praktis, dan konfigurasi enterprise

Diperbarui 2026-11-27

Butuh API key? Daftar →Endpoint & Base URL →

Di halaman ini

Hooks memungkinkan Anda menyisipkan logika sendiri di titik-titik penting dalam siklus hidup Claude Code — memformat kode secara otomatis, memblokir perintah berbahaya, mengirim notifikasi, menulis log audit. Hooks adalah salah satu mekanisme ekstensi Claude Code yang paling ampuh.


1. Konsep inti

Setiap hook memiliki tiga bagian:

Event (When)   →  Matcher (Which)     →  Handler (What)
PreToolUse        matcher: "Bash"        command: "check_safety.sh"
  • Event: kapan hook dijalankan (misalnya PreToolUse — sebelum sebuah tool berjalan)
  • Matcher: filter nama tool yang opsional (hanya Bash, atau hanya Write)
  • Handler: perintah shell, injeksi prompt, atau subagent

2. Daftar event lengkap

Event inti

Event Dijalankan Dapat memblokir Penggunaan umum
PreToolUse Sebelum sebuah tool berjalan Ya (exit 2) Intersepsi keamanan, validasi argumen
PostToolUse Setelah sebuah tool berjalan Tidak Format otomatis, logging
Notification Claude mengirim notifikasi Tidak Alert Slack / Feishu / DingTalk
Stop Claude menyelesaikan respons Tidak Pemeriksaan kualitas, commit otomatis
UserPromptSubmit Pengguna mengirim prompt Ya Injeksi konteks, pemeriksaan kebijakan
SessionStart Sesi dimulai Tidak Penyiapan lingkungan, pesan selamat datang

Event tambahan (baru di 2026)

Event Dijalankan Dapat memblokir Penggunaan umum
SubagentStop Sebuah subagent selesai Tidak Mengumpulkan hasil subagent
SubagentToolUse Sebuah subagent menggunakan tool Ya Membatasi izin subagent
FileChanged Sebuah file diubah Tidak Lint otomatis, memicu build
CwdChanged Direktori kerja berubah Tidak Memuat konfigurasi khusus direktori
ModelChange Model diganti Tidak Melacak pemakaian model
CompactComplete /compact selesai Tidak Pemrosesan pasca-compaction
ToolError Sebuah tool mengalami error Tidak Pengumpulan error, logika retry

3. Jenis handler

Jenis 1: Command (perintah shell)

Jenis yang paling umum — menjalankan perintah shell:

{
  "type": "command",
  "command": "npx prettier --write \"$FILEPATH\""
}

Environment variable:

Variabel Arti Tersedia di
$FILEPATH Path file yang sedang dioperasikan PreToolUse/PostToolUse
$TOOL_INPUT Input tool dalam bentuk JSON PreToolUse
$TOOL_NAME Nama tool PreToolUse/PostToolUse
$SESSION_ID Id sesi Semua
$NOTIFICATION_MESSAGE Isi notifikasi Notification

Input stdin: skrip hook juga menerima payload JSON di stdin yang berisi session_id, tool_name, dan tool_input. Bacalah saat Anda membutuhkan data terstruktur — ini lebih andal daripada mengurai environment variable.

Exit code:

  • 0: lanjutkan
  • 2: blokir operasi (hanya didukung di PreToolUse / UserPromptSubmit / SubagentToolUse)
  • selain itu: dianggap error tetapi tidak memblokir

Jenis 2: Prompt (injeksi prompt)

Menyuntikkan teks ke konteks Claude:

{
  "type": "prompt",
  "prompt": "Remember: every database operation must use a transaction"
}

Berguna untuk: menyuntikkan aturan proyek tambahan saat SessionStart.

Jenis 3: Subagent

Menjalankan subagent untuk menangani peristiwa:

{
  "type": "subagent",
  "prompt": "Review the code that was just modified and check for security vulnerabilities"
}

Berguna untuk: tinjauan kualitas kode otomatis setelah PostToolUse.


4. Konfigurasi

Konfigurasikan di .claude/settings.json (level proyek) atau ~/.claude/settings.json (level pengguna):

{
  "hooks": {
    "EventName": [
      {
        "matcher": "tool name (optional, | separates several)",
        "hooks": [
          {
            "type": "command|prompt|subagent",
            "command": "..."
          }
        ]
      }
    ]
  }
}

5. Resep praktis

Resep 1: format otomatis setelah file disimpan

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$FILEPATH\" 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

Resep 2: blokir perintah shell berbahaya

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$TOOL_INPUT\" | grep -qE 'rm -rf /|sudo rm|git push --force|DROP TABLE|DROP DATABASE' && echo 'dangerous command blocked' && exit 2 || exit 0"
          }
        ]
      }
    ]
  }
}

Resep 3: lindungi file sensitif

⚠️ Pencocokan regex pada Resep 2 / 3 adalah peringatan tambahan, bukan batas izin atau sandbox: $TOOL_INPUT dapat dilewati dengan escaping, newline, ekspansi variabel, atau skrip pembungkus. Isolasi sesungguhnya bergantung pada aturan izin (permissions.deny), sandboxing, dan menjalankan dengan hak istimewa minimum — jangan pernah hanya mengandalkan regex hook.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$TOOL_INPUT\" | grep -qE '\\.env|\\.env\\.|credentials|secrets?\\.ya?ml|private.key' && echo 'access to a sensitive file blocked' && exit 2 || exit 0"
          }
        ]
      }
    ]
  }
}

Resep 4: notifikasi sistem saat tugas selesai

macOS:

{
  "hooks": {
    "Notification": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"$NOTIFICATION_MESSAGE\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

Linux:

{
  "hooks": {
    "Notification": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "notify-send 'Claude Code' \"$NOTIFICATION_MESSAGE\""
          }
        ]
      }
    ]
  }
}

Resep 5: notifikasi Slack

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "curl -s -X POST https://hooks.slack.com/services/xxx/yyy/zzz -H 'Content-Type: application/json' -d '{\"text\": \"Claude Code task finished\"}'"
          }
        ]
      }
    ]
  }
}

Resep 6: perbaikan otomatis ESLint

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "npx eslint --fix \"$FILEPATH\" 2>/dev/null; npx prettier --write \"$FILEPATH\" 2>/dev/null; exit 0"
          }
        ]
      }
    ]
  }
}

Resep 7: log audit

{
  "hooks": {
    "PostToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) | session=$SESSION_ID | tool=$TOOL_NAME | file=$FILEPATH\" >> ~/.claude/audit.log"
          }
        ]
      }
    ]
  }
}

Resep 8: jalankan test secara otomatis

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$FILEPATH\" | grep -qE '\\.(ts|tsx|js|jsx)$' && echo \"$FILEPATH\" | grep -qvE '\\.test\\.|\\.spec\\.' && npx vitest related \"$FILEPATH\" --run 2>/dev/null || exit 0"
          }
        ]
      }
    ]
  }
}

Resep 9: lindungi file migrasi

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$FILEPATH\" | grep -qE 'migrations/|alembic/versions/' && echo 'editing an existing migration is not allowed, create a new one' && exit 2 || exit 0"
          }
        ]
      }
    ]
  }
}

Resep 10: suntikkan konteks saat sesi dimulai

{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Important: this project is mid-way through a v3.0 rewrite. All new code must use React Server Components; the pages/ directory is no longer supported."
          }
        ]
      }
    ]
  }
}

6. Hooks Enterprise

Konfigurasi managed-settings.d/

Administrator Enterprise dapat menegakkan kebijakan keamanan seluruh organisasi melalui direktori managed-settings.d/:

# Create a policy file in the enterprise management directory
mkdir -p /etc/claude-code/managed-settings.d/
// /etc/claude-code/managed-settings.d/security.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "/opt/claude-policy/check_command.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "/opt/claude-policy/audit_log.sh"
          }
        ]
      }
    ]
  }
}

Kebijakan Enterprise tidak dapat ditimpa oleh konfigurasi tingkat pengguna atau proyek.


7. Debugging

Mode verbose

Tekan Ctrl+O untuk mengaktifkan mode verbose, yang menampilkan:

  • kapan setiap hook dijalankan
  • stdout/stderr dari skrip hook
  • exit code hook

Masalah umum

Masalah Penyebab Perbaikan
Hook tidak pernah dijalankan Salah ketik di matcher Periksa kapitalisasi nama tool: Bash, Write, Edit, Read
Hook memblokir pekerjaan normal Logika exit code salah Pastikan jalur normal adalah exit 0 dan hanya blokir dengan exit 2
Hook lambat Skrip memakan waktu terlalu lama Hook sebaiknya selesai dalam 1–2 detik; jalankan tugas panjang di latar belakang
Environment variable kosong Event tersebut tidak menyediakannya Periksa tabel di atas untuk melihat variabel yang disediakan event

Uji skrip hook

Uji secara manual di terminal sebelum memasukkannya ke konfigurasi:

# Simulate the PreToolUse environment variables
FILEPATH="src/main.ts" TOOL_INPUT="rm -rf /" bash -c 'echo "$TOOL_INPUT" | grep -qE "rm -rf" && echo "blocked" && exit 2 || exit 0'

8. Dibandingkan dengan Codex Hooks

Claude Code Hooks Codex Hooks
Jumlah event 13 Lebih sedikit
Konfigurasi settings.json config.toml
Jenis handler command/prompt/subagent command
Manajemen enterprise managed-settings.d/ Tidak ada
Pemblokiran exit code 2 Terbatas

Langkah berikutnya

Mulai dengan QCode

Satu API key untuk Claude Code, Codex, dan lainnya — ditagih per token, harga per model di qcode.cc/models

Enterprise →