I have created a package-protected custom metadata type (sf_Assistant_Settings), a field (Value) and a record (API_Key).
I use it to store an API Key which is used when making http requests to an endpoint in Apex (in order to not hard-code it).

I retrieve the value of the custom metadata type record using Apex as follows:

public with sharing class Helper {

    public static String getAPIkey() {
        // retrieve the API Key from Package-Protected Custom Metadata Type
        sf_Assistant_Settings__mdt cmdtRecord = sf_Assistant_Settings__mdt.getInstance('API_Key');
        return cmdtRecord.Value__c;
    HttpRequest req = new HttpRequest();
    req.setHeader('API-Key', getAPIkey());

It works fine when I deploy it to a scratch org, but when I create a package version and want to install the package in a (different) scratch org, it gives the following error (pointing to getInstance('API_Key') function):

Custom Metadata Type cannot be referenced outside code from the same namespace

I don't see the reason for this error, because the apex code and the package-protected custom metadata type are both part of the same package.

I tried with namespace prefix as well, but got the same error:

myNamespace__sf_Assistant_Settings__mdt cmdtRecord = myNamespace__sf_Assistant_Settings__mdt.getInstance('myNamespace__API_Key');
return cmdtRecord.myNamespace__Value__c;

Also tried enabling Deploy Metadata from Non-Certified Package Versions via Apex in Apex settings of the target org, but the error persists.

  • Is the error during package installation? Oct 17, 2023 at 19:14
  • @MohithShrivastava yes.
    – LoMaPh
    Oct 17, 2023 at 20:30

1 Answer 1


For some reason getInstance() doesn't work with package-protected custom metadata types when installing the package. Using SOQL solved the issue:

public static String getAPIkey() {
    List<sf_Assistant_Settings__mdt> settings = [
        SELECT Value__c 
        FROM sf_Assistant_Settings__mdt 
        WHERE DeveloperName = 'API_Key'
    return settings[0].Value__c;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .