All Projects → Swizec → Useauth

Swizec / Useauth

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

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Useauth

Reflexjs
Starter kits, themes and blocks to help you build Gatsby and Next.js sites faster. Built on top of a best-in-class styling library.
Stars: ✭ 571 (-77.45%)
Mutual labels:  gatsby, nextjs
Nextjs Auth0
Next.js SDK for signing in with Auth0
Stars: ✭ 690 (-72.75%)
Mutual labels:  nextjs, auth0
Ram
⚛️ React Application Manager: create and run React (and other) applications – no command line or build setup required
Stars: ✭ 585 (-76.9%)
Mutual labels:  gatsby, nextjs
Material Kit React
React Dashboard made with Material UI’s components. Our pro template contains features like TypeScript version, authentication system with Firebase and Auth0 plus many other
Stars: ✭ 3,465 (+36.85%)
Mutual labels:  auth0, nextjs
Mdx Embed
Embed 3rd party media content in MDX - no import required 🧽
Stars: ✭ 119 (-95.3%)
Mutual labels:  gatsby, nextjs
Jamstackthemes
A list of themes and starters for JAMstack sites.
Stars: ✭ 298 (-88.23%)
Mutual labels:  gatsby, nextjs
Tinacms
Open source editor that brings visual editing into React websites. A developer-centric CMS to build contextual and intuitive editing experience without sacrificing code quality.
Stars: ✭ 6,804 (+168.72%)
Mutual labels:  gatsby, nextjs
Graphcms Examples
Example projects to help you get started with GraphCMS
Stars: ✭ 295 (-88.35%)
Mutual labels:  gatsby, nextjs
Create Ueno App
The easiest and fastest way to create new web projects with next, gatsby, create-react-app and mobile projects with react-native.
Stars: ✭ 116 (-95.42%)
Mutual labels:  gatsby, nextjs
Jamstack Ecommerce
A starter project for building performant ECommerce applications with Next.js and React
Stars: ✭ 1,384 (-45.34%)
Mutual labels:  gatsby, nextjs
Pizzaql
🍕 Modern OSS Order Management System for Pizza Restaurants
Stars: ✭ 631 (-75.08%)
Mutual labels:  nextjs, auth0
Actions Gh Pages
GitHub Actions for GitHub Pages 🚀 Deploy static files and publish your site easily. Static-Site-Generators-friendly.
Stars: ✭ 2,576 (+1.74%)
Mutual labels:  gatsby, nextjs
Reactime
Chrome extension for improving and optimizing performance in React applications (Gatsby and Next.js compatible).
Stars: ✭ 1,219 (-51.86%)
Mutual labels:  gatsby, nextjs
Nitro
An Example of a PWA using Nextjs, Material-UI, Typescript and Auth0 💗
Stars: ✭ 130 (-94.87%)
Mutual labels:  nextjs, auth0
Startup Landing
Collection of free top of the line startup landing templates built using react/nextjs/gatsby. Free to download, simply edit and deploy! Updated weekly!
Stars: ✭ 176 (-93.05%)
Mutual labels:  gatsby, nextjs
Next Routes
Universal dynamic routes for Next.js
Stars: ✭ 2,354 (-7.03%)
Mutual labels:  nextjs
Starter Pack
Combines React (ft. hooks), Redux, Redux-saga and TypeScript with Auth0 as a starting point for modern web apps with solid authentication
Stars: ✭ 209 (-91.75%)
Mutual labels:  auth0
Saas
Build your own SaaS business with SaaS boilerplate. Productive stack: React, Material-UI, Next, MobX, WebSockets, Express, Node, Mongoose, MongoDB. Written with TypeScript.
Stars: ✭ 2,720 (+7.42%)
Mutual labels:  nextjs
Timelite
Why is it 5 AM? Isn't there something simple I can use to track what I'm doing with all this time?
Stars: ✭ 201 (-92.06%)
Mutual labels:  nextjs
Next Blog
基于react(ssr)服务端框架next.js和antd-design搭建的个人博客
Stars: ✭ 214 (-91.55%)
Mutual labels:  nextjs

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!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].