mauricioao / React-router_Auth_Router_Provider-

Created with StackBlitz ⚡️

Home Page:https://stackblitz.com/edit/github-fzy7ru-a5wst2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

title toc
Authentication (using RouterProvider)
false

Auth Example (using RouterProvider)

This example demonstrates how to restrict access to routes to authenticated users when using <RouterProvider>.

The primary difference compared to how authentication was handled in BrowserRouter is that since RouterProvider decouples fetching from rendering, we can no longer rely on React context and/or hooks to get our user authentication status. We need access to this information outside of the React tree so we can use it in our route loader and action functions.

For some background information on this design choice, please check out the Remixing React Router blog post and Ryan's When to Fetch talk from Reactathon.

Be sure to pay attention to the following features in this example:

  • The use of a standalone object outside of the React tree that manages our authentication state
  • The use of loader functions to check for user authentication
  • The use of redirect from the /protected loader when the user is not logged in
  • The use of a <Form> and an action to perform the login
  • The use of a from search param and a redirectTo hidden input to preserve the previous location so you can send the user there after they authenticate
  • The use of <Form replace> to replace the /login route in the history stack so the user doesn't return to the login page when clicking the back button after logging in
  • The use of a <fetcher.Form> and an action to perform the logout

Preview

Open this example on StackBlitz:

Open in StackBlitz

About

Created with StackBlitz ⚡️

https://stackblitz.com/edit/github-fzy7ru-a5wst2


Languages

Language:TypeScript 91.5%Language:CSS 4.5%Language:HTML 4.0%