Divjoy

Create a Next.js app with Auth0 and Cloud Firestore

a dev guide by Divjoy ✨

About this guide

This development guide walks you through everything you need to do to build a high-quality Next.js app integrated with Auth0 and Cloud Firestore. Check out the tasks below to get started. To save time, you can also use our boilerplate, which gives you a complete React codebase with all of these tasks done for you. Okay, let's dive in!

Tasks

  • ⚛Setup your Next.js app

    Create a Next.js app using npx create-next-app and then run your project locally with the npm run dev command.
  • 🅰️Extend the Auth0 library

    Create a file that wraps the auth0-js library and abstracts away the storage and retrieval of the user's access token. Auth functions, such as auth0.signupAndAuthorize() and auth0.client.login(), should store the access token in memory or local storage after executing. Add a function called getCurrentUser() that fetches the current user by passing the stored access token to auth0.client.userInfo(). Our auth logic in subsequent tasks can call this function to get the current user.
  • 🎣Create an Auth0 AuthProvider and useAuth hook

    Create an AuthProvider component that fetches the current user from Auth0, subscribes to changes, stores the user in state, and then makes all this data available to child components using Context.Provider. Make sure to update your Next.js App component so that AuthProvider wraps all your pages. You'll then create a useAuth hook that reads the user with useContext and returns its value. This will enable any component to call useAuthto get the current user and re-render when it changes.
  • 🔐Protect pages with an Auth0 requireAuth HOC

    Create a requireAuth higher order component for pages that should only be viewable by authenticated users. It should call your useAuth hook internally to get the current user, show a loading indicator while waiting on the response, and then either render the page or redirect to /signin depending on whether the user is authenticated.
  • 👥Merge extra user data from Cloud Firestore

    Update the useAuth React hook to automatically fetch extra user data from the Cloud Firestore users collection and merge it into the returned user object. This makes it easy to access extra user data (think username, subscription plan, etc) without needing to manage extra queries and loading states. Make sure to return an undefined user object while the query is pending so that the user isn't considered logged in until all data is ready.
  • 👩‍🚀Build your authentication UI

    Create an authentication UI using your component library of choice and Auth0 functions. You'll want routes for user sign-up, sign-in, forgot password, and change password. Make sure you properly validate inputs and display any errors returned by Auth0. You may also want to use a library, such as React Hook Form, for managing form state.
  • 👥Link user to analytics session

    You can connect Google Analytics sessions to the current authenticated user with the User ID feature. This allows you to see what your users are doing across sessions and devices. You'll need to update your useAuth hook to set the user_id property whenever the user changes.
  • 🆙Enable Auth0 email and password updating

    To allow users to update their email and password you'll need to setup an API endpoint. Create a Next.js API route at /pages/api/auth-user.js that uses the auth0 library and calls Auth0.ManagementClient.updateUser() to change this info. Make sure that Auth0.ManagementClient is instantiated with the credentials for a "Machine to Machine" app, instead of your client-side app credentials. You can then create an updateUser function in the Auth0 wrapper you previously setup that makes a request to this endpoint.
  • ☎️Create an Auth0 callback page

    In order to support social login via OAuth you'll need to setup an Auth0 callback page and specify it's path as the redirectUri value when calling auth0.popup.authorize(). This page should use the auth0-js library and call auth0.popup.callback() on load. This is what enables your app to get the authentication results after the OAuth flow has completed.
  • 👩‍❤️‍👨Get Auth0 working with Cloud Firestore

    In order to make authenticated requests to Cloud Firestore you'll need to setup an API route that generates a custom Firebase token. Create a Next.js API route at /pages/api/firebase-token.js that is passed the current Auth0 user's uid and returns a custom Firebase token with firebase.auth().createCustomToken(uid). Right after login you'll want to make a request to this API route and pass the retrieved token to signInWithCustomToken(auth, token). This ensures that your Firestore rules will be able to read the user'suid in order to dictate what queries the current user can make.
  • ⛅️Create Cloud Firestore query hooks

    Create React hooks that wrap your Cloud Firestore queries, such as useUser, useItem, and useItemsByUser. These hooks should subscribe to data using onSnapshot and return a query status of "success", "loading", or "error". The React Query library makes it especially easy to setup these hooks and have components re-render when data changes.
  • 👩‍🏫Add Firestore rules

    Be sure to specify your Firestore security rules so that your Firestore database is secure. For example, if you have a users collection you might ensure that the authenticated user can only update a doc if userDoc.uid matches their uid. If you have an items collection you might ensure that they can only update and fetch items where itemDoc.owner matches their uid. You'll also generally want to specify an array of fields that are writeable, as you wouldn't want a user to be able to change userDoc.planId without actually upgrading their plan.
  • ⚡Build a data-driven UI

    Create a data-driven UI using your component library of choice that reads/writes data to Cloud Firestore. The specifics will depend on the type of app you're building, but we generally recommend having a useItemsByOwner hook that fetches "items" in Cloud Firestore that are owned by the current user. You can then create a component for displaying that data in a simple list or table if more columns are needed. Finally, you'll want create a flow for creating and updating items utilizing modal and form components.

Get the code

You can get the code for this guide with our Next.js, Auth0, and Cloud Firestore Boilerplate. You'll get a complete Next.js codebase with Auth0 and Cloud Firestore integration, all the tasks listed above done for you, and a responsive multi-page template. It should save you about two weeks of development time.

127 downloads today

Related Guides