Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
Lost data stored in localStorage issue

I have a token stored in localStorage, I have also a method that verifies if the token is correct or not, as you can see in this code:

let token = localStorage.getItem('token');
console.log(token);

if ( !token )
{
    return null;
}

const parts = token.split('.');

if ( parts.length !== 3 )
{
    throw new Error('error');
}
....

if the token is undefined I will return null, else continue the verification.

There are two issues I can't understand:

  • Why did I lose the token from the localStorage when I refresh the page
  • Why does the if ( !token ) return false when token is undefined, the first console.log return undefined, but my method continues to const parts = token.split('.');.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Local storage work only with strings.

MDN: Window.localStorage

The keys and the values stored with localStorage are always in the UTF-16 DOMString format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

So, every value is serialized as a string.

localStorage.setItem('token', undefined);
let token = localStorage.getItem('token');
console.log(token);
console.log(typeof(token));

Prints out in the console:

undefined
string

Conclusions:

  1. Don't store null and undefined in Local Storage.
  2. When validating the value from Local Storage, always treat it as a string value.

Notes:

  1. Validation should return false by default. And only in case of success should return true.
  2. You shouldn't store any tokens in Local Storage, it's not secure.
  3. You shouldn't validate anything on a client as the validation logic can be easily manipulated.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda