NextJS Authentication Full Course 2025 | Learn Better Auth in 1 Hour

PedroTechAbout 6 min readSep 11, 2025Watch original
THE SUMMARYAI-generated

Key Concepts

  • Authentication (O): Proving user identity and permissions. Includes sign-up, sign-in, session management, route guarding, and authorization.
  • O Libraries: Pre-built solutions for handling authentication, avoiding the need to "roll your own."
  • Clerk: A hosted O platform with UI components for fast O integration (paid).
  • Better Off: A framework-agnostic, open-source O alternative, giving control over data and UI.
  • BaaS (Backend as a Service): Platforms like Superbase, Firebase, or Appwrite, whose built-in authentication can be used.
  • ORM (Object-Relational Mapper): A library that facilitates communication between a programming language and a database (e.g., Prisma, Drizzle).
  • Server Actions (Next.js): Functions that run on the server, used here for secure authentication operations.
  • Social Providers: Third-party services (e.g., Google, GitHub) used for authentication.
  • Session: A record of a user's login, stored server-side and often accessed via cookies.

Setting Up Authentication in Next.js with Better Off

Introduction

The video provides a crash course on setting up authentication in Next.js using Better Off, an open-source O library. It also discusses different O options and when to choose each. The video emphasizes using server actions for secure authentication.

Choosing an Authentication Method

  • Clerk: Fastest way to ship production-ready O, with beautiful UI components. It's a hosted service, so there's a cost associated with it. Ideal for projects needing rapid deployment or where paying for a managed service is acceptable.
  • Better Off: A framework-agnostic, open-source alternative. It requires setting up your own database and UI, but offers more control. It's becoming a leading open-source option.
  • BaaS (Superbase, Firebase, Appwrite): If already using a BaaS, leverage its built-in authentication for seamless integration.

