@conduit-client/salesforce-lightning-service-worker
v3.5.0
Published
Service worker for accessing Salesforce data
Readme
Salesforce Lightning Service Worker
A specialized HTTP client and service worker for Salesforce Lightning applications that provides automatic CSRF (Cross-Site Request Forgery) protection for API requests. This package ensures secure communication with Salesforce APIs by automatically managing CSRF tokens.
Installation
npm install @conduit-client/salesforce-lightning-service-workerUsage
This package provides two ways to use CSRF protection:
1. Using ConduitClient (Recommended)
The ConduitClient provides a convenient wrapper around fetch with automatic CSRF protection:
import { ConduitClient } from '@conduit-client/salesforce-lightning-service-worker';
// Create a client instance
const client = ConduitClient.create();
// Make API calls - CSRF protection is automatic for protected endpoints
const response = await client.fetch('/services/data/v65.0/sobjects/Account', {
method: 'POST',
body: JSON.stringify({ Name: 'Test Account' }),
});2. Using Service Worker (Advanced)
For applications that desire service worker-level CSRF protection:
Register the Service Worker
import { ConduitClient } from '@conduit-client/salesforce-lightning-service-worker';
// Register service worker for enhanced protection
await ConduitClient.registerServiceWorker('./sw.js');Create the Service Worker File
// sw.js - served statically by your bundler
import { ConduitClient } from '@conduit-client/salesforce-lightning-service-worker';
// Define service worker behavior
ConduitClient.defineServiceWorker({ debug: true });**NOTE: ** Note, if service worker registration fails the wrapper approach will remain in place in order to maintain CSRF protection.
Important Configuration Notes:
- Static File Name: The service worker file must have a static name (e.g.,
sw.js) without hash tokens - Module Type: Use ES6 modules for modern bundlers
- Scope: Service worker scope determines which requests it can intercept
CSRF Protection Features
This package provides automatic CSRF protection with the following features:
Automatic Token Management
- Token Caching: CSRF tokens are cached using the Cache API for performance
- Token Refresh: Automatically refreshes tokens when they become invalid
- Retry Logic: Retries requests once with fresh tokens on authentication failures
Protected Endpoints
- Method Protection: Automatically protects data-mutating methods (POST, PUT, PATCH, DELETE)
- URL Protection: Currently protects all Salesforce API endpoints under
/services - Intelligent Detection: Only applies CSRF protection where needed
Service Worker Integration
- Install Handler: Skips waiting to activate immediately
- Activate Handler: Claims all clients immediately
- Fetch Interception: Intercepts and enhances requests with CSRF tokens
Complete Example
// Main application code
import { ConduitClient } from '@conduit-client/salesforce-lightning-service-worker';
async function setupApiClient() {
// Optionally register service worker for enhanced protection
await ConduitClient.registerServiceWorker('./sw.js');
// Create client for API calls
const client = ConduitClient.create();
// Make API calls - CSRF protection is automatic
const account = await client.fetch('/services/data/v65.0/sobjects/Account', {
method: 'POST',
body: JSON.stringify({ Name: 'New Account' }),
});
return client;
}// sw.js - Service worker file if `registerServiceWorker` is used
import { ConduitClient } from '@conduit-client/salesforce-lightning-service-worker';
ConduitClient.defineServiceWorker({ debug: false });Development
Running the Development Server
Use the dev script to run and debug the service worker code:
npm run devThis will:
- Build the service worker code
- Start a development server on port 3000
- Serve a test page with service worker registration
- Automatically open your browser
Development Features
- Live Service Worker Updates: The development server includes automatic service worker update detection and page reloading when you make changes to the source code
- Test API Endpoint: A dummy
/api/dataendpoint is configured to test fetch interception by the service worker - Debug Console: The test page includes buttons to check service worker status and test API calls
- TypeScript Transformation: Service worker code is served as transformed TypeScript via Vite
Development Workflow
- Make changes to
src/index.ts(service worker logic) - The page will automatically detect service worker updates and reload
- Use the test page buttons to verify your changes:
- Check SW Status: View service worker registration details
- Fetch API Data: Test the
/api/dataendpoint through the service worker - Clear Output: Clear the debug console
Development File Structure
src/index.ts- Main service worker code and registration utilitiesscripts/dev.ts- Development server with API mock and service worker servingscripts/dev-service-worker.ts- Entry point for the development service workerscripts/dev-test-page.html- Test page for debugging service worker functionality
Building for Production
npm run buildThis creates production-ready files in the dist/ directory.
Browser Support
Requires browsers with service worker support. The registration function includes feature detection and will gracefully handle unsupported browsers.
This software is provided as-is with no support provided.
