Cursor rules are a powerful way to enhance your development workflow. In this guide, we'll walk through the basics of creating and using cursor rules.
Cursor rules are predefined patterns and behaviors that help you navigate and manipulate code more efficiently. They can be customized to fit your specific needs and preferences.
To create your first cursor rule, follow these steps:
// Example cursor rule configuration
{
"name": "TypeScript Auto-Import",
"pattern": "import\\s+{\\s*([\\w\\s,]+)\\s*}\\s+from\\s+['\"]([\\w\\-@/\\.]+)['\"];?",
"action": "suggest-imports",
"scope": ["typescript", "typescriptreact"]
}
Every cursor rule consists of several key components that define its behavior:
These rules help autocomplete common patterns:
{
"name": "React Component Template",
"trigger": "rfc",
"expansion": "import React from 'react';\n\nconst $1 = () => {\n return (\n <div>\n $0\n </div>\n );\n};\n\nexport default $1;",
"scope": ["javascript", "typescript", "jsx", "tsx"]
}
Rules that enforce consistent formatting:
{
"name": "Console Log Format",
"pattern": "console\\.log\\(([^)]+)\\)",
"replacement": "console.log('🐛 Debug:', $1)",
"scope": ["javascript", "typescript"]
}
Keep your imports clean and organized:
{
"name": "Group Imports",
"pattern": "^import.*$",
"action": "sort-imports",
"options": {
"groups": ["builtin", "external", "internal", "relative"],
"newlinesBetweenGroups": true
}
}
Cursor rules support variables that make them more flexible:
{
"name": "API Endpoint Creator",
"trigger": "api",
"expansion": "const ${1:endpoint} = async (${2:params}) => {\n const response = await fetch('/api/${1}', {\n method: '${3:GET}',\n headers: {\n 'Content-Type': 'application/json',\n },\n ${4:body: JSON.stringify(params),}\n });\n return response.json();\n};",
"scope": ["javascript", "typescript"]
}
Create rules that adapt based on context:
{
"name": "Smart Component Import",
"condition": "file.extension === 'tsx' && project.hasReact",
"pattern": "import ([A-Z]\\w+)",
"action": "add-component-props",
"template": "interface ${1}Props {\n // Add props here\n}\n\nconst ${1}: React.FC<${1}Props> = (props) => {"
}
Begin with basic rules and gradually add complexity:
{
"name": "Simple Console",
"trigger": "cl",
"expansion": "console.log($0)",
"scope": ["javascript", "typescript"]
}
Choose clear, descriptive names for your rules:
// ✅ Good
"name": "React Functional Component with Props"
// ❌ Bad
"name": "rfc"
Always test your regex patterns to ensure they work correctly:
// Test your patterns in the browser console
const pattern = /import\s+{\s*([\w\s,]+)\s*}\s+from\s+['"]([\/\w\-@.]+)['"]/;
const testString = "import { useState, useEffect } from 'react'";
console.log(pattern.test(testString)); // Should return true
Group related rules together:
{
"categories": {
"React": [
"React Functional Component",
"React Hook",
"React Context"
],
"TypeScript": [
"Interface Definition",
"Type Declaration",
"Generic Function"
],
"Testing": [
"Jest Test",
"React Testing Library",
"Mock Function"
]
}
}
{
"name": "Next.js Page",
"trigger": "nextpage",
"expansion": "import { NextPage } from 'next';\n\ninterface ${1:Home}Props {\n // Add props here\n}\n\nconst ${1}: NextPage<${1}Props> = (props) => {\n return (\n <div>\n <h1>${2:Page Title}</h1>\n $0\n </div>\n );\n};\n\nexport default ${1};",
"scope": ["typescript", "tsx"]
}
{
"name": "Express Route",
"trigger": "route",
"expansion": "app.${1:get}('/${2:path}', async (req, res) => {\n try {\n $0\n res.json({ success: true });\n } catch (error) {\n res.status(500).json({ error: error.message });\n }\n});",
"scope": ["javascript", "typescript"]
}
{
"name": "Try-Catch Block",
"trigger": "tryc",
"expansion": "try {\n $0\n} catch (error) {\n console.error('Error:', error);\n // Handle error appropriately\n}",
"scope": ["javascript", "typescript"]
}
{
"name": "JSDoc Function",
"trigger": "jsdoc",
"expansion": "/**\n * ${1:Description}\n * @param {${2:type}} ${3:param} - ${4:description}\n * @returns {${5:type}} ${6:description}\n * @example\n * ${7:example usage}\n */",
"scope": ["javascript", "typescript"]
}
Problem: Your rule doesn't activate when expected.
Solutions:
Problem: Rule triggers at wrong times or doesn't match intended text.
Solutions:
Problem: Too many rules slow down the editor.
Solutions:
# Export rules to a file
cursor --export-rules my-rules.json
# Import rules from a file
cursor --import-rules community-rules.json
Now that you understand the basics of cursor rules, here are some next steps:
Cursor rules are a powerful way to customize your development environment and boost productivity. Start with simple rules and gradually build more complex automation as you become comfortable with the system.
Remember, the best rules are those that solve real problems in your daily workflow. Take note of repetitive tasks and consider how rules might help automate them.
Happy coding! 🚀
Expert developer passionate about modern web technologies and AI-assisted development.
Get the latest articles and tutorials delivered to your inbox.