Lesson

Level Up Cursor Hooks with TypeScript and Bun

Learn how to replace clunky Bash scripts with a robust TypeScript and Bun setup for creating powerful, custom Cursor Hooks.

Access
Included
Transcript
Needs source

Bash scripts work for basic hooks, but they quickly become unwieldy when you need to parse JSON, implement complex logic, or maintain the code over time. This lesson transforms your hook development workflow by introducing Bun—a fast JavaScript runtime that lets you write hooks in TypeScript.

You'll set up a dedicated Bun project for your hooks, learn how to handle the JSON payloads Cursor provides, and return properly formatted responses to control the AI's behavior. This approach gives you the full power of TypeScript and the Node.js ecosystem, making your hooks more maintainable, testable, and powerful.

Key Benefits:

  • Write hooks in a familiar, strongly-typed language (TypeScript).
  • Avoid the complexities of shell scripting and JSON manipulation in Bash.
  • Leverage the entire Node.js/Bun ecosystem within your hooks.
  • Simplify setup, as bun run handles script execution without needing chmod.

Building Your First TypeScript Hook

The workflow is straightforward. You'll create a dedicated directory for your hooks, initialize a Bun project, and write a TypeScript script that demonstrates controlling the AI.

  1. Initialize a Bun Project: Create a .cursor/hooks directory and initialize a new Bun project within it. This gives you a dedicated environment for your hook logic with TypeScript support out of the box.

    mkdir .cursor/hooks
    cd .cursor/hooks
    bun init
    
  2. Configure hooks.json: Update your .cursor/hooks.json to execute the TypeScript script using bun run. This command points to the entry file generated by Bun.

    {
      "version": 1,
      "hooks": {
        "beforeSubmitPrompt": [
          {
            "command": "bun run hooks/index.ts"
          }
        ]
      }
    }
    
  3. Handle Hook Output: Each hook type expects a specific JSON response structure. For beforeSubmitPrompt, you return an object with a continue property. Setting it to false blocks the AI from processing the prompt—a powerful demonstration of controlling the AI's behavior.

    const output = {
      continue: false,
    };
    
    console.log(JSON.stringify(output, null, 2));
    

With this foundation in place, you can create sophisticated automations that integrate seamlessly with Cursor, all while working in a familiar TypeScript environment with full access to the Node.js ecosystem.

Prompts Used

Do anything
Please say hello