Initial Setup

  1. Clone the Starter Code: Download the starter repo from the description. It includes a basic website structure with a homepage, dashboard (protected route), and sign-in/sign-up page.
  2. Install Better Off: npm install better-off
  3. Database Setup: Better Off requires a database to store user data. The video uses a Postgress SQL database with Prisma as the ORM.
    • Install Prisma: npm install prisma
    • Initialize Prisma: npx prisma init (creates a prisma folder with schema.prisma)
    • Configure .env.local file:
      • BETTER_OFF_URL: URL of the app (e.g., http://localhost:3000).
      • BETTER_OFF_SECRET: A randomly generated secret key (generated from Better Off docs).
      • DATABASE_URL: Connection string to the Postgress SQL database.
    • Generate Better Off Schema: npx better-off cli/generate (modifies schema.prisma to include Better Off's required models: User, Session, Account, Verification).
    • Migrate the Schema: npx prisma migrate dev --name init (creates the tables in the database).
  4. Create lib/auth.ts: This file configures Better Off.
    • Import BetterOff from better-off.
    • Enable email/password authentication: emailPassword: { enable: true }.
    • Configure social providers (Google, GitHub):
      • socialProviders: { GitHub: { clientId: "", clientSecret: "" }, Google: { clientId: "", clientSecret: "" } } (Client IDs and secrets will be added later).
    • Specify the database adapter:
      • Import the Prisma adapter: import { PrismaAdapter } from "better-off/adapters/prisma"
      • Pass the Prisma client instance to the adapter: database: PrismaAdapter(prismaClient)
    • Add the Next.js cookies plugin: plugins: [NextCookies()] (import NextCookies from better-off/plugins/next-cookies).
  5. Create app/api/auth/[...all]/route.ts: This file handles the API routes for authentication.
    • Paste the code directly from the Better Off documentation.
    • Ensure the O import points to the lib/auth.ts file.

Building Authentication Functions (Server Actions)

  1. Create lib/actions/auth-actions.ts: This file contains the server actions for authentication.
    • Add "use server" at the top to mark it as a server action file.
    • signUp(email: string, password: string, name: string):
      • Calls O.api.signUpEmail to create a new user.
      • Passes email, password, name, and callbackURL (redirects to the dashboard after successful signup) in the body.
      • Returns the result.
    • signIn(email: string, password: string):
      • Calls O.api.signInEmail to sign in an existing user.
      • Passes email, password, and callbackURL in the body.
      • Returns the result.
    • signOut():
      • Calls O.api.signOut to sign out the current user.
      • Passes the headers (obtained using next/headers) to the function.
      • Returns the result.

Implementing Authentication in the Client

  1. Import Server Actions: In the OClient component (the client component for the sign-in/sign-up page), import the signUp, signIn, and signOut functions from lib/actions/auth-actions.ts.
  2. Implement handleEmailOff: This function handles email/password sign-in and sign-up.
    • Uses the isSignIn state to determine whether to call signIn or signUp.
    • Passes the email, password, and name (for signup) to the respective server actions.
    • Handles errors by setting an error message state.
  3. Detecting Authentication Status:
    • In app/layout.tsx (the root layout, a server component), use O.api.getSession to get the current user session.
    • Pass the session as a prop to the Navbar component.
    • In the Navbar component (a client component), destructure the session prop and use it to conditionally render links (e.g., show "Dashboard" link only if the user is logged in).
    • Define a type called Session and make it be a type of O.inferSession to properly type the session variable.
  4. Guarding Routes:
    • In the server component for the O page (app/off/page.tsx), use O.api.getSession to get the current user session.
    • If a session exists, redirect the user to the dashboard page using redirect from next/navigation.
    • In the server component for the Dashboard page (app/dashboard/page.tsx), use O.api.getSession to get the current user session.
    • If a session does not exist, redirect the user to the O page.
  5. Implementing Sign Out:
    • In the DashboardClient component (the client component for the dashboard page), call the signOut server action when the sign-out button is clicked.
    • After signing out, use router.push from next/navigation to redirect the user to the O page.

Integrating Social Providers (Google, GitHub)

  1. Create OOTH Apps:
    • GitHub: Go to GitHub Developer Settings, create a new OOTH app, and set the homepage URL and authorization callback URL (http://localhost:3000/api/callback/github).
    • Google: Go to Google Cloud Platform, create a project (if needed), go to Credentials, create an OOTH client ID, and set the authorized redirect URI (http://localhost:3000/api/callback/google).
  2. Get Credentials: Obtain the client ID and client secret from each provider.
  3. Set Environment Variables: Add the client IDs and secrets to the .env.local file:
    • GOOGLE_CLIENT_ID
    • GOOGLE_CLIENT_SECRET
    • GITHUB_CLIENT_ID
    • GITHUB_CLIENT_SECRET
  4. Update lib/auth.ts: Add the client IDs and secrets to the socialProviders object in the lib/auth.ts file.
  5. Create signInSocial Server Action:
    • Creates a server action called signInSocial that requires a provider.
    • Calls O.api.signIn to sign in an existing user.
    • Redirects the user to the URL that is returned from the O.api.signIn function.
  6. Implement handleSocialOff: In the OClient component, implement the handleSocialOff function.
    • Calls the signInSocial server action with the provider (either "Google" or "GitHub").
    • If there are any errors, then set the error message.

Accessing User Data

  1. Pass Session to Client Component: In the server component for the dashboard page, pass the session as a prop to the DashboardClient component.
  2. Access User Data: In the DashboardClient component, access the user data from the session object (e.g., session.user.name, session.user.email).

Conclusion

The video provides a comprehensive guide to setting up authentication in Next.js using Better Off. It covers the initial setup, building authentication functions, implementing authentication in the client, integrating social providers, and accessing user data. The video emphasizes using server actions for secure authentication and provides a clear explanation of the different O options available.

Notable Quotes

  • "Authentication in Nex.js is how we prove who a user is and what they're allowed to do."
  • "It is actually advised that you don't roll out your own o. It is advised that you use an o library."
  • "Better Off is a framework agnostic open-source alternative that makes it super easy for us to integrated into our projects."
  • "Choosing your authentication depends on whether or not you what kind of purpose you're you're going for this."

AI summaries can miss context or contain errors. Check important details against the original video.

Go a little deeper.

Have a question about this video? Load its transcript to open the video chat.