Custom Slash Commands in Claude Code: Build Your Own
By Learnia Team
Custom Slash Commands in Claude Code: Build Your Own
This article is written in English. Our training modules are available in French.
Built-in slash commands cover common operations, but every team has unique workflows. Custom commands let you package complex prompts into simple triggers—turn multi-step processes into single commands that anyone can run.
Why Custom Commands?
Without custom commands, you repeat yourself:
> Review this code following our style guide. Check for:
- ESLint compliance
- TypeScript strict mode compatibility
- Our naming conventions from CONTRIBUTING.md
- Performance patterns we use
- Security vulnerabilities
Run the tests after suggesting fixes.
With custom commands:
> /code-review
Same result, zero typing. And your entire team uses the exact same process.
Command File Structure
Custom commands are markdown files in
.claude/commands/:
- →project/.claude/commands/deploy.md
- →project/.claude/commands/code-review.md
- →project/.claude/commands/generate-docs.md
Basic Command
<!-- .claude/commands/hello.md -->
---
description: Say hello
---
Say hello to the user and introduce yourself.
Usage:
/hello
Command with Parameters
<!-- .claude/commands/create-component.md -->
---
description: Create a React component
---
Create a new React component named $COMPONENT_NAME in the src/components folder.
Include:
- TypeScript types
- CSS module for styling
- Unit tests in __tests__ folder
- Storybook story
Usage:
/create-component Button
The
$COMPONENT_NAME becomes "Button".
Frontmatter Options
The YAML frontmatter configures command behavior:
---
description: Short description shown in /help
allowed-tools: Tool1, Tool2(pattern)
---
description (required)
Appears in command listings:
> /help
Custom Commands:
/deploy Deploy to staging environment
/code-review Review code with team standards
/generate-docs Generate API documentation
allowed-tools (optional)
Restricts which tools the command can use:
---
description: Safe documentation generator
allowed-tools: Read, Write(docs/**)
---
Generate documentation for the current project.
This command can only read files and write to the docs folder.
Tool patterns:
| Pattern | Meaning |
|---|---|
| All read operations |
| Write only to docs folder |
| Only npm commands |
| Edit only src files |
Creating Your First Command
Step 1: Create the Commands Folder
mkdir -p .claude/commands
Step 2: Write the Command File
<!-- .claude/commands/review.md -->
---
description: Review code following team standards
allowed-tools: Read, Bash(npm:test), Bash(npm:lint)
---
Review the current changes following our team standards:
## Code Quality
- Check ESLint compliance
- Verify TypeScript types are correct
- Look for unused imports/variables
## Style Guide
- Follow naming conventions in CONTRIBUTING.md
- Ensure consistent formatting
## Security
- Check for hardcoded secrets
- Look for SQL injection vulnerabilities
- Verify input validation
## Performance
- Identify N+1 queries
- Check for unnecessary re-renders
- Look for memory leaks
After review, run `npm test` and `npm run lint` to verify changes.
Step 3: Use the Command
> /review
Claude follows your template exactly.
Parameter Substitution
Commands support dynamic values using
$PARAMETER_NAME:
Single Parameter
<!-- .claude/commands/test.md -->
---
description: Run tests for a specific module
---
Run tests for the $MODULE module:
1. Find all test files in src/$MODULE
2. Run `npm test -- --testPathPattern=$MODULE`
3. Summarize results
Usage:
> /test auth
> /test payments
Multiple Parameters
<!-- .claude/commands/migrate.md -->
---
description: Create database migration
---
Create a new database migration:
- Name: $MIGRATION_NAME
- Type: $TYPE (create_table, alter_table, add_index)
Generate the migration file and corresponding rollback.
Usage:
> /migrate add_user_avatar alter_table
Default Values
<!-- .claude/commands/build.md -->
---
description: Build for environment
---
Build the project for $ENV environment.
$ENV defaults to "development" if not specified.
Context Variables
Commands can reference contextual information:
| Variable | Description |
|---|---|
| Currently active file |
| Selected text in IDE |
| All arguments as string |
<!-- .claude/commands/explain.md -->
---
description: Explain selected code
---
Explain this code in detail:
$SELECTION
Cover:
- What it does
- How it works
- Why it's written this way
Real-World Command Examples
Code Review Command
<!-- .claude/commands/code-review.md -->
---
description: Comprehensive code review
allowed-tools: Read, Bash(git:diff*), Bash(npm:test), Bash(npm:lint)
---
Perform a thorough code review of recent changes.
## 1. Gather Changes
Run `git diff HEAD~1` to see recent changes.
## 2. Review Checklist
### Logic & Correctness
- [ ] Does the code do what it's supposed to?
- [ ] Are edge cases handled?
- [ ] Is error handling appropriate?
### Code Quality
- [ ] Is the code readable and well-organized?
- [ ] Are functions/methods appropriately sized?
- [ ] Is there unnecessary duplication?
### Testing
- [ ] Are new features tested?
- [ ] Do existing tests still pass?
### Security
- [ ] Is user input validated?
- [ ] Are there any exposed secrets?
- [ ] Are there SQL injection risks?
## 3. Run Verification
Run `npm test` and `npm run lint`.
## 4. Summary
Provide a summary with:
- Overall assessment (Approve/Request Changes)
- List of issues found
- Suggestions for improvement
Deploy Command
<!-- .claude/commands/deploy.md -->
---
description: Deploy to staging
allowed-tools: Bash(npm:*), Bash(git:*), Bash(docker:*)
---
Deploy the current branch to staging:
## Pre-flight Checks
1. Ensure all tests pass: `npm test`
2. Check for uncommitted changes: `git status`
3. Verify on correct branch
## Build
1. Run production build: `npm run build`
2. Build Docker image: `docker build -t app:staging .`
## Deploy
1. Push image: `docker push registry/app:staging`
2. Update staging: `kubectl rollout restart deployment/app -n staging`
## Verify
1. Wait for rollout: `kubectl rollout status deployment/app -n staging`
2. Check health endpoint
3. Run smoke tests
## Report
Summarize:
- Commit deployed
- Time taken
- Any issues encountered
API Endpoint Generator
<!-- .claude/commands/create-endpoint.md -->
---
description: Generate a new API endpoint
allowed-tools: Read, Write, Edit
---
Create a new REST API endpoint:
## Endpoint Details
- Resource: $RESOURCE
- Method: $METHOD (GET, POST, PUT, DELETE)
## Generate Files
### Route Handler
Create `src/routes/$RESOURCE.ts`:
- Express/Fastify route handler
- Input validation with Zod
- Error handling middleware
### Service Layer
Create `src/services/$RESOURCE.service.ts`:
- Business logic
- Database operations
- Proper error types
### Tests
Create `src/__tests__/$RESOURCE.test.ts`:
- Unit tests for service
- Integration tests for route
- Mock database calls
### Types
Add types to `src/types/$RESOURCE.ts`:
- Request/response interfaces
- Domain models
## Documentation
Update `docs/api.md` with new endpoint documentation.
Usage:
> /create-endpoint users POST
> /create-endpoint products GET
Documentation Generator
<!-- .claude/commands/document.md -->
---
description: Generate documentation for a file
allowed-tools: Read, Write(docs/**)
---
Generate comprehensive documentation for $FILE:
## Analysis
1. Read the file and understand its purpose
2. Identify all exports (functions, classes, types)
3. Trace dependencies
## Documentation Output
Create `docs/$FILE.md` with:
### Overview
- File purpose
- When to use it
- Dependencies
### API Reference
For each export:
- Description
- Parameters with types
- Return value
- Example usage
### Examples
Provide 2-3 practical examples showing common use cases.
### Related
Link to related documentation files.
User-Level Commands
Personal commands go in
~/.claude/commands/:
- →~/.claude/commands/my-workflow.md
- →~/.claude/commands/quick-fix.md
User commands are available in all projects.
Personal Productivity Command
<!-- ~/.claude/commands/standup.md -->
---
description: Generate standup update
allowed-tools: Read, Bash(git:log*)
---
Generate my daily standup update:
## Yesterday
Run `git log --oneline --since="yesterday" --author="<my-email>"` and summarize what I worked on.
## Today
Based on:
- Open TODOs in the codebase
- Recent branch names
- Uncommitted changes
Suggest what I should focus on today.
## Blockers
Check for:
- Failing tests
- Merge conflicts
- Pending reviews
Format as:
---
**Yesterday:** <summary>
**Today:** <plan>
**Blockers:** <issues or "None">
---
Command Organization
By Feature
Organize commands in subfolders:
- →auth/ -
,add-oauth.mdupdate-session.md - →api/ -
,create-endpoint.mddocument-api.md - →testing/ -
,unit-test.mde2e-test.md
Subfolders become command prefixes:
> /auth/add-oauth
> /api/create-endpoint
By Role
Organize by team role:
- →dev/ -
,review.mdrefactor.md - →qa/ -
,test-plan.mdbug-report.md - →devops/ -
,deploy.mdrollback.md
Team Command Sharing
Version Control
Commit
.claude/commands/ to your repository:
git add .claude/commands/
git commit -m "Add team Claude Code commands"
Everyone gets the same commands automatically.
Command Standards
Create a README for your commands:
<!-- .claude/commands/README.md -->
# Team Commands
## Development
- `/review` - Code review with team standards
- `/create-component` - Generate React component
## DevOps
- `/deploy staging` - Deploy to staging
- `/deploy production` - Deploy to production (requires approval)
## Testing
- `/test-unit` - Run unit tests
- `/test-e2e` - Run end-to-end tests
## Adding Commands
1. Create a markdown file in `.claude/commands/`
2. Follow the template in `_template.md`
3. Submit a PR for team review
Advanced Patterns
Command Chaining
Reference other commands in your prompts:
<!-- .claude/commands/release.md -->
---
description: Full release process
---
Perform a complete release:
1. First, run the code review process (like /review)
2. Update version in package.json
3. Generate changelog from commits
4. Build for production (like /build production)
5. Create git tag
6. Deploy (like /deploy production)
Conditional Logic
Use prompts to guide conditional behavior:
<!-- .claude/commands/fix.md -->
---
description: Fix issues based on type
---
Fix the following issue: $ISSUE_TYPE
If $ISSUE_TYPE is "lint":
- Run npm run lint:fix
- Review and commit changes
If $ISSUE_TYPE is "test":
- Run failing tests
- Fix the failures
- Verify all tests pass
If $ISSUE_TYPE is "type":
- Run TypeScript compiler
- Fix type errors
- Ensure strict mode compliance
Interactive Commands
Commands can ask for more input:
<!-- .claude/commands/refactor.md -->
---
description: Interactive refactoring session
---
Start an interactive refactoring session.
First, ask the user:
1. What file or component to refactor?
2. What's the goal of the refactoring?
3. Are there any constraints?
Then:
1. Analyze the current code
2. Propose a refactoring plan
3. Wait for approval
4. Implement changes incrementally
5. Run tests after each change
Debugging Commands
Test Your Command
Run with verbose output:
claude --verbose
> /my-command
Common Issues
Command not found:
- →Check file is in
.claude/commands/ - →Verify filename ends in
.md - →Ensure frontmatter has
description
Parameters not substituting:
- →Use exact format:
$PARAMETER_NAME - →Check for typos in variable names
- →Ensure arguments are provided in order
Permission errors:
- →Review
restrictionsallowed-tools - →Check project permission settings
- →Use
to debug/permissions
Integration with Other Features
Commands + Hooks
Trigger hooks from commands:
<!-- .claude/commands/safe-deploy.md -->
---
description: Deploy with safety hooks
allowed-tools: Bash(npm:*), Bash(git:*), Bash(docker:*)
---
Deploy to production with all safety checks.
This command relies on our PreToolUse hooks to:
- Validate deployment approvals
- Check for required tags
- Notify team via Slack
See Claude Code Hooks: Automate Your Development Workflow.
Commands + MCP
Use MCP tools in commands:
<!-- .claude/commands/sync-issues.md -->
---
description: Sync GitHub issues
allowed-tools: mcp__github__*, Read, Write
---
Sync GitHub issues with local tracking:
1. Use GitHub MCP to fetch open issues
2. Update local TODO.md with issue list
3. Mark completed issues as done
See Model Context Protocol (MCP) for Claude Code: Complete Guide.
Commands + Sub-Agents
Spawn specialized agents:
<!-- .claude/commands/deep-analysis.md -->
---
description: Deep codebase analysis
---
Perform a deep analysis of the codebase:
Use the Explore sub-agent to:
1. Map all modules and dependencies
2. Identify architectural patterns
3. Find potential issues
Then synthesize findings into a report.
See Claude Code Sub-Agents: Orchestrating Complex Tasks.
Key Takeaways
- →
Commands are markdown files: Simple to create, version, and share.
- →
Use parameters for flexibility:
makes commands reusable.$PARAM_NAME - →
Restrict tools for safety:
limits what commands can do.allowed-tools - →
Commit team commands: Share via version control for consistency.
- →
Combine with other features: Commands integrate with hooks, MCP, and sub-agents.
Build Effective Prompts for Your Commands
Custom commands are only as good as the prompts inside them. Learn to write prompts that get consistent results.
In our Module 3 — Prompt Engineering Basics, you'll learn:
- →Core principles of effective prompting
- →Structure and clarity techniques
- →Iterative prompt refinement
- →Common patterns and anti-patterns
Module 3 — Chain-of-Thought & Reasoning
Master advanced reasoning techniques and Self-Consistency methods.