Skip to content

localStorage.getItem can be undefined #68

@kosta

Description

@kosta

Hi!

We ran into one user on Safari 17.6, probably in an private window who raised the error:

null is not an object (evaluating 'localStorage.getItem')

Looking at the code (guided by the stack trace):

function hasLocalStorage() {
  return typeof localStorage !== "undefined";
}

function getLocalStorageNumber(key) {
  if (!hasLocalStorage()) {
    return null;
  }
  const value = localStorage.getItem(key);
  if (!value) {
    return null;
  }
  const num = parseInt(value, 10);
  if (Number.isNaN(num)) {
    return null;
  }
  return num;
}

I would propose either:
a) Just wrap the localStorage access into a try/catch and return null; or
b) check whether localStorage.getItem is defined in hasLocalStorage as well

Not super urgent, just "correctness". Also it seems (in local testing) that Safari 18 has localStorage in a private window, so 🤷

Thanks in advance for your consideration!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions