👋

Authentication

useAuth

Your codebase includes a convenient useAuth hook that allows you to get the currently authenticated user and automatically re-render components when the user changes.

Here's how easy it is:

import { useAuth } from './../util/auth.js';

function MyComponent(){
  // Get the auth object
  const auth = useAuth();

  // Depending on auth state show signin or signout button.
  // auth.user will either be an object, null when loading,
  // or false if signed out.
  return (
    <div>
      {auth.user ? (
        <button onClick={(e) => auth.signout()}>Signout</button>
      ) : (
        <button onClick={(e) => {
					auth.signin('hello@divjoy.com', 'yolo');
				}}>
					Signin
				</button>
      )}
    </div>
  );
}

requireAuth

We also give you a requireAuth higher order component that is used to require that a user be authenticated before viewing a page. If the user's authentication status is still loading then this will display a loading indicator. If the user is not logged in then it will automatically redirect to your /auth/signin route.

Here's how you use it:

import { requireAuth } from "./../util/auth.js";

function DashboardPage(props) {
	return (
	  // Components here
	);
}

export default requireAuth(DashboardPage);

If your codebase contains server logic that needs to know the authenticated user (such as Stripe payments) then we include a similar, server-side version of this function in api/_require-auth.js. This will return an error in the API response if the user isn't authenticated.

Your auth provider

The actual logic for your auth provider, such as Firebase or Auth0, is located in src/util/auth.js. It wraps your providers authentication logic and uses React context to expose the provider methods (such as signup function) and authenticated user to any components that call the useAuth hook.

It also has the following functionality, which can be toggled on/off:

  • Automatically merge extra user data from your database into the auth object so that you don't have to do subsequent database queries to fetch that extra user data (for example their Stripe subscription ID). It's handy having all the user-related data available on page load without needing to worry about loading states.
  • If you're using analytics in your codebase it will automatically call analytics.identify() with the current user.uid so that the analytics session is connected to the user across browsers.
  • Automatically sends a verification email on signup

Files

  • src/util/auth.js
  • api/_require-auth.js

🗣

Any questions you have that aren't answered here? Please reach out and let us know. We'll answer your question and then improve the docs for others.