Claude Code for Salesforce Apex: Write and Debug Apex Faster in 2026
By Kushal Magar · April 25, 2026 · 14 min read
Salesforce Apex development has a well-known tax: boilerplate. Every trigger needs a handler class. Every batch job needs a start, execute, and finish method. Every test class needs data setup, assertions, and bulk coverage. Claude Code eliminates that tax — writing production-ready Apex from a plain-English prompt, with governor limit awareness built in.
This guide is for Salesforce developers who want to move faster without cutting corners. It covers how Claude Code connects to your org, the exact prompts that generate deployable triggers, batch jobs, and test classes, and the deployment workflow that keeps a human in the loop. No other post on this topic includes working code prompts — this one does.
What does Claude Code do for Salesforce Apex development?
Claude Code is an AI coding agent that writes, reviews, and debugs Salesforce Apex — including triggers, batch jobs, queueable classes, test classes, and SOQL queries — directly in your terminal or connected via the Salesforce DX MCP to your org. It understands governor limits, bulkification patterns, and Salesforce-specific deployment requirements, producing first drafts that compile and pass test coverage without manual scaffolding.
Key Takeaways
- Claude Code writes bulkified Apex by default — DML outside loops, collections over single-record operations, and proper trigger handler separation.
- Connect via the Salesforce DX MCP to give Claude Code direct access to your org's metadata, debug logs, and CLI commands — no manual copy-paste.
- Triggers, batch jobs, and test classes all have prompt templates that ship production-ready code on the first attempt approximately 85% of the time.
- Governor limits are baked in — Claude Code generates SOQL with bind variables, avoids queries inside loops, and respects heap size patterns.
- Never deploy directly to production. Use sandbox → validate → review → deploy. Claude Code can automate all steps except the final human sign-off.
- Test class generation is where Claude Code saves the most time — it writes both positive and negative test methods with proper mock data setup.
What Is Claude Code for Salesforce Apex?
Claude Code for Salesforce Apex is the use of Anthropic's AI coding agent to write, review, debug, and deploy Apex classes, triggers, batch jobs, and test classes — either through a terminal session or connected directly to a Salesforce org via the Model Context Protocol (MCP).
Unlike GitHub Copilot, which offers inline autocomplete, Claude Code is a full autonomous agent. It reads your existing codebase, understands Salesforce-specific patterns like trigger handler frameworks and queueable chains, and produces complete file-level output rather than line-by-line suggestions.
| Tool | Apex Compilation Rate | Full-file Generation |
|---|---|---|
| Claude Code | ~85% first attempt | Yes — full class files |
| GitHub Copilot | ~70% first attempt | Snippets only |
| Einstein for Developers | ~75% first attempt | Snippets + doc generation |
| ChatGPT | ~60% first attempt | Yes, but no org context |
The ~85% first-attempt compilation rate is observed across Salesforce developer community benchmarks (including Clientell's 10-task Claude Code test) and reflects Claude Code's Salesforce-specific training on trigger handler patterns, bulkification rules, and governor limit boundaries. The remaining ~15% typically requires one round of feedback — usually a missing import or an edge case in the business logic.
“Claude Code writes Apex the way a senior developer would — it thinks about bulkification, test coverage, and handler separation from the first line, not as an afterthought. That's what separates it from autocomplete tools.”
— Hema, Senior Salesforce Developer at Apex Hours
How Does Claude Code Connect to Salesforce?
Claude Code connects to Salesforce through two methods: the Salesforce DX MCP for full org integration, or a standalone terminal session for code generation without org access.
Method 1 — Salesforce DX MCP (Recommended)
The Salesforce DX MCP gives Claude Code direct access to your org: it can read metadata, retrieve existing Apex classes, run sf apex run test, deploy to scratch orgs, and parse debug logs.
Install the MCP, authenticate to your sandbox, and Claude Code operates as a full Salesforce developer — reading your existing trigger handlers before writing new ones, checking for naming conflicts, and validating deployments without leaving the terminal.
Method 2 — Standalone Terminal Session
Without the MCP, Claude Code generates Apex from a prompt alone. You paste the output into VS Code or your Salesforce CLI project, then deploy manually. This works well for greenfield classes where you don't need org context.
For any code that modifies existing logic — trigger extensions, handler updates, batch job modifications — use the MCP. It eliminates the risk of Claude Code writing code that conflicts with existing class structure.
Sandbox-first rule:
Always authenticate Claude Code to a sandbox or scratch org — never directly to production. As of 2026, every Salesforce Developer Edition org includes a free Agentforce Vibes IDE with Claude Sonnet as the default coding model and a hosted MCP server. Use that as your starting point.
How Do You Write Apex Triggers With Claude Code?
Apex triggers are where Claude Code delivers the most immediate productivity gain. A well-structured trigger — thin trigger body, handler class, interface, and factory pattern — takes 45+ minutes to scaffold manually. Claude Code produces the full stack in under two minutes.
The key is specificity in your prompt. Vague prompts produce generic code. Specific prompts produce deployable code.
Prompt Template: Apex Trigger + Handler
Write a bulkified Apex trigger and handler class for the Opportunity object. Requirements: - Trigger fires on: before insert, before update, after insert, after update - Business logic: when Opportunity Stage changes to 'Closed Won', create a related Onboarding Task record (custom object: Onboarding_Task__c) linked to the Account - Use a trigger handler framework: thin trigger body, separate TriggerHandler interface, and an OpportunityTriggerHandler class - All DML must be outside loops — use collections - Use Map<Id, Opportunity> oldMap for before/after comparison - Handle null Account IDs gracefully Org context: - Salesforce API version: 62.0 - Onboarding_Task__c has fields: Account__c (Lookup), Opportunity__c (Lookup), Status__c (Picklist: 'Not Started'), Name (Text) Output: Three separate files — OpportunityTrigger.trigger, TriggerHandler.cls, OpportunityTriggerHandler.cls
This prompt reliably produces three complete, deployable files. The handler class follows the standard TriggerHandler pattern used across enterprise Salesforce orgs, making the output compatible with existing codebases.
Common Trigger Patterns Claude Code Handles Well
- Before insert validation with custom error messages on specific fields
- After update field sync across parent-child relationships
- Duplicate prevention using SOQL deduplication checks
- Cross-object field updates using maps keyed by relationship IDs
- Recursive trigger prevention with static Boolean flags
How Do You Generate Batch Apex Jobs With Claude Code?
Batch Apex requires boilerplate that is tedious to write correctly: the Database.Batchable interface, a proper start method returning a query locator, chunked execute logic, and a finish method for notifications or chaining.
Claude Code writes this pattern correctly on the first attempt when you specify the scope size, the SOQL query, and what happens in each chunk.
Prompt Template: Batch Apex Job
Write a Batch Apex class that re-enriches stale Contact records. Requirements: - Query Contacts where LastModifiedDate < LAST_N_DAYS:90 AND Email != null - For each Contact in scope, call a named Callout method (EnrichmentService.enrichContact) that accepts a Contact and returns an enriched Contact — stub this method - Update enriched Contacts with bulk DML in the execute method - Batch scope: 200 records per chunk - Implement Database.Batchable<SObject> and Database.AllowsCallouts - In the finish method, send an email to a hardcoded admin email with job summary: total records processed, total updated, job ID - Add a schedulable wrapper class that can run this batch nightly at 2 AM API version: 62.0 Output: Two files — ContactEnrichmentBatch.cls and ContactEnrichmentScheduler.cls
Claude Code generates both files with correct interface implementations, proper scope handling, and the schedulable cron expression for nightly execution.
Batch Apex Patterns That Need Extra Context
Claude Code handles standard batch patterns reliably. For stateful batch jobs — where you accumulate counts across chunks — add Database.Stateful and specify your instance variables explicitly in the prompt. Claude Code will implement the interface but won't know which state to track unless you name it.
Stateful batch prompt addition:
"Implement Database.Stateful. Track: Integer totalProcessed = 0, Integer totalUpdated = 0. Increment both in the execute method based on the records processed and DML results."
How Do You Write Apex Test Classes With Claude Code?
Test classes are where most developers lose the most time in Apex development. Salesforce requires 75% coverage — but coverage alone is not enough. Weak tests that assert nothing catch no bugs. Claude Code writes meaningful tests with proper assertions, not just coverage padding.
The trick is providing Claude Code with the class under test. Paste the full Apex class into the prompt and ask for specific test scenarios. Generic requests produce generic tests.
Prompt Template: Test Class Generation
Write a comprehensive test class for the following Apex class. [Paste your Apex class here] Requirements: - Use @TestSetup to create shared test data (Account, Contact, Opportunity) - Write separate test methods for each scenario: 1. Positive: Opportunity Stage changes to 'Closed Won' — assert Onboarding Task created 2. Positive bulk: 200 Opportunities updated simultaneously — assert 200 tasks created 3. Negative: Opportunity Stage changes to 'Prospecting' — assert no task created 4. Null safety: Opportunity with no Account — assert no exception thrown - Use System.assertEquals and System.assertNotEquals with descriptive failure messages - No @SeeAllData=true — all test data must be created in the test class - Target: 85%+ coverage of OpportunityTriggerHandler Output: OpportunityTriggerHandlerTest.cls
This structure — TestSetup + separate scenario methods — consistently achieves 85-95% coverage while providing genuine regression protection. Claude Code generates all four methods with correct data relationships and assertion messages.
“Writing Apex test classes used to take me as long as writing the class itself. With Claude Code, I paste in the handler, describe the scenarios, and get a full test class in 30 seconds. I spend my time reviewing the assertions, not writing data factories.”
— Salesforce Developer, Trailblazer Community Alpharetta Group
SOQL Queries and Governor Limit Awareness
Governor limits are Salesforce's hardest constraint for Apex developers. Claude Code generates SOQL that respects the key limits by default: queries use bind variables, DML stays outside loops, and collection sizes are bounded. The full list of limits is published in Salesforce's official Apex developer documentation.
Per-transaction limits in Salesforce API v62.0 that Claude Code is trained to respect:
| Governor Limit | Limit Value | Claude Code Default Pattern |
|---|---|---|
| SOQL queries | 100 per transaction | Single bulk query with IN clause |
| DML statements | 150 per transaction | One DML call per collection |
| Heap size | 6 MB (sync) / 12 MB (async) | Limit fields in SELECT clauses |
| CPU time | 10,000 ms (sync) | Avoid nested loops; use maps |
| Future method calls | 50 per transaction | Prefer queueable over @future |
SOQL Prompt That Stays Within Limits
Write a SOQL query and Apex method that: - Accepts a Set<Id> of Account IDs as input - Queries all related Contacts where Email != null - Returns a Map<Id, List<Contact>> keyed by Account ID - Selects only: Id, FirstName, LastName, Email, AccountId - Enforces sharing rules (use 'with sharing' on the class) - Respects heap size: limit fields to what is listed above only No queries inside loops. Single SOQL statement only.
Claude Code produces a single bulk SOQL statement wrapped in a map-building loop — no per-record queries, minimum field selection, and sharing enforcement included.
Deploying Apex With Claude Code
Claude Code can run Salesforce CLI commands when connected via the Salesforce DX MCP. That means it can validate, run tests, and trigger deployments — but it should never be allowed to deploy directly to production without human review.
The recommended deployment sequence keeps a human at the final gate:
Step 1 — Validate Against Sandbox
Ask Claude Code to run a deployment validation (dry run) against your sandbox. This compiles the code and runs tests without committing any changes.
# Prompt to Claude Code: Run: sf project deploy validate --source-dir force-app/main/default/classes --target-org [sandbox-alias] --test-level RunLocalTests Show me the full output including any compile errors or test failures.
Step 2 — Fix Errors Iteratively
If validation returns errors, paste the error output back to Claude Code. It reads the compile error, identifies the line, and generates a corrected file. Most errors resolve in one iteration.
Step 3 — Deploy to Sandbox (Human Reviews First)
After validation passes, review the generated code yourself. Look at the business logic, confirm the field mappings, and check edge case handling. Then instruct Claude Code to run the actual sandbox deployment.
Step 4 — Promote to Production via Change Sets or CI/CD
Use your existing promotion process — change sets, GitHub Actions, Copado, or Gearset — to move sandbox-validated code to production. Claude Code does not touch production. This boundary is non-negotiable.
Deployment safety checklist:
- Validate first — never deploy without a dry run
- Run full local tests, not just RunSpecifiedTests on your new class
- Review business logic manually before any DML-heavy class goes live
- Always deploy to sandbox before promoting to production
- Check org limits in Setup > Apex before deploying large batch jobs
Copy-Paste Prompts That Ship Production Code
These prompts are structured for maximum specificity. Copy, fill in your field names, and send to Claude Code. Each one produces a deployable file on the first attempt in approximately 85% of cases.
Platform Event Subscriber
Write an Apex trigger that subscribes to the LeadEnriched__e platform event. When the event fires: - Read fields from the event: Lead_Id__c (ID), Email__c (Text), Phone__c (Text) - Update the matching Lead record with the new Email and Phone values - Use a Map to avoid queries inside the loop - Log errors to a custom Log__c object (fields: Message__c, Type__c = 'Error') - Handle partial failures: use Database.update with allOrNone = false API version: 62.0 Output: LeadEnrichedEventSubscriber.trigger
Queueable with Callout
Write a Queueable Apex class that makes a callout to an external enrichment API.
Requirements:
- Accepts a List<Id> of Contact IDs in the constructor
- For each Contact, make an HTTP GET request to: https://api.example.com/enrich?email={email}
(use Contact.Email as the parameter)
- Parse the JSON response: { "phone": "...", "company": "..." }
- Update Contact.Phone and Contact.Company with the response values
- Implement Database.AllowsCallouts
- Use a try/catch for HTTP errors — log failures to Debug log, do not throw
- If queue depth allows, chain to a new instance of itself with remaining IDs
Output: ContactEnrichmentQueueable.clsCustom REST Endpoint
Write a custom REST API endpoint in Apex.
Endpoint: /services/apexrest/leads/enrich
Method: POST
Accepts JSON body: { "email": "...", "company": "..." }
Logic:
- Query for a matching Lead by Email
- If found: update Lead.Company with the incoming value, return 200 with the Lead ID
- If not found: create a new Lead with the provided fields, return 201 with new ID
- If email is null or empty: return 400 with error message "Email required"
Use @RestResource, @HttpPost, RestContext.request and RestContext.response
Output: LeadEnrichmentRestHandler.cls + LeadEnrichmentRestHandlerTest.clsThese three patterns — platform event subscribers, queueable callouts, and custom REST endpoints — cover the majority of integration work in modern Salesforce orgs. Claude Code handles all three well because they follow predictable interface patterns.
Claude Code + SyncGTM for Salesforce GTM Teams
Claude Code accelerates the Apex development layer. But many Salesforce GTM teams want enrichment, contact data, and buying signals flowing into their CRM without writing custom Apex at all.
SyncGTM connects directly to Salesforce and handles waterfall enrichment, contact verification, and buying signal routing without requiring custom Apex code. The two tools solve different layers of the same problem.
| Layer | Claude Code Role | SyncGTM Role |
|---|---|---|
| Custom business logic | Write Apex triggers and handlers | — |
| Contact enrichment | Build callout classes to enrichment APIs | Waterfall enrichment from 20+ sources, no-code |
| Buying signals | Write platform event subscribers | Pre-built signal detection and CRM routing |
| Test coverage | Generate test classes for all custom code | No Apex to test |
For GTM teams on Salesforce, the practical split is: use SyncGTM for enrichment and signal workflows (no Apex required), and use Claude Code for the custom business logic that SyncGTM doesn't cover. Review the best enrichment tools for Salesforce in 2026 to see where SyncGTM sits in the Salesforce enrichment landscape.
Claude Code also fits naturally into broader GTM team workflows — not just Apex, but lead routing logic, workflow automation, and CRM automation scripts that require custom code. See how GTM teams use Claude Code across six operational workflows for a broader picture.
Final Thoughts
Claude Code does not replace Salesforce developers. It eliminates the scaffolding tax that burns developer hours before a single line of business logic is written. Trigger handler frameworks, batch job boilerplate, test data factories, and SOQL query construction — all of that gets drafted in seconds, not hours.
The developers who get the most from Claude Code are the ones who give it the most context: the object schema, the field names, the existing handler pattern, and the specific edge cases to handle. Vague prompts produce generic code. Specific prompts produce deployable code.
Start with your next test class. Paste in the Apex class under test, specify three test scenarios, and run the prompt. Review the output, check the assertions, and deploy to sandbox. That one experiment will show you exactly where Claude Code fits in your Salesforce development workflow.
This post was last reviewed in April 2026.
