Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
Diagram of Experience Cloud guest user create records flow through a system-mode Apex insert
Apex

Experience Cloud Guest User Create Records: Use System Mode

Granting Create on the guest profile lets any anonymous caller insert records through the standard createRecord path and skip your form's checks. Leave the object permission off, insert from a with sharing Apex class in system mode, and harden that method, because anyone can call it.

The short answer

Leave Create off the guest profile and insert from a with sharing Apex class using Database.insert(rec, true, AccessLevel.SYSTEM_MODE) for that one statement. Profile Create lets anonymous callers use the standard createRecord path and skip your form, so harden the Apex method instead: typed input, server-resolved Ids, validation, a captcha and a minimal response.

Key takeaways Remove every object permission on the intake object from the guest profile, and grant access only to the one Apex class the form calls. Keep the controller with sharing and run only the insert in system mode, behind a custom permission so you can switch intake off without a deployment. Accept typed parameters, resolve related records on the server from codes, and assign every field in Apex, because system mode ignores FLS. Put the rules that must block bad records in validation rules or triggers so they run on every insert path, and return only success or an error message to the browser. Turn on default ownership for guest-created records and audit the guest profile with the Guest User Sharing Rule Access Report.

A public warranty-claim form on an Experience Cloud site has to insert a record for someone who never logged in. The quick fix is to tick Create on the guest user profile, and the form works within minutes. That same checkbox opens the object to every anonymous caller who can reach your site's API, whether or not they use your form. My recommendation is to leave the object permission off, insert from Apex in system mode, and treat that Apex method as the public endpoint it is.

Two ways to let a guest create a record

Salesforce documents the profile route first: give the guest profile Create on the object, which also forces Read on it. The same guide says that if guests don't need to read the object, you should strip every permission on it and do the create in a without sharing controller. Guests can only hold Read and Create as object permissions. Edit, Delete, View All and Modify All are blocked, and guests can only update or delete records in system mode. That makes Create the largest write capability the platform lets you give an anonymous visitor.

Create on the guest profile No object permission, Apex inserts in system mode
Who can insert Any caller reaching the site's API, through any path that honours profile CRUD and FLS Only callers of your @AuraEnabled method
Read on the object Forced, since Create requires Read Not granted
Where blocking validation must live Validation rules, flows, triggers Apex method plus DML-layer rules
Fields a caller can set Any field with edit FLS on the guest profile Only fields your Apex assigns
What you maintain Guest profile CRUD and FLS One system-mode endpoint and its input checks

I would build the second column, with one change to Salesforce's wording: keep the class with sharing and lift access only for the insert statement.

What Create on the guest profile actually exposes

Experience Cloud sites expose an Aura endpoint at /s/sfsites/aura, and Salesforce's own guidance on guest user security names it as a surface attackers probe. Lightning Data Service and the UI API create records through standard actions on that surface, and they enforce the running user's object and field permissions. So once the guest profile carries Create on Warranty_Claim__c, that check passes for any anonymous caller.

An answer on Salesforce Stack Exchange (question 440000, November 2026, no accepted answer yet) spells out the result. A guest can call the standard createRecord action directly and set any field they have FLS on. Your component never loads and your Apex validation never runs, and the platform is working as designed when that happens. A request body in the UI API record input shape is all it takes:

{
  "apiName": "Warranty_Claim__c",
  "fields": {
    "Serial_Number__c": "ZZ00000000",
    "Purchase_Date__c": "2019-01-01",
    "Status__c": "Approved",
    "Contact_Email__c": "[email protected]"
  }
}

If Status__c has edit FLS because someone ticked the whole field list on the profile, that caller just filed a pre-approved claim for a product years out of warranty. The form's date check and its status default never ran, because the form was never involved.

The profile route is acceptable in one case. Every rule that must block a bad record lives in validation rules, record-triggered flows or triggers. FLS is trimmed to the fields the form needs. And you are comfortable with records arriving from scripts as well as from your form.

The pattern: a with sharing class that runs one insert in system mode

Give the guest profile no permissions on Warranty_Claim__c. Give it access to one Apex class. The site needs that grant regardless, because guests must be explicitly given every @AuraEnabled class they call. The component sends plain values and the server builds the record.

import { LightningElement } from 'lwc';
import submitClaim from '@salesforce/apex/WarrantyIntakeController.submitClaim';

export default class WarrantyClaimForm extends LightningElement {
    serialNumber = '';
    modelCode = '';
    purchaseDate;
    contactEmail = '';
    issueType = '';
    issueDescription = '';
    captchaToken;
    submitted = false;
    errorMessage;

    handleChange(event) {
        this[event.target.name] = event.target.value;
    }

    handleCaptcha(event) {
        this.captchaToken = event.detail.token;
    }

    async handleSubmit() {
        this.errorMessage = undefined;
        try {
            await submitClaim({
                claim: {
                    serialNumber: this.serialNumber,
                    modelCode: this.modelCode,
                    purchaseDate: this.purchaseDate,
                    contactEmail: this.contactEmail,
                    issueType: this.issueType,
                    issueDescription: this.issueDescription
                },
                captchaToken: this.captchaToken
            });
            this.submitted = true;
        } catch (error) {
            this.errorMessage = error?.body?.message ?? 'We could not submit your claim.';
        }
    }
}

The controller:

public with sharing class WarrantyIntakeController {

    private static final String BYPASS_PERMISSION = 'Guest_Warranty_Intake';
    private static final String GENERIC_ERROR =
        'We could not save your claim. Please check your details and try again.';

    public class ClaimInput {
        @AuraEnabled public String serialNumber { get; set; }
        @AuraEnabled public String modelCode { get; set; }
        @AuraEnabled public Date purchaseDate { get; set; }
        @AuraEnabled public String contactEmail { get; set; }
        @AuraEnabled public String issueType { get; set; }
        @AuraEnabled public String issueDescription { get; set; }
    }

    @AuraEnabled
    public static Boolean submitClaim(ClaimInput claim, String captchaToken) {
        // Callout first: a callout after uncommitted DML in the same transaction fails.
        if (claim == null || !CaptchaVerifier.isHuman(captchaToken)) {
            throw new AuraHandledException('We could not verify your submission. Please try again.');
        }

        List<String> problems = validate(claim);
        if (!problems.isEmpty()) {
            throw new AuraHandledException(String.join(problems, ' '));
        }

        Id productId = new ProductResolver().activeProductId(claim.modelCode);
        if (productId == null) {
            throw new AuraHandledException('That model code was not recognised.');
        }

        Warranty_Claim__c rec = new Warranty_Claim__c(
            Serial_Number__c = claim.serialNumber.trim().toUpperCase(),
            Purchase_Date__c = claim.purchaseDate,
            Contact_Email__c = claim.contactEmail.trim().toLowerCase(),
            Issue_Type__c = claim.issueType,
            Issue_Description__c = claim.issueDescription.trim(),
            Product__c = productId,
            Status__c = 'New'
        );

        // Two deliberate grants are needed for system mode: class access and the custom permission.
        AccessLevel mode = FeatureManagement.checkPermission(BYPASS_PERMISSION)
            ? AccessLevel.SYSTEM_MODE
            : AccessLevel.USER_MODE;

        try {
            Database.insert(rec, true, mode);
        } catch (DmlException e) {
            if (e.getDmlType(0) == StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION) {
                throw new AuraHandledException(e.getDmlMessage(0));
            }
            System.debug(LoggingLevel.ERROR, 'Warranty intake insert failed: ' + e.getMessage());
            throw new AuraHandledException(GENERIC_ERROR);
        } catch (Exception e) {
            System.debug(LoggingLevel.ERROR, 'Warranty intake insert failed: ' + e.getMessage());
            throw new AuraHandledException(GENERIC_ERROR);
        }
        return true;
    }
}

The class is with sharing. Salesforce's guest security guide says to always use with sharing on @AuraEnabled controllers used by Lightning components, and its create-records guide suggests without sharing for the insert. Combining with sharing with AccessLevel.SYSTEM_MODE on one DML statement satisfies both. The bypass is a single line you can search for, and any query someone adds to this class next year still runs under sharing.

The access level comes from a custom permission. FeatureManagement.checkPermission('Guest_Warranty_Intake') returns true only if you granted that permission to the guest user. Without it the insert runs in USER_MODE, and because the guest has no Create on the object, it fails. Phil W suggested this gate in the same Stack Exchange thread. It also gives you a kill switch: remove the custom permission and intake stops without a deployment.

