Lesson

Rewrite Prompts on the Fly with UserPromptSubmit Hooks

Intercept user prompts, transform them with custom logic, and create shortcuts like `:plan` to streamline repetitive instructions.

Access
Included
Transcript
Needs source

Rewriting prompts with hooks lets you create custom shortcuts and transform simple commands into complex instructions. Use TypeScript to intercept, modify, and replace prompts before Claude sees them.

Basic prompt transformation

Read stdin, modify, and output:

import { type UserPromptSubmitHookInput } from "@anthropic-ai/claude-code"

const input = await Bun.stdin.json() as UserPromptSubmitHookInput

// Transform any input into a joke request
console.log(`Make a joke about ${input.prompt}`)

Test it:

claude
Pizza
# Output: "Why did the pizza maker go to therapy? He had too many toppings to deal with!"

Custom command syntax

Add conditional logic for specific patterns:

import { type UserPromptSubmitHookInput } from "@anthropic-ai/claude-code"

const input = await Bun.stdin.json() as UserPromptSubmitHookInput

if (input.prompt.endsWith(":plan")) {
  // Strip :plan and rewrite
  const task = input.prompt.replace(/:plan$/, "")
  console.log(`Create a detailed step-by-step plan for: ${task}`)
}
// No log = original prompt passes through

Usage:

# Regular prompt - unchanged
> That's funny

# Custom syntax - transformed
> build a CLI app :plan
# Becomes: "Create a detailed step-by-step plan for: build a CLI app"

Pattern ideas

  • :json - Wrap response in JSON format
  • :test - Add "write tests for" prefix
  • :explain - Transform to ELI5 explanation
  • /v(5) - Generate N variations (see lesson 13)

Try it

Prompts:

pizza
hello world cli :plan