Custom Metadata Types: Your Recipe for API Key Security
Imagine we are running a top-secret sandwich joint, and we've got the most delicious secret sauce recipe that's known to humankind. Now, we don’t want to share our secret with anyone, but insiders should know the secret ! In this world of our Salesforce development, our secret sauce is the API key and endpoint URL we need for secure API integration. But worry not; we've got a clever trick for us: Custom Metadata Types!
The Problem: Hardcoding Secrets
While coding we shouldn’t hardcode our API key and endpoint URL. It’s like leaking out our secret sauce recipe on the internet. It's not only insecure but also a recipe for disaster. People can misuse our API key and cause havoc.
The Solution: Custom Metadata Types
Here comes our savior, Custom Metadata Types. They work like our Salesforce Objects, and we can create records to store our API key and endpoint URL. It’s a good way right, to store our sneaky API keys!
How to Use Custom Metadata Types:
Step 1: Create Your Custom Metadata Type
In setup < Custom Code < Custom Metadata Types < New
Give it a label, say “API Config” and save. It will be saved as API_Config__mdt.
Don't forget to check out: What is Custom Metadata in Salesforce in 2023?
Step 2: Create Fields
In our Custom Metadata Type, let’s add fields for our API key and endpoint URL. Let's call them "API_Key__c" and "API_Endpoint__c."
Step 3: Create a Record
Now, create a record with your API key and endpoint values. This record is like the key to our secret sauce vault. Store API Key and endpoint URL in this record. (You can name it according to you)
Step 4: Retrieve Your Secrets
Now in our Apex code, let’s retrieve the values from our Custom Metadata Type. No more hardcoded secrets in your code; it's like magic!
Add the below code to your Apex Controller and continue the rest of the coding.
API_Config__mdt config = [SELECT API_Key__c, API_Endpoint__c FROM API_Config__mdt LIMIT 1]; String apiKey = config.API_Key__c; String endpoint = config.API_Endpoint__c;
Step 5: Enjoy our Secure Integration
Hurray!!! We can now securely perform integration now.
Why Custom Metadata Types?
Security: Our secrets are locked up tight in Salesforce, away from prying eyes.
Flexibility: We can easily update your secrets without changing your code.
Control: We decide who gets access to your secret sauce vault.
Questions for You:
- What's your favorite secret sauce (or API integration)?
- Have you ever had an "API key exposed" nightmare?
- Did Custom Metadata Types make your life as a developer easier and more secure?
Check out another amazing blog by Nayan here: Fetching and Displaying Data in Salesforce Lightning Web Components: A Step-by-Step Guide Salesforce
Great work !