Sam Sam - 22 days ago 6
React JSX Question

Checking authentication in React

How do I check if user is authenticated in my React component?

class MyComponent extends Component {

var isAuthenticated = false; // How do I check if the user is authenticated?
var message = "Hello stranger!";

if(isAuthenticated) {
message = "Hello friend!";
}

render() {
return(
<div>
{message}
</div>
);
}
}

Answer

you need to have a way to surface your auth to the frontend. lets say you have an api called user/validate the purpose of that api is to return an authenticated flag and whatever else you want like the server auth token or something. you need a method to request that information. I'm assuming you have a way to make requests to api methods already setup.

make a function to request this authentication.

export const checkAuth = () => {
    const url = `${api_route}/user/validate`;
    // this is just pseudo code to give you an idea of how to do it
    someRequestMethod(url, (resp) => {
        if (resp.status === 200 && resp.data.isAuthenticated === true) {
            setCookie(STORAGE_KEY, resp.data.token);
        }
    });
}

your base app component would look something like this

export default class App extends Component {
    constructor() {
        super();
        checkAuth();
    }
    ....
}

now your component could do something like this.

class MyComponent extends Component {
   constructor(){
      super()
      this.isAuthenticated = getCookie(STORAGE_KEY);
   }

   render() {
      return(
         <div>
             Hello {this.isAuthenticated ? 'friend' : 'stranger'} !
         </div>
      );
   }
}

your getCookie and setCookie methods would be something like this

export const setCookie = (name, value, days, path = '/') => {
    let expires = '';
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = `; expires=${date.toUTCString()};`;
    } 
    document.cookie = `${name}=${value}${expires}; path=${path}`;
};

export const getCookie = (cookieName) => {
    if (document.cookie.length > 0) {
        let cookieStart = document.cookie.indexOf(cookieName + '=');
        if (cookieStart !== -1) {
            cookieStart = cookieStart + cookieName.length + 1;
            let cookieEnd = document.cookie.indexOf(';', cookieStart);
            if (cookieEnd === -1) {
                cookieEnd = document.cookie.length;
            }
            return window.unescape(document.cookie.substring(cookieStart, cookieEnd));
        }
    }
    return '';
};

Now... I would strongly recommend you look at adding something like Redux to handle passing data around via props. This way you can have one storage method that does the getCookie and sets it up right away and everything else will have isAuthenticated as a flag in the props