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

172
Visualizações
How can I use refresh token in react

I have a get refresh token url like this client.com/api//auth/refresh-token. but I have a hard time using this. I think it should save a refresh token in the local storage after the login. but how can I use it?

login.tsx

export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    return {
        LoginAuth,
    }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Save it in local storage

export const storeToken = async (token: string) => {
  await AsyncStorage.setItem('@token', token);
};

And fetch from storage when needed

export const getToken = async () => {
  return await AsyncStorage.getItem('@token');
};

You should probably fetch the token from storage when application starts or when fetching from the API and store it in state or such while using the application.

about 4 years ago · Juan Pablo Isaza Relatório

0

Save in web storage

Only strings can be stored in web storage

LocalStorage

Persists even when the browser is closed and reopened.

Get

const token = localStorage.getItem('token');

Set

localStorage.setItem('token', 'value')

SessionStorage

Data removed when browser closed

Get

sessionStorage.getItem('token', 'value')

Set

sessionStorage.setItem('token', 'value')
about 4 years ago · Juan Pablo Isaza Relatório

0

You should not set the refresh token in local storage, it would cause a security vulnerability, since local storage is accessible by javascript, and since refresh token is long term token (live longer than access token), what you would do is, to store access token in local storage, since access token is short termed token, storing in local storage or cookies is totally fine, and then you should make an useEffect() call in react, that check whenever the token is expired and then make the call, a small example:

import Cookies from 'js-cookie';
axios.get("ur_url_here/",data,{headers:{"Content-Type": "application/json",Accept: "application/json"}}).then((res)=>{
                Cookies.set(res.data.access) // assuming the response has the access token
        
}))

// now we check the expiration of access token

useEffect(()=>{
   if(!(Cookies.get("access"){
      axios.get("refresh_url_here/",{headers:{"Content-Type": "application/json",Accept: "application/json"}}).then((res)=>{
        Cookies.set(res.data.access)
})
/*what you do here, is try to have a 
resource/view in your backend that has 
the refresh token and make request to it 
so that it gives you a new access token, 
because refresh token should be in cookies tagged with `httponly', 
then you can send the access token to client side 
as a response and set it somewhere.
*/
}
   else{
      //do something else
}
})

this is a simplified code, but should explain well the idea of refreshing a token safely.

also note, i stored access in cookies, but you can do the same and store it in local storage.

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