Sub topic 12
Security behavior and limits to plan for
This chapter covers what the GraphQL wire adapter does with a user's permissions, and which limits to design around before they show up as bugs. It assumes you can already write a query with gql and @wire(graphql), read edges/node results, pass reactive variables, and page with first, after, and pageInfo. It also assumes you know Salesforce object permissions, field-level security (FLS), and sharing rules at a working level.
The core rule: queries run as the current user
A query sent through lightning/uiGraphQLApi is evaluated for the user viewing the component. You don't choose a system mode and can't opt out of enforcement. The server applies three layers before any data reaches your component:
- Object permissions. The user needs read access to each object in the query.
- Record access. Ownership, role hierarchy, sharing rules, and manual shares decide which records come back.
- Field-level security. The user needs read access to each field you request.
Two users who run the same query can get different results from the same component. This is correct behavior, and your component must expect it.
Sharing: missing records are not an error
Sharing rules filter silently. If a user can see 40 of 100 Account records, a query for all accounts returns 40 and reports no problem. Nothing in the response says that 60 more exist.
Practical consequences:
- An empty result means "nothing visible to this user." It doesn't mean "nothing exists." Word your empty state accordingly, for example "No accounts available to you" instead of "There are no accounts."
- Counts and aggregates reflect only visible records. If you show a total, label it as the user's own view.
- Don't depend on a record being present. A related record that the user can't see may show up as
nullin a parent relationship field. Guard every parent access.
// Safe access to a parent that may be hidden by sharing
const ownerName = node.Owner?.Name?.value ?? 'Not available';Hidden parents are common enough that unguarded node.Owner.Name.value is one of the most frequent causes of a component that works for admins and fails for everyone else.
Field-level security: ask only for fields you need
When a query includes a field the user can't read, the response contains an entry in the errors array for it. Depending on the shape of the request, you may also get a data object where the affected parts are null. Treat this as the partial-result case from the error-handling chapter: check errors even when data is present.
Two habits keep this manageable:
- Request the minimum. Every extra field is another way for the query to fail for a restricted profile. Don't query fields "just in case."
- Test with a restricted user. Create a permission set that removes read access to one field, assign it to a test user, and load your component as that user. You will see the real behavior in your org, which is more reliable than assuming.
Don't use the client to enforce security. Hiding a field with lwc:if or CSS doesn't protect data that is already in the response. If a value must not reach a user, FLS or sharing must remove it on the server.
A component that tolerates restricted access
This component separates three outcomes: data loaded, partially loaded with errors, and nothing visible. It also logs errors for developers without showing raw messages to users.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class SafeAccountList extends LightningElement {
accounts = [];
hasErrors = false;
loaded = false;
@wire(graphql, {
query: gql`
query safeAccounts {
uiapi {
query {
Account(first: 20, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
Owner { Name { value } }
}
}
}
}
}
}
`
})
wiredAccounts({ data, errors }) {
if (errors) {
// Log full detail for developers; show a generic message to users.
console.error('GraphQL errors', JSON.stringify(errors));
this.hasErrors = true;
} else {
this.hasErrors = false;
}
if (data) {
const edges = data.uiapi.query.Account.edges;
this.accounts = edges.map(({ node }) => ({
id: node.Id,
name: node.Name?.value ?? '(name unavailable)',
owner: node.Owner?.Name?.value ?? 'Not available'
}));
this.loaded = true;
} else if (errors) {
this.accounts = [];
this.loaded = true;
}
}
get isEmpty() {
return this.loaded && !this.hasErrors && this.accounts.length === 0;
}
}<template>
<lightning-card title="Accounts" icon-name="standard:account">
<template lwc:if={hasErrors}>
<p class="slds-p-around_medium">Some account data could not be loaded.</p>
</template>
<template lwc:if={isEmpty}>
<p class="slds-p-around_medium">No accounts are available to you.</p>
</template>
<ul class="slds-p-around_medium">
<template for:each={accounts} for:item="account">
<li key={account.id}>{account.name}, owned by {account.owner}</li>
</template>
</ul>
</lightning-card>
</template>The isEmpty getter is deliberately false when errors exist. Without that check, a permissions failure would show the same "no accounts" message as a legitimately empty list.
Which objects and fields are available
The adapter is built on the UI API, so it can query only objects and fields that the UI API supports. Some objects, and some field types, are not exposed. If a query is rejected because an object or field isn't in the uiapi schema, the cause is usually schema support, not permissions. The two cases look similar in the errors array, so check the object's support first and then check the user's access.
Other points that affect what you can request:
- Custom objects and fields appear after deployment, and the user needs access to them like any other field.
- Guest users on an Experience Cloud site are limited by the guest user profile and sharing rules for guest access. A query that works for an internal user may return nothing for a guest.
- Field names in the query are API names, including the
__csuffix for custom fields.
Limits to plan for
The GraphQL API enforces limits on query size and shape. Exact numbers change between releases, so confirm current values in the Salesforce GraphQL API Developer Guide before you design around a specific figure. The categories stay stable:
| Limit category | What it means for your component |
|---|---|
| Page size | `first` has a maximum per request. Requesting a larger value fails or is capped. Use pagination for anything bigger. |
| Query depth | Deeply nested relationships (parent of parent of child) hit a depth ceiling. Flatten your design or split into two queries. |
| Query complexity | Many fields across many objects raise the cost of a query. A wide, deep query can be rejected even if each part is valid. |
| Result volume | You can't pull an entire large object in one call. Plan for pages, filters, or aggregates. |
| Request volume | Frequent reruns add load. Avoid reactive variables that change on every keystroke. |
If first is omitted, the API applies a default page size, which is small. Always set first explicitly so your component's behavior doesn't depend on a default you didn't choose.
Clamp user-controlled values
Page size often comes from a UI control. Clamp it before it becomes a variable, so a bad input can't produce a rejected query:
const MAX_PAGE_SIZE = 50;
get variables() {
const requested = Number(this.pageSize) || 10;
return {
first: Math.min(Math.max(requested, 1), MAX_PAGE_SIZE),
after: this.after
};
}Your own ceiling can be lower than the platform's. That keeps payloads small and renders fast.
Debounce filter input
When a search box feeds a where variable, each change reruns the wire. Wait until the user stops typing:
handleSearchChange(event) {
const value = event.target.value;
window.clearTimeout(this.searchTimer);
this.searchTimer = window.setTimeout(() => {
this.searchTerm = value;
}, 300);
}searchTerm is a reactive property used by the variables getter, so the query reruns once per pause instead of once per character.
Caching and stale permissions
Wire results are cached on the client. A cached result can outlive a change that affects what the user may see, such as a record being reassigned or a permission set being removed during the session. Refreshing with refreshGraphQL re-runs the query on the server, which applies current permissions again. If your component displays sensitive data after an action that changes access, call the refresh as part of that action.
Common mistakes
- Treating an empty list as proof the data doesn't exist.
- Accessing
node.Parent.Field.valuewithout optional chaining. - Checking
dataand ignoringerrors. - Testing only as a System Administrator.
- Leaving
firstunset and getting an unexpected default. - Letting raw error text from
errorsappear in the UI, which may reveal field or object names to users who shouldn't see them.
Exercise
A component lists Opportunities with their Account name. It works for administrators, but for a sales user it throws "Cannot read properties of null (reading 'Name')" for some rows. What is the likely cause, and what is the fix?
Show answer
The sales user can see those Opportunities but not the parent Account, because sharing hides it, so the relationship field is null. Use optional chaining with a fallback, for example node.Account?.Name?.value ?? 'Not available', and test the component as a restricted user.
Exercise
A query for Contacts returns an empty edges array and no errors for a particular user. Give two possible explanations that don't involve a bug in the query.
Show answer
The user has no sharing access to any matching Contact records, or the filter in the where argument matches no records the user can see. Object read permission can also be missing, though that normally appears as an entry in errors. An empty result without errors means nothing is visible to this user, not that nothing exists.
Exercise
Your page-size picker lets users type any number. Why clamp the value before passing it as first, and where should the clamp live?
Show answer
A value above the platform maximum, or zero or negative, can cause the query to be rejected or to behave unexpectedly. Clamp it in the getter that builds the variables object, so the wire only ever receives a valid first value.