- Notifications
You must be signed in to change notification settings - Fork112
The simplest way to add authentication to your React app. Supports various providers.
License
Swizec/useAuth
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
useAuth is designed to be quick to setup. You'll need an account with Auth0 or Netlify Identity and the appropriate access keys.
$ yarn add react-use-authDownloads from npm, adds to your package.json, etc. You can use npm as well.
useAuth does not install its own authentication clients. Instead they're marked as peer dependencies.
Installauth0-js ornetlify-identity-widget depending on what you'd like to use. More coming soon :)
$ yarn add auth0-jsor
$ yarn add netlify-identity-widgetYou'll see warnings about missing peer dependencies for the client you aren't using. That's okay.
useAuth uses an<AuthConfig> component to configure your authentication client. We use XState behind the scenes to manage authentication state for you.
EnsureAuthConfig renders on every page.
With Gatsby, add it togatsby-browser.js. With NextJS,_app.js is best. You don'tneed to wrap your component tree, but you can if you prefer. We make sure useAuth doesn't break server-side rendering. ✌️
// gatsby-browser.jsimport*asReactfrom"react";import{navigate}from"gatsby";import{AuthConfig}from"react-use-auth";import{Auth0}from"react-use-auth/auth0";exportconstwrapRootElement=({ element})=>(<><AuthConfignavigate={navigate}authProvider={Auth0}params={{domain:"useauth.auth0.com",clientID:"GjWNFNOHqlino7lQNjBwEywalaYtbIzh"}}/>{element}</>);
<AuthConfig> initializes the global XState state machine, sets up an Auth0 client, and validates user sessions on every load. You now have easy access to authentication in your whole app :)
The config options are:
navigate– your navigation function, used for redirects. Tested with Gatsby, NextJS, and React Router. Anything should work.authProvider– the useAuth interface to your authentication provider.params– parameters for your authentication provider
useAuth client wrappers provide smart defaults.
More detail on using custom configuration for each client inUse with Auth0, andUse with Netlify Identity. To learn about how this works, go toCreate an auth provider
PS: feel free to use my Auth0 domain and clientID to see ifuseAuth is a good fit for you. That's why they're visible in the code snippet 😊
Auth0 and most other authentication providers use OAuth. That requires redirecting your user to their login form. After login, the provider redirects users back to your app.
You can skip this step with Netlify Identity. It uses an in-page popup.
Any way of creating React pages should work, here's the code I use for Gatsby:
import*asReactfrom"react"import{useAuth}from"react-use-auth"constAuth0CallbackPage=()=>{const{ handleAuthentication}=useAuth()React.useEffect(()=>{handleAuthentication()},[handleAuthentication])return(<h1> This is the auth callback page, you should be redirected immediately!</h1>)}exportdefaultAuth0CallbackPage
The goal is to load a page, briefly show some text, and run thehandleAuthentication method fromuseAuth on page load.
That method will create a cookie in local storage with your user's information and redirect back to homepage. You can pass apostLoginRoute param to redirect to a different page.
Make sure you add<domain>/auth0_callback as a valid callback URL in your Auth0 config.
You're ready to useuseAuth for authentication in your React app. 🤘
Here's a login button for example:
constLogin=()=>{const{ isAuthenticated, login, logout}=useAuth();if(isAuthenticated()){return<ButtononClick={logout}>Logout</Button>;}else{return<ButtononClick={login}>Login</Button>;}};
isAuthenticated is a method that checks if the user's cookie is still valid.
login andlogout trigger their respective actions.
You can even say hello to your users:
// src/pages/index.jsconstIndexPage=()=>{const{ isAuthenticated, user}=useAuth()return(<Layout><SEOtitle="Home"/><h1>Hi{isAuthenticated() ?user.name :"people"}</h1> )}
CheckisAuthenticated then use theuser object. ✌️
For more detailed docs visituseAuth.dev
You can try it out here 👉https://gatsby-useauth-example.now.sh/
👤Swizec Tellerswizec@swizec.com
- Github:@swizec
- Twitter:@swizec
- Blog:swizec.com/blog
Contributions, issues and feature requests are welcome!
Feel free to checkissues page.
I am looking to support other authentication providers. Please help :)
Give a ⭐️ if this project helped you!
Copyright © 2019Swizec Tellerswizec@swizec.com.
This project isMIT licensed.
This README was generated with ❤️ byreadme-md-generator
Thanks goes to these wonderful people (emoji key):
This project follows theall-contributors specification. Contributions of any kind welcome!
About
The simplest way to add authentication to your React app. Supports various providers.
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