The method returns true or throws. Salesforce's guidance is to keep record Ids away from the guest client. If a later step really needs to find the record again, return an encrypted string built from the Id and the creation timestamp, never the raw Id. Validation rule messages pass through because you wrote them. Every other failure gets a generic message, and the detail goes to the debug log.

Hardening a method anyone on the internet can call

The @AuraEnabled method is now your endpoint. Anyone can post a payload they wrote themselves to the site's Aura endpoint without opening the form, so the endpoint is only as safe as what it accepts.

Typed input, record built on the server

ClaimInput has six typed properties. If the method took a Warranty_Claim__c or a Map<String, Object> of fields, a caller could add Status__c or OwnerId, and system mode ignores FLS, so nothing would stop them. Assign every field in Apex, including defaults such as Status__c = 'New'.

No Ids from the browser

The form sends a model code and the server finds the product. If the browser sent a Product2 Id, a caller could swap in any record Id in the org. Salesforce's guest guidelines make the same point about lookups: letting a guest look up records by Id makes those records public in practice. The resolver below runs in a small without sharing inner class that returns an Id and nothing else. The query runs WITH SYSTEM_MODE because Apex at API 67.0 and later enforces the running user's object and field permissions by default, and the guest has none on Product2.

Validate what the form validates, again

Check required fields, lengths, formats, active picklist values and date ranges. The LWC checks are there for the user's convenience. The Apex copy is the one that holds when someone skips the form. These go in the same class:

    private static List<String> validate(ClaimInput c) {
        List<String> problems = new List<String>();
        if (String.isBlank(c.serialNumber)
                || !Pattern.matches('[A-Z]{2}[0-9]{8}', c.serialNumber.trim().toUpperCase())) {
            problems.add('Enter the 10-character serial number from the product label.');
        }
        if (String.isBlank(c.modelCode) || c.modelCode.length() > 20) {
            problems.add('Enter a valid model code.');
        }
        if (c.purchaseDate == null || c.purchaseDate > Date.today()
                || c.purchaseDate < Date.today().addYears(-3)) {
            problems.add('Purchase date must be within the last three years.');
        }
        if (String.isBlank(c.contactEmail) || c.contactEmail.length() > 254
                || !Pattern.matches('[^@ ]+@[^@ ]+[.][^@ ]+', c.contactEmail.trim())) {
            problems.add('Enter a valid email address.');
        }
        if (!allowedIssueTypes().contains(c.issueType)) {
            problems.add('Choose an issue type from the list.');
        }
        if (String.isBlank(c.issueDescription) || c.issueDescription.length() > 2000) {
            problems.add('Describe the issue in 2000 characters or fewer.');
        }
        return problems;
    }

    private static Set<String> allowedIssueTypes() {
        Set<String> values = new Set<String>();
        for (Schema.PicklistEntry entry :
                Warranty_Claim__c.Issue_Type__c.getDescribe().getPicklistValues()) {
            if (entry.isActive()) {
                values.add(entry.getValue());
            }
        }
        return values;
    }

    // Returns only an Id. Never return product data from here to the guest.
    private without sharing class ProductResolver {
        public Id activeProductId(String modelCode) {
            List<Product2> matches = [
                SELECT Id FROM Product2
                WHERE ProductCode = :modelCode.trim() AND IsActive = true
                WITH SYSTEM_MODE
                LIMIT 1
            ];
            return matches.isEmpty() ? null : matches[0].Id;
        }
    }

Captcha, verified on the server

The component can render whatever captcha your team uses, but the token means nothing until Apex checks it with the provider. Keep the verification in its own class and make it fail closed:

public with sharing class CaptchaVerifier {
    public static Boolean isHuman(String token) {
        if (String.isBlank(token) || token.length() > 4000) {
            return false;
        }
        try {
            return verifyWithProvider(token);
        } catch (Exception e) {
            System.debug(LoggingLevel.ERROR, 'Captcha verification failed: ' + e.getMessage());
            return false;
        }
    }

    // Stub: call your provider's server-side verify endpoint through a Named Credential,
    // then check the success flag, the expected hostname and the token age.
    private static Boolean verifyWithProvider(String token) {
        return false;
    }
}

