Omg I just built the simplest way to add authentication to your React app. Should seriously open source it
Handles everything for you. Users, login forms, redirects, sharing state between components. Everything
So I did 😎
Announcing useAuth
useAuth
is the simplest way to add authentication to your React app. Handles everything for you – user management, cookies, sharing state between components, login forms, everything you need to get started.
A lot of that is handled through Auth0 right now and I'm very open to adding other providers. I like Auth0 because it's free for way more users than I'll ever have and it isn't Google 😛
You can try it out here 👉 https://gatsby-useauth-example.now.sh/
See the code here 👉 https://github.com/Swizec/useAuth
Example code here 👉 https://github.com/Swizec/useAuth/tree/master/examples/useauth-gatsby
How to use useAuth
useAuth
is designed to be quick to setup. You'll need an Auth0 account with an app domain and client id.
1. Install the hook
Downloads from npm, adds to your package.json, etc. You can use npm
as well.
2. Set up AuthProvider
useAuth uses an AuthProvider
component to configure the Auth0 client and share state between components. It's using React context with a reducer behind the scenes, but that's an implementation detail.
I recommend adding this around your root component. In Gatsby that's done in gatsby-browser.js
and gatsby-ssr.js
. Yes useAuth
is built so it doesn't break server-side rendering. ✌️
But of course server-side "you" will always be logged out.
<AuthProvider>
creates a context, sets up a state reducer, initializes an Auth0 client and so on. Everything you need for authentication to work in your whole app :)
The API takes a couple config options:
navigate
– your navigation function, used for redirects. I've tested with Gatsby, but anything should workauth0_domain
– from your Auth0 appauth0_client_id
– from your Auth0 appauth0_params
– an object that lets you overwrite any of the default Auth0 client parameters
PS: even though Auth doesn't do anything server-side, useAuth will throw errors during build, if its context doesn't exist
Default Auth0 params
By default useAuth
's Auth0 client uses these params:
domain
and clientID
come from your props.
redirectUri
is set to use the auth0_callback
page on the current domain. Auth0 redirects here after users login so you can set cookies and stuff. useAuth
will handle this for you ✌️
audience
is set to use api/v2. I know this is necessary but honestly have been copypasting it through several of my projects.
responseType
same here. I copy paste this from old projects so I figured it's a good default.
scope
you need openid
for social logins and to be able to fetch user profiles after authentication. Profile and Email too. You can add more via the auth0_params
override.
3. 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 the user back to your app.
Any way of creating React pages should work, here's what I use for Gatsby.
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. Redirecting to other post-login pages currently isn't supported but is a good idea now that I thought of it 🤔
PS: Make sure you add <domain>/auth0_callback
as a valid callback URL in your Auth0 config
4. Enjoy useAuth
You're ready to use useAuth
for authentication in your React app.
Here's a login button for example:
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
Check isAuthenticated
then use the user object. Simple as that.
You can try it out here 👉 https://gatsby-useauth-example.now.sh/
See the code here 👉 https://github.com/Swizec/useAuth
Example code here 👉 https://github.com/Swizec/useAuth/tree/master/examples/useauth-gatsby
Hope you like it :)
Cheers,
~Swizec
PS: we'll be using and talking about useAuth in more depth at my Barcelona workshop in September
Continue reading about useAuth – the simplest way to add authentication to your React app
Semantically similar articles hand-picked by GPT-4
- How to set up Gatsby and Auth0 for easy authentication on your next project
- useReducer + useContext for easy global state without libraries
- [CodeWithSwiz 21] useAuth beta support for Firebase 🎉
- React context without context, using XState – CodeWithSwiz 14, 15
- Add granular role-based access to your JAMStack app
Learned something new?
Read more Software Engineering Lessons from Production
I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.
Subscribe below 👇
Software Engineering Lessons from Production
Join Swizec's Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️