Classius
Tech Stack (MERN)
• React
• Redux
• Tailwind CSS
• NodeJS
• Express
• MongoDB
This website collects cookies to deliver better user experience
react
react-router
res.redirect
function which redirects the user with NodeJS, but that won't do anything here because the frontend and backend are on different ports. Basically, the backend can't redirect the frontend because it can only send data and receive data from it. Since we can't use express for routing, we must thus use react-router.Content-type: "application/json"
and x-access-token: localStorage.getItem("token")
. localhost:BACKEND_PORT/exampleroute
if we set a proxy in our package.json to proxy the backend, and we can instead just write /exampleroute
.then
afterwards to get back any data we pass back from the backend after processing the requestWe first handle the form submission by grabbing the inputs and making a request to our login route which handles the validation, confirms the user exists, and signs a json web token for the user's session. Once the request has been fulfilled, we set the token we received from the backend or we display an error message
We are using localStorage to set this token so that it persists a page refresh and is global to our application but there are many pros and cons about saving tokens in localStorage which I will discuss later
This leads us right to our second block of code which is the useEffect. This code calls on our '/isUserAuth' route which has the sole purpose of confirming if the user is logged in. It does this by verifying that we have the right token. This is why need to send the x-access-token
header. If the login fails, nothing will happen, but if the user successfully logs in, the json web token will be confirmed and we will use React Router's history API to redirect the user to our home page. Since the useEffect is run whenever the component is mounted, we are also ensured that a logged in user can not access the login page since they will always be immediately redirected with this useEffect call.
We finally have our simple login form which uses an onSubmit
event to transfer the data
history.go(0)
)