Protected page with Reactjs

Maya Treacy
AnitaB.org Open Source
2 min readJul 13, 2020

Week 6 GSoC 2020 — Second Coding Phase with AnitaB.Org

Photo by Yaroslav Danylchenko from Pexels

No…, this blog is not about Covid19. But please, DO TAKE THE MESSAGE OF THE PICTURE ABOVE SERIOUSLY. Protect yourself, family and others from Covid19 by wearing mask when going out and keep your hand clean by sanitizing them often.…. 🙏

Ok, now let’s get down to business.

I’m going to share what I have learned this week on BridgeInTech Frontend development which is how to protect private pages on the Reactjs web application. This protected page is used with User Login functionality.

This will be a quick blog since probably it’ll be more straight forward and much clearer to look at the code itself rather than reading my explanation 😁. I’ll try to give a brief explanation though.

What I have learned this week…

This task was achieved using the create-react-app with added dependencies react-bootstrap, react-router-dom and js-cookie

Here, cookies are used to store the user’s name and token that are received from user input on Login form and sending POST /login request. They are then used with React Context to be passed on the pages that require user token for that page to be accessible (aka protected page). useEffect helps setting the state of the authentication based on whether user opt to login or logout from the application.

On the Navbar, useContext with the state of authentication (isAuth) is used to toggle between Register/Login or Logout menu option.

Below is the Navigation.js.

Route.js is used as the first filter that helps direct the next step where the application need to go to when user select any menu from the Navigation.js. Here, the page that should be accessible only when user is authenticated is wrapped with the <ProtectedRoute /> .

Below is the Route.js file:

Finally, the ProtectedRoute that is protecting the page helps determine whether to render the page being protected, or, if user is not authenticated, to redirect user back to the Home page.

Ok. That’s it. Pretty short blog, isn’t it? Hope this helps anyone who’s also looking for few tips on similar functionality 😉.

Until next week…… 👋.

Profile Link:

LinkedIn | Github | Online resume

--

--

Maya Treacy
AnitaB.org Open Source

Master of IT student / Software Developer / GSoC20 Student with AnitaB.org / Passionate learner