2

I am doing a Vue 3 practice together with Django Rest Framework, what I am trying to do is a token authentication validation, a user logs in, a token is going to be generated, but I run into a problem and it is that when at moment of logging in is done correctly and I am able to obtain the generated token, the problem is that when reloading the page the token is no longer in the vue application, a possible solution that I decided is to make the token save in local storage, but i think it is not the correct solution.
This is my Login.vue:

<template>
  <h2>login</h2>
  <form method="POST" @submit.prevent="sendData" autocomplete="off">
    <input
      type="text"
      placeholder="Nombre de Usuario"
      v-model.trim="username"
    />
    <input
      type="password"
      placeholder="Contraseña de Usuario"
      v-model.trim="password"
    />
    <button type="submit">enviar</button>
  </form>
</template>

<script>
  import { ref } from '@vue/reactivity';
  import { watchEffect } from '@vue/runtime-core';
  export default {
    setup() {
      const username = ref('');
      const password = ref('');

      const token = ref('');

      const sendData = () => {
        fetch(`http://localhost:8000/auth-token/`, {
          method: 'POST',
          body: JSON.stringify({
            username: username.value,
            password: password.value,
          }),
          headers: {
            'Content-Type': 'application/json',
          },
        })
          .then((res) => res.json())
          .catch((error) => console.error('Error:', error))
          .then((response) => {
            token.value = response.token;
          });
      };

      watchEffect(() => localStorage.setItem('Token', token.value));

      return {
        username,
        password,
        sendData,
      };
    },
  };
</script>
kissu
  • 40,416
  • 14
  • 65
  • 133
cosmos multi
  • 543
  • 1
  • 6
  • 13
  • 2
    Setting the token in either local storage or a cookie are fine options. Either way, when your app first loads, in the top level component, you need to check for the token in local storage or a cookie and if it exists, then set the value in your app. – bassxzero Apr 02 '21 at 03:22

1 Answers1

1

Here is one of my latest answer on the question: https://stackoverflow.com/a/66872372/8816585

TLDR: you only have a few possibilities to persist the data on the frontend but using localStorage/cookies/IndexedDB is totally fine for this purpose.

Also, making a call to the backend at the start of your app is a good idea too, especially if the payload is a bit heavy (you send some JWT, and get a load of personal infos).

Here is a list of packages that may help you persist data on the frontend: https://github.com/vuejs/awesome-vue#persistence

kissu
  • 40,416
  • 14
  • 65
  • 133