Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

This demo app enhances my previous React Router Events project with user authentication. 🗝️ It includes toggleable login and signup forms, 🛡️ maintains user login status, ⏱️ features auto-logout, and 🚧 protects certain routes for logged-in users only. The UI updates based on the user's authentication status.

NotificationsYou must be signed in to change notification settings

sofiane-abou-abderrahim/react-router-events-and-authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 

Repository files navigation

User Signup & Login

  • How Authentication Works in React Apps
  • Implementing User Authentication
  • Adding Authentication Persistence & Auto-Logout

Steps

0. Project Setup & Route Setup

  1. runcd backend/ &npm install &npm start
  2. runcd frontend/ &npm install &npm start
  3. set a way to go to theAuthentication.js page for a/auth route
    1. inApp.js, add a new route definition for thisauth route
    2. inMainNavigation.js, add an entry to the main navigation to navigate to the authentication page

1. Working with Query Parameters

  1. leverage query parameters inAuthForm.js
    1. get rid of the state
    2. replace the button with a<Link> & add to it theto attribute set to?mode & a value based on the currently selected mode
    3. manage yourmode with query parameters & access the currently set query parameter with theuseSearchParams hook
  2. updateMainNavigation.js so that when we clickAuthentication we load this login form by default

2. Implementing the Auth Action

  1. enable user creation with anaction
    1. inAuthentication.js, add anaction that is triggered when theForm inAuthForm.js is submitted
    2. get the data from the form withformData
    3. send different requests based on themode this form is in with help ofsearchParams
    4. send the request to the backend
    5. handle the response
  2. inApp.js, add this action to the route definitions

3. Validating User Input & Outputting Validation Errors

  1. inAuthForm.js, get theaction data with theuseActionData hook
  2. youraction function must return something and not only aredirect
  3. in our case it returns aresponse in case of 422 or 401 errors inAuthentication.js
  4. output that information to the user inAuthForm.js
  5. add an indicator that the form was submitted successfully & that we're waiting for the response with theuseNavigation hook

4. Attaching Auth Tokens to Outgoing Requests

  1. The login feature already works because theaction we created inAuthentication.js send a request based on the selected mode
  2. inAuthentication.js, attach the token we're getting back from the backend to requests to protect resources because now if you try to delete an event, you get an 401 unauthorized error
    1. extract from the backend
    2. store that token inlocalStorage after signing up or loging in
    3. in a newutil folder, add a newauth.js file where you add a helpergetAuthToken function to get that storedtoken when needed
    4. use thatgetAuthToken function inEventDetail.js for deleting events & inEventForm.js for adding and editing events

5. Adding User Logout

  1. inMainNavigation.js, add a newlogout navigation link
  2. the button should trigger anaction that deletes the token
    1. add a newLogout.js pages in thepages folder
    2. inside of it define anaction that clears thelocalStorage & gets rid of thetoken
  3. inApp.js, register a newlogout route
  4. inMainNavigation.js, send a request to this route by submitting a<Form> that targets this route

6. Updating the UI Based on Auth Status

  1. update the UI based on the existence of thetoken
    1. make thetoken easily available in your entire app (on all your routes basically)
    2. the information whether thetoken is available or not should be automatically updated so that the UI automatically updates
  2. to do so, you could use theuseContext hook
  3. but, leverage React Router for doing that
    1. inApp.js, in the root route, add aloader that takes a look atlocalStorage & extract thetoken from it
    2. React Router will reevaluate that, if we, for example, logout & update all the pages that use thatloader data
    3. inutil/auth.js, add thetokenLoader function & callgetAuthToken() inside of it & return its result
    4. in order to use the data from thattokenLoader & easily get access to it, assign anid with a value ofroot to that route
    5. inMainNavigation.js, use theuseRouteLoaderData hook to get thetoken by targetting theroot id
    6. conditionally show thatAuthentication link if thetoken doesn't exist (so when the user is not logged in)
    7. show theLogout link only when thetoken (so when the user is logged in)
    8. inEventsNavigation.js, use the same approach as inMainNavigation.js & show theNew Event link if there is atoken
    9. inEventItem.js, do the same to conditionally show theEdit &Delete menu

7. Adding Route Protection

  1. the user can still access a specific page that needs a token directly in the URL, like/events/new
  2. inApp.js, protect theedit &new routes so that there will not be accessible unless the user is logged in
    1. inutil/auth.js, add acheckAuthLoader function that checks if there is atoken & if not redirects the user away
    2. inApp.js, use thischeckAuthLoader to protect all these routes that need protection

8. Adding Automatic Logout

  1. inRoot.js, useuseEffect() to set a timer whenever theRootLayout is rendered which happens when this application starts
  2. useuseLoaderData() to get thetoken
  3. use thistoken as a dependency foruseEffect so that this effect function runs whenever thetoken changes
  4. set a timer that expires after 1 hour & that then triggers that logout action (basically sends a request to thatlogout route)
  5. for that, use theuseSubmit() hook to programmatically submit thatlogout form fromMainNavigation.js

9. Managing the Token Expiration

  1. inAuthentication.js, where you store the token, store the expiration time with help ofDate() etsetHours()
  2. inutil/auth.js, update thegetAuthToken() function to take a look at thisexpiration date & find out if the token expired with help of a newgetTokenDuration() function
  3. inRoot.js, trigger thelogout action, if the token duration expired
  4. if the token is not expired, set the timeout duration at the remaining lifetime of the token
  5. inLogout.js, remove theexpiration from thelocalStorage

About

This demo app enhances my previous React Router Events project with user authentication. 🗝️ It includes toggleable login and signup forms, 🛡️ maintains user login status, ⏱️ features auto-logout, and 🚧 protects certain routes for logged-in users only. The UI updates based on the user's authentication status.

Topics

Resources

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp