Question Regarding my Javascript Web Token Workflow

Hi FCC,

I had a question regarding JWT implementation with react. I am building my voting app right now and have implemented authentication in this pattern: post to /login, verify username and password, if everything is correct create a JWT and send it back to the browser, save in localStorage and then redirect the user to the dashboard etc.

Currently, several of my pages (or even individual components like my navbar) will need to know if there is a user logged in or not. What I was planning on doing with is — before any of these components/pages render (my navbar, my signup page, my registration page, my dashboard page etc) In componentWillMount or something I will fire off an AJAX request to the server including the JWT. The JWT will be verified server side and the server will send back the information needed (username, etc). In the callback of the AJAX request i can then setState of the component or page based off of the information sent back from the server in the JWT. So for in the Navbar for instance I would render the username of the logged in user, and a logout button etc.

Is this considered a hacky or clunky implementation? Could all of these components or pages just check to see if there is a token in local history instead and skip verification? I feel like sending an AJAX request before every authentication dependant component or page mounts may be a bit excessive or inefficient. Is there a better way of approaching this or something that I am missing here?

Thank you very much for your input!

Multiple authentication checks to render components does seem excessive.

The only thing you can reliably “protect” is data stored server-side behind your API. You should authenticate every API request for non-public data and every request to modify data. Once you send data (example, a user name) to the client there’s no sense trying to protect it further. Just render components that need it when it’s available.

The UI is really just a convenient interface to let the client interact with your API. It helps them see what they can and can’t do based on their current authentication state. The UI is not itself a security measure. That’s all handled server-side.