15 Prompts for Cursor: Mastering AI-Assisted Development in Your IDE

Introduction

Cursor has redefined the developer experience by embedding AI directly into the code editor. Unlike traditional autocomplete tools, Cursor understands your project context, your coding style, and even your intentions. However, the magic lies in how you prompt it. Whether you're using autocomplete, chat, or command mode, the quality of your output depends on the precision of your prompts. This article provides 15 battle-tested prompts across basic, advanced, and expert categories, each with a real-world example and the resulting code. By the end, you'll be able to turn Cursor into a force multiplier for your daily workflow.

Basic Prompts (Autocomplete & Quick Fixes)

1. Generate a Function from a Comment

Task: Write a clear comment describing the function, then let Cursor autocomplete the implementation.

Prompt: // Returns the sum of all even numbers in an array

Result:

function sumEvenNumbers(arr) {
  return arr.filter(num => num % 2 === 0).reduce((acc, curr) => acc + curr, 0);
}

This is the simplest way to accelerate boilerplate. Cursor reads the comment and generates idiomatic code. For best results, be specific about the data type and expected behavior.

2. Refactor a Code Block Inline

Task: Select a block of messy code and ask Cursor to refactor it within the autocomplete popup.

Prompt: (Select the old code and type) // Refactor this to use async/await

Result:

// Old: callback-based
fetchData(function(err, data) {
  if (err) console.error(err);
  else process(data);
});

// New:
async function handleData() {
  try {
    const data = await fetchData();
    process(data);
  } catch (err) {
    console.error(err);
  }
}

This works best when you give a clear transformation rule. Cursor understands common patterns like callbacks to promises, loops to map/filter, or class components to hooks.

3. Complete a Test Case Pattern

Task: Start a test file and let Cursor infer the next test from context.

Prompt: (In a test file after writing a test for add()) test('subtracts two numbers', () => {

Result:

test('subtracts two numbers', () => {
  expect(subtract(5, 3)).toBe(2);
});

Cursor uses the surrounding imports and previous test structure to guess the implementation. This is a huge time-saver when writing unit tests for similar functions.

4. Generate a Regex from Natural Language

Task: Ask Cursor to create a regex based on a plain English description.

Prompt: // regex to match email addresses

Result:

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

You can also use the chat mode for more complex patterns: "Create a regex that matches US phone numbers with optional dashes."

Advanced Prompts (Chat & Multi-file Edits)

5. Explain and Fix a Bug

Task: Paste an error message into Cursor Chat and ask for an explanation and fix.

Prompt: "I get 'TypeError: Cannot read property 'length' of undefined' at line 45. Here's the code: [paste code]. What's wrong?"

Result:
Cursor will identify that the variable users might be undefined before calling .length. It will suggest a guard clause or optional chaining: users?.length || 0.

6. Generate a Full API Endpoint with Validation

Task: Ask Cursor Chat to create an Express route with input validation.

Prompt: "Create a POST /api/users endpoint that accepts name, email, and age. Validate that name is non-empty, email is valid, and age is between 18 and 120. Return appropriate error messages."

Result:

const express = require('express');
const router = express.Router();

router.post('/api/users', (req, res) => {
  const { name, email, age } = req.body;
  const errors = [];
  if (!name || name.trim() === '') errors.push('Name is required');
  if (!email || !email.includes('@')) errors.push('Valid email is required');
  if (age < 18 || age > 120) errors.push('Age must be between 18 and 120');
  if (errors.length > 0) return res.status(400).json({ errors });
  // ... save to database
  res.status(201).json({ success: true });
});

This prompt demonstrates Cursor's ability to understand multiple constraints and generate production-ready code.

7. Create a Migration Script from a Schema

Task: Provide a database schema and ask Cursor to write the migration SQL.

Prompt: "Here is a Prisma schema for a blog. Write a SQL migration to add a 'comments' table with id, content, postId, and createdAt."

Result:

CREATE TABLE comments (
  id SERIAL PRIMARY KEY,
  content TEXT NOT NULL,
  "postId" INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
  "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_comments_postId ON comments("postId");

Cursor understands foreign keys and indexing best practices from the schema context.

8. Convert Between Languages or Frameworks

Task: Ask Cursor to translate code from one language to another.

Prompt: "Convert this Python function to TypeScript: def add(a, b): return a + b"

Result:

function add(a: number, b: number): number {
  return a + b;
}

For framework migrations, like Vue to React, Cursor can translate lifecycle methods to hooks and templates to JSX.

Expert Prompts (Command Mode & Complex Workflows)

9. Refactor a File with a Specific Pattern

Task: Use Cursor's command mode (Cmd+K or Ctrl+K) to apply a global refactor.

Prompt: /refactor Replace all switch statements with object literals in this file

Result:
Before:

function getColor(code) {
  switch(code) {
    case 1: return 'red';
    case 2: return 'blue';
    default: return 'unknown';
  }
}

After:

const colorMap = { 1: 'red', 2: 'blue' };
function getColor(code) {
  return colorMap[code] || 'unknown';
}

This is one of the most powerful features — you can refactor entire files with a single command.

10. Generate a Complete Component with Tests

Task: Ask Cursor to create a React component and its test file simultaneously.

Prompt: "Create a React component called UserCard that displays name, email, and avatar. Also generate a corresponding Jest test file that checks rendering and props."

Result:

// UserCard.jsx
export default function UserCard({ name, email, avatar }) {
  return (
    <div className="user-card">
      <img src={avatar} alt={name} />
      <h2>{name}</h2>
      <p>{email}</p>
    </div>
  );
}

// UserCard.test.jsx
import { render, screen } from '@testing-library/react';
import UserCard from './UserCard';

test('renders user card with props', () => {
  render(<UserCard name="John" email="john@test.com" avatar="pic.jpg" />);
  expect(screen.getByText('John')).toBeInTheDocument();
});

Cursor can handle multi-file generation when you specify the file names and structure.

11. Debug a Race Condition

Task: Describe a concurrency issue and ask Cursor to fix it.

Prompt: "This Node.js server sometimes returns stale data because two requests update the same cache simultaneously. Fix it using a mutex."

Result:

const { Mutex } = require('async-mutex');
const cacheMutex = new Mutex();

async function updateCache(key, value) {
  const release = await cacheMutex.acquire();
  try {
    // critical section
    cache[key] = value;
  } finally {
    release();
  }
}

Cursor suggests specific libraries and patterns based on the environment.

12. Create a CLI Tool

Task: Ask Cursor to generate a command-line interface with argument parsing.

Prompt: "Create a Node.js CLI tool called 'file-summary' that accepts a directory path and prints the number of files, total size, and file types."

Result:

#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const dir = process.argv[2];

if (!dir) {
  console.error('Usage: file-summary <directory>');
  process.exit(1);
}

const files = fs.readdirSync(dir);
let totalSize = 0;
const types = {};

files.forEach(file => {
  const stats = fs.statSync(path.join(dir, file));
  totalSize += stats.size;
  const ext = path.extname(file) || '(no extension)';
  types[ext] = (types[ext] || 0) + 1;
});

console.log(`Files: ${files.length}`);
console.log(`Total size: ${totalSize} bytes`);
console.log('Types:', types);

This prompt shows Cursor's ability to handle file system operations and produce a complete, runnable script.

13. Optimize a Slow Query

Task: Provide a slow SQL query and ask Cursor to optimize it.

Prompt: "This query takes 5 seconds on a 1M row table. Optimize it: SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE signup_date > '2024-01-01') ORDER BY created_at DESC;"

Result:

-- Use JOIN instead of subquery, and add index hints
SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.signup_date > '2024-01-01'
ORDER BY o.created_at DESC;
-- Also consider composite index on (customer_id, created_at)

Cursor explains the reasoning: subqueries are often slower than joins in MySQL, and indexes can dramatically reduce scan time.

14. Write a Dockerfile with Best Practices

Task: Ask Cursor to generate a production-ready Dockerfile.

Prompt: "Create a Dockerfile for a Node.js app that uses multi-stage builds, installs only production dependencies, and runs as a non-root user."

Result:

FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install --only=production

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]

This prompt demonstrates Cursor's knowledge of security (non-root user) and efficiency (multi-stage).

15. Generate a Complete API Client from OpenAPI Spec

Task: Paste an OpenAPI JSON snippet and ask Cursor to generate a JavaScript client.

Prompt: "Given this OpenAPI spec, generate a fetch-based JavaScript client for the /users endpoint with getUsers and createUser methods."

Result:

const BASE_URL = 'https://api.example.com';

export async function getUsers() {
  const res = await fetch(`${BASE_URL}/users`);
  if (!res.ok) throw new Error('Failed to fetch users');
  return res.json();
}

export async function createUser(userData) {
  const res = await fetch(`${BASE_URL}/users`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData),
  });
  if (!res.ok) throw new Error('Failed to create user');
  return res.json();
}

With the right prompt, Cursor can generate entire API layers from documentation.

Conclusion

Cursor is not just an autocomplete tool — it's an AI pair programmer that understands your codebase, your language, and your intent. The key to unlocking its full potential is crafting precise prompts. Start with simple comments for autocomplete, move to chat for complex features, and use command mode for large-scale refactors. The 15 prompts in this article cover the spectrum from beginner to expert, giving you a practical toolkit for daily development. Try them in your next project, and you'll find yourself writing less code and solving more problems. Happy coding!

← All posts

Comments