if (window.freighterApi.isConnected()) {
  alert("User has Freighter!");

const retrievePublicKey = async () => {
  let publicKey = "";
  let error = "";

  try {
    publicKey = await window.freighterApi.getPublicKey();
  } catch (e) {
    error = e;

  if (error) {
    return error;

  return publicKey;

const result = retrievePublicKey();

Hi. This is Freighter Wallet javascript code. I try to find a way to get publicKey outside of this code. when I console.log(publicKey) after "await" everything ok. But I can't set publicKey to other variables to use outside of this code. When I set a variable after "await" and use it outside it is just undefined. result log gives me "promise pending". I can use "then" to get results on "console.log" . but still don't know any way to set the result to a variable to use.

1 Answer 1


You can define a global variable at the top:

var publicKey;

(remove the line let publicKey = "";)

and set it like you do already:

publicKey = await window.freighterApi.getPublicKey();

But it will still be available only after the retrievePublicKey has run; it's an async function so you have to await it, and that cannot be done from the 'main' method (just await retrievePublicKey() won't work). You can do it with then, as you already tried, or a self-invoked async function as described in this Stack Overflow answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.