• Stars
    star
    2,591
  • Rank 17,611 (Top 0.4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The simplest way to add authentication to your React app. Supports various providers.

useAuth

the quickest way to add authentication to your React app

All Contributors Version License: MIT

useAuth.dev

Getting Started

useAuth is designed to be quick to setup. You'll need an account with Auth0 or Netlify Identity and the appropriate access keys.

1. Install the hook

$ yarn add react-use-auth

Downloads from npm, adds to your package.json, etc. You can use npm as well.

2. Install your auth client

useAuth does not install its own authentication clients. Instead they're marked as peer dependencies.

Install auth0-js or netlify-identity-widget depending on what you'd like to use. More coming soon :)

$ yarn add auth0-js

or

$ yarn add netlify-identity-widget

You'll see warnings about missing peer dependencies for the client you aren't using. That's okay.

3. Configure with AuthConfig

useAuth uses an <AuthConfig> component to configure your authentication client. We use XState behind the scenes to manage authentication state for you.

Ensure AuthConfig renders on every page.

With Gatsby, add it to gatsby-browser.js. With NextJS, _app.js is best. You don't need to wrap your component tree, but you can if you prefer. We make sure useAuth doesn't break server-side rendering. โœŒ๏ธ

// gatsby-browser.js
import * as React from "react";
import { navigate } from "gatsby";

import { AuthConfig } from "react-use-auth";
import { Auth0 } from "react-use-auth/auth0";

export const wrapRootElement = ({ element }) => (
    <>
        <AuthConfig
            navigate={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:

  1. navigate โ€“ your navigation function, used for redirects. Tested with Gatsby, NextJS, and React Router. Anything should work.

  2. authProvider โ€“ย the useAuth interface to your authentication provider.

  3. params โ€“ parameters for your authentication provider

useAuth client wrappers provide smart defaults.

More detail on using custom configuration for each client in Use with Auth0, and Use with Netlify Identity. To learn about how this works, go to Create an auth provider

PS: feel free to use my Auth0 domain and clientID to see if useAuth is a good fit for you. That's why they're visible in the code snippet ๐Ÿ˜Š

4. Create the callback page

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 * as React from "react"
import { useAuth } from "react-use-auth"

const Auth0CallbackPage = () => {
    const { handleAuthentication } = useAuth()
    React.useEffect(() => {
        handleAuthentication()
    }, [handleAuthentication])

    return (
        <h1>
            This is the auth callback page,
            you should be redirected immediately!
        </h1>
    )
}

export default Auth0CallbackPage

The goal is to load a page, briefly show some text, and run the handleAuthentication method from useAuth 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 a postLoginRoute param to redirect to a different page.

Make sure you add <domain>/auth0_callback as a valid callback URL in your Auth0 config.

5. Enjoy useAuth

You're ready to use useAuth for authentication in your React app. ๐Ÿค˜

Here's a login button for example:

const Login = () => {
    const { isAuthenticated, login, logout } = useAuth();

    if (isAuthenticated()) {
        return <Button onClick={logout}>Logout</Button>;
    } else {
        return <Button onClick={login}>Login</Button>;
    }
};

isAuthenticated is a method that checks if the user's cookie is still valid.

login and logout trigger their respective actions.

You can even say hello to your users:

// src/pages/index.js

const IndexPage = () => {
  const { isAuthenticated, user } = useAuth()

  return (
    <Layout>
      <SEO title="Home" />
      <h1>Hi {isAuthenticated() ? user.name : "people"}</h1>
  )
}

Check isAuthenticated then use the user object. โœŒ๏ธ


For more detailed docs visit useAuth.dev


You can try it out here ๐Ÿ‘‰ https://gatsby-useauth-example.now.sh/

Author

๐Ÿ‘ค Swizec Teller [email protected]

๐Ÿค Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page.

I am looking to support other authentication providers. Please help :)

Show your support

Give a โญ๏ธ if this project helped you!

๐Ÿ“ License

Copyright ยฉ 2019 Swizec Teller [email protected].
This project is MIT licensed.


This README was generated with โค๏ธ by readme-md-generator

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Dejan

๐Ÿ’ก

Jason Miller

๐Ÿ’ป

Graham Barber

๐Ÿ’ฌ

Mateus Gabi

๐Ÿ“–

Jorge Galat

๐Ÿ’ป

Swizec Teller

๐Ÿ’ป ๐Ÿ“– ๐Ÿ“ ๐Ÿ’ก ๐Ÿšง

Nick Richmond

๐Ÿ’ป

Ollie Monk

๐Ÿ“– ๐Ÿ’ป

Henrik Wenz

๐Ÿ›

Max Chehab

๐Ÿ“–

Joel Bartlett

๐Ÿ’ป

SIDDIK MEHDI

๐Ÿ’ป

Jess

๐Ÿ›

Jorge Cuadra

๐Ÿ“–

ร˜yvind Marthinsen

๐Ÿ’ป

Fredrik Sรธgaard

๐Ÿ’ป

Artem Rudenko

๐Ÿ’ป

Travers Pinkerton

๐Ÿ’ป

Eric Hodges

๐Ÿ’ป

Devin Fitzsimons

๐Ÿ“–

Jason Laster

๐Ÿ“– ๐Ÿ’ป ๐Ÿ›

Patrick Arminio

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

useDimensions

A React Hook to measure DOM nodes
TypeScript
585
star
2

nightowls

Why programmers work at night - a book about programmers, by a programmer
321
star
3

react-lazyload-fadein

React component to lazyload children with a nice fadein effect.
JavaScript
314
star
4

serverlesshandbook.dev

A resource for frontend engineers to learn everything about modern backend development.
JavaScript
286
star
5

react-fractals

An experiment -> Fractals in React.
JavaScript
225
star
6

react-particles-experiment

An experiment to see if you can make a particle generator in redux+react+d3.
JavaScript
176
star
7

lambda-screenshot-as-a-service

AWS Lambda Chrome Headless screenshots
TypeScript
142
star
8

thaw-carrots

Thaw carrots by warming up your laptop to a specific temperature
JavaScript
130
star
9

react-testing-example

A sample project to investigate testing options with ReactJS
JavaScript
113
star
10

node-unshortener

This simple library can take an short URL and discover its long counterpart while attempting to be nice and using the correct shortener's API.
JavaScript
90
star
11

d3blackbox

A simple React wrapper for any D3 code you want
TypeScript
85
star
12

h1b-software-salaries

Using React and d3.js, I built a visualisation of H1B salaries in the software industry.
HTML
83
star
13

better-fetch

A tiny ES6 fetch() wrapper that makes your life easier without drastic changes to the API.
JavaScript
80
star
14

styled-button

jQuery plugin for imageless buttons a la Google
JavaScript
68
star
15

react-d3-enter-exit-transitions

A proof of concept exploration of using d3js transitions in a React visualization.
JavaScript
61
star
16

nodestagram

A node.js library for instagr.am
JavaScript
58
star
17

webrtc-sample

Demo app to learn WebRTC. Communicates with itself via RTCPeerConnection
JavaScript
53
star
18

blockchain-redux

A crypto experiment, Redux-like store backed by blockchain.
JavaScript
49
star
19

react-d3js-es6-ebook

ES6 edition of React+d3js, a book about making modular data visualizations.
JavaScript
41
star
20

react-real-world

Proof of concept code that turns a React component into a jQuery plugin.
JavaScript
39
star
21

react-d3js-step-by-step

Step by step example for the React+D3v4 book.
JavaScript
39
star
22

ImgurApp

A better mobile pooping experience
JavaScript
39
star
23

ml-class-homework

MATLAB
38
star
24

random-coding

This is my playground. It's where experiments with new technology happen, benchmarks of different things. Many real projects start their life here.
Clojure
37
star
25

component-css-extractor

Extract CSS from any scoped styles in a component framework. In the browser.
JavaScript
37
star
26

checkbox-field

A jquery plugin that turns multiselect fields into a field of checkboxes.
JavaScript
36
star
27

d3.js-book-examples

Haphazard collection of examples for a book.
CSS
36
star
28

Le-Thesis

For my undergrad thesis I am building an automatic poet. The idea is to implement an evolutionary algorithm that can construct a poem using fitness functions trained on a text-based corpora.
Haskell
32
star
29

webgl-airplanes-map

An experiment to build a live map of airplanes with WebGL and React
JavaScript
29
star
30

Personal-Runway

Every 3 days Personal-Runway predicts what my bank account will look like in two weeks and sends me an email. Income is gleamed from my Toggl account, expenses come from Toshl. The fetching and emailing logic is built with node.js, predictions and graphs in haskell.
JavaScript
29
star
31

space-invaders

Space Invaders clone in React and d3.js
JavaScript
26
star
32

web-session-counter

Utility to count a user's web sessions based on the definition GA uses.
JavaScript
23
star
33

article-threader

Smรถl tool that turns URLs into twitter threads
TypeScript
23
star
34

JustATributeApp

This is not the best app in the world, no, this is just a tribute.
JavaScript
22
star
35

ScholarStream.ai

A twitter-like experience for arXiv feeds using GPT
TypeScript
22
star
36

remark-code-screenshot

Remark plugin to turn code blocks into carbon.now.sh screenshots.
JavaScript
21
star
37

react-d3js-ebook

This is a baby project, things will show up soon.
JavaScript
20
star
38

learn-while-you-poop-react

No pressure learning at 2 minutes per day. Start with WHY React all the way to a React 16.3 master in a month.
JavaScript
19
star
39

server-side-d3-poc

Trying out server-side D3 rendering with React 16
JavaScript
18
star
40

declarative-canvas-react-konva

Declarative animation rendered with <canvas> built with React and Konva
JavaScript
18
star
41

corona-simulation

An experiment to simulate viral spread of Covid19 under different conditions
JavaScript
17
star
42

spark-joy

A little widget to ask your fans if what you made sparked joy :)
JavaScript
15
star
43

letter-builder

Build better technical newsletters and emails
JavaScript
14
star
44

Generative-poetry

Trying to find an algorithm to generate poetry
Python
14
star
45

migrations-map

A map of global migrations built from the UN dataset.
JavaScript
13
star
46

personal-dashboard

An experiment in visualising personal data.
JavaScript
13
star
47

dom-benchmark

An experiment to see which is faster at DOM manipulation because I'm curious.
JavaScript
13
star
48

hot-dog-taco

What if I told you modern tools let you build and launch a small webapp in 30 minutes?
CSS
13
star
49

d3-course-examples

Examples for a d3.js video course
JavaScript
12
star
50

lolcode-babel-macro

LOLCODE implementation with Babel macros
JavaScript
11
star
51

react-d3js-landing-page

The landing page for React+d3.js
HTML
10
star
52

es6-cheatsheet

Modern JavaScript cheatsheet
CSS
10
star
53

markdownlandingpage.com

A quick landing page for anyone
JavaScript
10
star
54

sharethisemail

A service to generate Share This Email mailto links
JavaScript
10
star
55

react-d3-pie

An example piechart built with React and D3 to try some things out.
JavaScript
9
star
56

markdown-to-tweet

A library that takes markdown and turns it into tweets
JavaScript
9
star
57

modern-webapp-starter-sep-2019

Starter repo for https://2019.fullstackfest.com/workshops/build-and-launch-jamstack-react-graphql-serverless/
JavaScript
9
star
58

d3-pong

Abusing d3.js to make a pong game.
CSS
9
star
59

log-viewer

A searchable <LogViewer> component built with Downshift and match-sorter
JavaScript
8
star
60

threadcompiler.com

A simple app for writing and scheduling tweet threads
JavaScript
8
star
61

livecoding-project

The description of a livecoding project, which shows stuff and visualizations in React and d3.
HTML
8
star
62

graphql-rest-proxy

Proof of concept GraphQL wrapper of a real world REST API
TypeScript
7
star
63

bigmac-index-price-calculator

Pricing based on Big Mac Index purchasing power parity ๐Ÿ”
TypeScript
7
star
64

something-3d

An experiment in compositional three.js
JavaScript
7
star
65

mondrian-generator

Generate mondrian style art boards with React and D3
JavaScript
7
star
66

mobx-clock-example

A quick example of modeling time as part of React application state
JavaScript
6
star
67

faux-js-ai

A faux AI that writes JavaScript. You write the tests, AI makes them pass.
JavaScript
6
star
68

react-d3-walkthrough-livecode

A livecode walkthtrough to go with the book
JavaScript
6
star
69

mortys-mindblowers

Morty's Mindblowers from Imgur frontpage
JavaScript
6
star
70

toshl.js

Toshl client library for node.js
JavaScript
6
star
71

ar-js-experiment

Playing around with AR.js
JavaScript
6
star
72

react-indie-bundle-donations

Suggest a JS Ecosystem Creator we should donate to.
6
star
73

compilers-homework

A Pascal compiler written for a class on compilers. Compiles to intermediate code, then uses an interpreter to run programs.
Java
6
star
74

rapid.queue

rapid.queue is a lightweight boss+queue+workers system built on node.js with a redis backend.
JavaScript
5
star
75

simple-dynamodb

A simple wrapper I've been using to help work with DynamoDB
TypeScript
5
star
76

learnwhileyoupoop.com

A landing page for the Learn While You Poop project
CSS
5
star
77

react-d3-flamegraph

Flamegraph implemented in React & D3
JavaScript
5
star
78

serverless-workshop-exercises

Exercises and their solutions for serverless workshop
TypeScript
5
star
79

irc-stats-bot

An experiment in creating an irc stats bot that pushes statistics about an irc channel to graphite ... in node.js
JavaScript
5
star
80

github-nightowls

The scripts I used/use to get a dataset of 500k Github repositories.
JavaScript
5
star
81

gatsby-suspense-poc

A proof-of-concept for using react suspense with Gatsby
JavaScript
5
star
82

swizec-blog

swizec.com/blog
JavaScript
5
star
83

twitter-lite-embed

The fastest most privacy focused Twitter embed component.
TypeScript
4
star
84

react-d3-workshop

React and D3v4 workshop, it's better in person
JavaScript
4
star
85

intro-to-react-workshop

Intro to React Workshop. It's better in person ๐Ÿ˜‰
JavaScript
4
star
86

HipsterVision

A fun app for playing around with Instragram's new API in node.js
PHP
4
star
87

remark-utf8

Remark plugin to transform basic markdown into utf8 special characters.
JavaScript
4
star
88

svelte-marvel-movie-timeline

A simple Marvel movie timeline built with Svelte
JavaScript
4
star
89

swizec.com

Blog and website on swizec.com
MDX
4
star
90

lovebox-lambda

AWS Lambda that sends daily random photos from an S3 bucket
TypeScript
4
star
91

750words-analysis

This is an analysis of my 750words.com writings
Python
4
star
92

doorbell-app

Answer the front gate buzzer via SMS, uses serverless and twilio
TypeScript
4
star
93

node-project-boilerplate

Boilerplate I use for node.js projects
JavaScript
4
star
94

moores-law

Visualizing Moore's law compared to actual transistor count like in https://www.youtube.com/watch?v=7uvUiq_jTLM&feature=youtu.be
JavaScript
4
star
95

react-d3-gallery

A gallery carousel for things built with React and d3
HTML
3
star
96

gatsby-remark-giphy

Embed giphy search results with ![](giphy:search_term)
TypeScript
3
star
97

mobx-modal

An example project that implements MobX driven modals.
JavaScript
3
star
98

chat-blockchain-redux-demo

Demo chat app using blockchain-redux built for WeAreDevs 2018
JavaScript
3
star
99

react-animated-pie

Example animated piechart in React and D3
JavaScript
3
star
100

thefantastic.me

A project to make people more awesome.
JavaScript
3
star