In web development, cookies track user sessions, persist state, and personalize UI experiences. In this tutorial, we will explore how to manage HTTP cookies (create, read, delete) dynamically within Lightning Web Components (LWC) in Salesforce.
document.cookie). However, security sandboxes like Lightning Web Security (LWS) place strict restrictions on cookie scopes across Salesforce domains.
Prerequisites
- Salesforce Developer Org: An active developer environment or Scratch Org.
- LWC Basics: Understanding component structure, reactive properties, and event handling.
- Salesforce CLI: Installed locally for component creation and deployment.
Step-by-Step Implementation
Step 1: Build the Component Markup (cookieExample.html)
Construct input fields bound to reactive component properties, paired with action buttons:
<template>
<lightning-card title="LWC Cookie Manager" icon-name="utility:custom_apps">
<div class="slds-p-around_medium">
<lightning-input
label="Cookie Name"
value={cookieName}
onchange={handleCookieNameChange}>
</lightning-input>
<lightning-input
label="Cookie Value"
value={cookieValue}
onchange={handleCookieValueChange}>
</lightning-input>
<div class="slds-m-top_medium slds-button-group" role="group">
<lightning-button
label="Set Cookie"
variant="brand"
onclick={setCookie}>
</lightning-button>
<lightning-button
label="Get Cookie"
onclick={getCookie}>
</lightning-button>
<lightning-button
label="Delete Cookie"
variant="destructive"
onclick={deleteCookie}>
</lightning-button>
</div>
</div>
</lightning-card>
</template>
Step 2: Implement JavaScript Operations (cookieExample.js)
Add input change handlers alongside cookie management methods:
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CookieExample extends LightningElement {
cookieName = '';
cookieValue = '';
handleCookieNameChange(event) {
this.cookieName = event.target.value;
}
handleCookieValueChange(event) {
this.cookieValue = event.target.value;
}
setCookie() {
if (!this.cookieName) {
this.showToast('Error', 'Cookie Name is required', 'error');
return;
}
// Set cookie with SameSite and Secure flags for compliance
document.cookie = `${this.cookieName}=${encodeURIComponent(this.cookieValue)};path=/;Secure;SameSite=Strict`;
this.showToast('Success', 'Cookie set successfully!', 'success');
}
getCookie() {
if (!this.cookieName) {
this.showToast('Error', 'Specify Cookie Name to retrieve', 'error');
return;
}
const cookies = document.cookie.split(';');
let found = false;
cookies.forEach((cookie) => {
const [name, value] = cookie.trim().split('=');
if (name === this.cookieName) {
this.cookieValue = decodeURIComponent(value || '');
found = true;
}
});
if (found) {
this.showToast('Success', 'Cookie retrieved successfully!', 'success');
} else {
this.showToast('Warning', 'Cookie not found', 'warning');
}
}
deleteCookie() {
if (!this.cookieName) {
this.showToast('Error', 'Specify Cookie Name to delete', 'error');
return;
}
document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
this.cookieValue = '';
this.showToast('Success', 'Cookie deleted successfully!', 'success');
}
showToast(title, message, variant) {
this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
}
}
handleCookieNameChange) in LWC templates prevents properties from updating dynamically as users type into input fields.
sessionStorage or localStorage APIs where appropriate.
Step 3: Deploy and Test
- Deploy the component using Salesforce CLI:
sf project deploy start --source-dir force-app/main/default/lwc/cookieExample - Open Lightning App Builder in your org and place
cookieExampleon an App or Record Page. - Enter a key (e.g.,
themePreference) and value (e.g.,dark), then click Set Cookie. - Clear the value field and click Get Cookie to verify retrieval.
- Click Delete Cookie to confirm removal.
Conclusion
Managing cookies in Lightning Web Components provides a straightforward way to maintain lightweight state. By incorporating proper URL encoding, security flags (Secure; SameSite=Strict), and input bindings, developers can manage persistent user preferences across Salesforce sessions.