Most of the below is based on the tutorials avalible at digitalocean.com
Token storage
When adding Authentication
(asking the user to type in login details) the details (normally a token) need to be store somewhere.
The common options are:
- localStorage (for all tabs, only cleared by you, could be a security concearn)
- sessionStorage (just for that tab, lost when the tab is closed but remains when the tab is refreshed)
- redux or context
- cookies (considered deprecated)
Implementation
Build an API that returns a JWT
Create a custom hook, this will provide
setToken
Create a login component at
/src/components/Login/Login.js
1 | import React, { useState } from 'react'; |
- At the App level display the component for all routes but conditionally hide it based on the existance of the token
1 | const App = () => { |
- So now once the user authenticates the usage of
useState
in the custom hook will cause a re-render.
Boom, the user is logged in.
Note that getToken
would need to be exported if you want to include the token in subsequent API calls to the BFF.