The stub returns false on purpose, so a half-finished integration blocks submissions instead of letting everything through.

Defense in depth: rules that run on every insert path

The Apex checks protect your endpoint. Rules at the DML layer protect every insert path, including one a future developer adds without reading this class. Put the rules that must block in validation rules, record-triggered flows or triggers, and leave soft warnings in the component. A serial number format rule as metadata:

<?xml version="1.0" encoding="UTF-8"?>
<ValidationRule xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>Serial_Number_Format</fullName>
    <active>true</active>
    <errorConditionFormula>NOT(REGEX(Serial_Number__c, "[A-Z]{2}[0-9]{8}"))</errorConditionFormula>
    <errorDisplayField>Serial_Number__c</errorDisplayField>
    <errorMessage>Serial number must be two letters followed by eight digits.</errorMessage>
</ValidationRule>

The controller passes this message straight to the user through the FIELD_CUSTOM_VALIDATION_EXCEPTION branch, so you write the wording once.

Guests no longer own the records they create. Turn on "Assign new records created by guest users to the default owner" under Setup > Digital Experiences > Settings, then pick the owner for this site under Setup > Digital Experiences > All Sites, then open the site's Workspaces > Administration > Preferences. Pick an active user whose role puts the records where your claims team can see them.

For the audit, Salesforce recommends starting the guest profile at zero access, restoring only what tested features need, and setting Default External Access to Private. Run the Guest User Sharing Rule Access Report in Setup. The free AppExchange package "Authenticated and Guest User Access Report and Monitoring" lists which objects and permissions guests can reach. Salesforce states that it doesn't own or support that package, so treat it as a reporting aid and keep your own checks.

What to watch for

  • The guest can't read back what it created. Guest-created records go to a default active owner, so the guest can only see them through a guest sharing rule, and those rules take effect only after the transaction completes. A with sharing class that creates and then queries the record in the same transaction gets nothing back, so show a confirmation screen built from what the user typed.
  • From API 67.0 Apex defaults to user mode, so every query and DML statement on the guest path that needs to bypass the guest's permissions must request system mode explicitly (WITH SYSTEM_MODE or AccessLevel.SYSTEM_MODE). A without sharing keyword alone is not enough.
  • System mode ignores FLS in both directions. Every field you forget to assign stays blank, and every field you copy from input without checking is writable by anyone.
  • Remove profile Create if an earlier build granted it. Otherwise the standard createRecord path stays open next to your new endpoint.
  • Test as the real guest user with the product lookup populated. SYSTEM_MODE drops the object and field checks, while record sharing still follows the class keyword. If the insert fails with a sharing error on the parent record, move only the DML into a without sharing helper rather than flipping the whole class.
  • Remove the Guest_Warranty_Intake permission in a sandbox and submit once. The insert should fail. If it succeeds, the guest profile still has Create somewhere.
  • Keep the Apex class grant on the guest profile in version control along with the custom permission assignment, so a profile refresh doesn't reopen or break intake without anyone noticing.

Originally reported by developer.salesforce.com

Frequently asked questions

Should I give the Experience Cloud guest user profile Create permission on a custom object?

Only if every rule that must block a bad record lives in validation rules, flows or triggers, and you accept records arriving from scripts as well as your form. Profile Create also forces Read on the object, and it opens the standard createRecord path to any anonymous caller.

How do I insert a record as a guest user without object permissions in Apex?

Call Database.insert(rec, true, AccessLevel.SYSTEM_MODE) from an @AuraEnabled method in a with sharing class that the guest profile has access to. System mode ignores the guest's object and field permissions for that statement only.

Why can't my guest user query the record it just created?

Guest-created records go to a default active owner, so the guest can only see them through a guest sharing rule, and those rules take effect only after the transaction completes. A with sharing class that creates and then queries the record in the same transaction gets nothing back, so return a confirmation message instead of record data.

Is an @AuraEnabled method on a public Experience Cloud site callable without my LWC?

Yes. Sites expose an Aura endpoint at /s/sfsites/aura, so anyone can call the method with a payload they wrote themselves. Validate every input on the server and verify a captcha token there.

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment