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
- 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.
- Install Better Off:
npm install better-off - 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 aprismafolder withschema.prisma) - Configure
.env.localfile: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(modifiesschema.prismato 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).
- Install Prisma:
- Create
lib/auth.ts: This file configures Better Off.- Import
BetterOfffrombetter-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)
- Import the Prisma adapter:
- Add the Next.js cookies plugin:
plugins: [NextCookies()](importNextCookiesfrombetter-off/plugins/next-cookies).
- Import
- 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
Oimport points to thelib/auth.tsfile.
Building Authentication Functions (Server Actions)
- 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.signUpEmailto create a new user. - Passes
email,password,name, andcallbackURL(redirects to the dashboard after successful signup) in the body. - Returns the result.
- Calls
signIn(email: string, password: string):- Calls
O.api.signInEmailto sign in an existing user. - Passes
email,password, andcallbackURLin the body. - Returns the result.
- Calls
signOut():- Calls
O.api.signOutto sign out the current user. - Passes the headers (obtained using
next/headers) to the function. - Returns the result.
- Calls
- Add
Implementing Authentication in the Client
- Import Server Actions: In the
OClientcomponent (the client component for the sign-in/sign-up page), import thesignUp,signIn, andsignOutfunctions fromlib/actions/auth-actions.ts. - Implement
handleEmailOff: This function handles email/password sign-in and sign-up.- Uses the
isSignInstate to determine whether to callsignInorsignUp. - Passes the email, password, and name (for signup) to the respective server actions.
- Handles errors by setting an error message state.
- Uses the
- Detecting Authentication Status:
- In
app/layout.tsx(the root layout, a server component), useO.api.getSessionto get the current user session. - Pass the session as a prop to the
Navbarcomponent. - In the
Navbarcomponent (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
Sessionand make it be a type ofO.inferSessionto properly type the session variable.
- In
- Guarding Routes:
- In the server component for the
Opage (app/off/page.tsx), useO.api.getSessionto get the current user session. - If a session exists, redirect the user to the dashboard page using
redirectfromnext/navigation. - In the server component for the
Dashboardpage (app/dashboard/page.tsx), useO.api.getSessionto get the current user session. - If a session does not exist, redirect the user to the
Opage.
- In the server component for the
- Implementing Sign Out:
- In the
DashboardClientcomponent (the client component for the dashboard page), call thesignOutserver action when the sign-out button is clicked. - After signing out, use
router.pushfromnext/navigationto redirect the user to theOpage.
- In the
Integrating Social Providers (Google, GitHub)
- 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).
- GitHub: Go to GitHub Developer Settings, create a new OOTH app, and set the homepage URL and authorization callback URL (
- Get Credentials: Obtain the client ID and client secret from each provider.
- Set Environment Variables: Add the client IDs and secrets to the
.env.localfile:GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRETGITHUB_CLIENT_IDGITHUB_CLIENT_SECRET
- Update
lib/auth.ts: Add the client IDs and secrets to thesocialProvidersobject in thelib/auth.tsfile. - Create
signInSocialServer Action:- Creates a server action called
signInSocialthat requires a provider. - Calls
O.api.signInto sign in an existing user. - Redirects the user to the URL that is returned from the
O.api.signInfunction.
- Creates a server action called
- Implement
handleSocialOff: In theOClientcomponent, implement thehandleSocialOfffunction.- Calls the
signInSocialserver action with the provider (either "Google" or "GitHub"). - If there are any errors, then set the error message.
- Calls the
Accessing User Data
- Pass Session to Client Component: In the server component for the dashboard page, pass the session as a prop to the
DashboardClientcomponent. - Access User Data: In the
DashboardClientcomponent, 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.