Skip to content

Instantly share code, notes, and snippets.

@olegpolyakov
Last active December 17, 2018 22:52
Show Gist options
  • Save olegpolyakov/33b0d47d9b14dca7e8491b2bbe2f67ab to your computer and use it in GitHub Desktop.
Save olegpolyakov/33b0d47d9b14dca7e8491b2bbe2f67ab to your computer and use it in GitHub Desktop.
JWT for React
import React from 'react';
let cachedToken;
function setToken(token) {
cachedToken = token;
localStorage.setItem('authToken', token);
}
function getToken() {
if (!cachedToken) {
cachedToken = localStorage.getItem('authToken');
}
return cachedToken;
}
function removeToken() {
cachedToken = null;
localStorage.removeItem('authToken');
}
function isAuthenticated() {
return !!getToken();
}
axios.post('https://localhost:5000/api/auth', { 'Authorization': `Bearer ${token}` })
.then(response => response.data)
.then(token => setToken(token));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment