1

Suppose I have API for login, log out. I am using Token Authentication. I have react component name Login. I can call API and I am getting token. But, I am not understanding how to save the token in a browser until log out or automatically destroy token after a moment.

  • You can use both cookie and localstorage. You can check if the client support localstorage if not use cookie. – madhurgarg Aug 29 '17 at 06:53

2 Answers2

1

You can create a storage module and check for available storage in client's browser.

import LocalStorage from "./localstorage"
import Cookie from "./cookie"

// Function to check availability of `localStorage`
function storageAvailable() {
    try {
        var storage = window["localStorage"],
            x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return false;
    }
}

export default function Storage() {
  return storageAvailable() ? LocalStorage : Cookie
}

Using above module:

function login(redirect = '/home') {
  // set your session data
  storage.set({email, id})

  // redirection
  window.location.href = redirect
}

function logout(redirect = "/") {
  storage.clear()

  // redirection
  window.location.href = redirect
}
const Session = {
  login,
  logout
}

export default Session

Now you can simply use your Session module for login and logout as Session.login() and Session.logut() respectively.

How to use cookie: How do I create and read a value from cookie?

How to use localStorage: Storing Objects in HTML5 localStorage

madhurgarg
  • 1,301
  • 2
  • 11
  • 17
  • You imported from "./localstorage". So, do I need to write anything for localstorage? – Mohammad Ashraful Islam Aug 29 '17 at 07:16
  • ".localstorage" and "./cookie" are modules for setting localstorage and cookie. You can create getter and setter for setting and getting storage data. I have added links on how to use localstorage and cookie. – madhurgarg Aug 29 '17 at 07:17
  • @AshrafulIslam Yes "./localstorage" . is your actual code that will set your storage data. I just showed you an abstract way of doing it properly. You can set your authentication token or any data you need after login in your storage. – madhurgarg Aug 29 '17 at 07:18
0

You can use universal-cookie package to set it in the cookie,

const cookies = new Cookies();
cookies.set('token', this.token, { path: '/' });

Don't forget to import(or require) Cookies from universal-cookie.

You can retrieve it back using :

cookies.get('token');

Refer to https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie

You can save it in local storage as well :

localStorage.setItem('token', this.token);

But saving in the cookie would be a better idea, refer to :

Local Storage vs Cookies

sudheer singh
  • 862
  • 1
  • 9
  • 23