Skip to lesson content

PROJECT 5 · LESSON 13 OF 18

Configure authentication for the task app

Connect an authentication library to the existing learning database.

  • authentication
  • sessions
  • Route Handlers
  • server secrets

Your workspace: task-app

Continue from lesson 12: Complete task CRUD. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

The shared task app cannot distinguish one person’s work from another’s. Before making tasks private, we need a trustworthy way for the server to identify the current caller. Authentication establishes that identity; ownership rules follow later.

Continue in the task-app folder. Better Auth handles password hashing and session cookies; do not implement either from scratch. The pinned dependency is already included in the checkpoint package.json.

Use a separate learning secret. Generate at least 32 random bytes with the command below and put the output only in .env.local. BETTER_AUTH_URL must match the origin actually used by the browser.

This lesson wires the provider. The following lesson adds the UI, and lesson 15 enforces ownership. Keep the app local until that protection is complete.

Separate identity, session and permission

Authentication verifies credentials and identifies a user. A session lets later requests refer to that authenticated identity without resending the password every time. Authorization then asks whether that identity may access a particular record or operation. These are related steps, not interchangeable words.

Better Auth manages the password and session mechanisms in this lab. The application configures the library and asks it for the current session. We do not store raw passwords, invent our own cookie format, or accept a user ID from a query string as evidence of identity.

Connect the server instance, handler and client

lib/auth.ts creates the server-side auth instance with the MongoDB adapter. The adapter stores auth data in the selected learning database using its own collections. The tasks collection remains our application data. The database client is reused rather than constructing another connection path.

app/api/auth/[...all]/route.ts exposes the library’s GET and POST handlers under /api/auth/*. The catch-all segment captures the provider’s multiple auth paths. A Route Handler produces HTTP responses; it is not a page component and does not return JSX.

lib/auth-client.ts creates the browser-facing helper. It calls the auth endpoints on the same origin. Import this helper into interactive forms, not the server auth module containing database configuration. The similarly named files serve different execution environments.

Configure secrets and read sessions correctly

BETTER_AUTH_SECRET is a high-entropy server secret used by the authentication system. It is not a test user’s password. BETTER_AUTH_URL identifies the application origin. If the app runs on a different port or host, update that value and restart the server rather than mixing localhost and another origin.

requireUser awaits the incoming request headers and passes them to auth.api.getSession. That gives the provider the cookie context it needs to identify this request. Without a valid session, redirect sends the user to sign-in. With a valid session, the helper returns the provider’s user object.

Creating requireUser does not protect anything by itself. Each sensitive read or mutation must call it and enforce any additional ownership rule. Lesson 14 uses it on Account; lesson 15 applies it to the actual task operations.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. A browser calls an /api/auth/* endpoint through the client helper.

  2. The catch-all handler delegates to the configured auth instance.

  3. The provider verifies credentials or sessions using the auth database.

  4. Application server code reads the current request’s session before using its user identity.

Trace requireUser while signed out

  1. A signed-out request reaches a page that calls requireUser.
  2. headers supplies that request’s header context, but there is no valid session cookie.
  3. getSession returns no authenticated session, so redirect interrupts the page.
  4. The browser reaches /sign-in. The protected page’s normal return statement is not reached.

3. Build it, one file at a time

  1. Replace package.json, run npm install, then add the server and client modules and the catch-all auth route below.
  2. Add BETTER_AUTH_URL=http://localhost:3000 and your generated BETTER_AUTH_SECRET to .env.local. Restart the server.
  3. Open /api/auth/get-session while signed out; expect an empty session response. MongoDB collections are created by the adapter as needed.
Terminal
npm install
node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

package.json

This is the project’s dependency and command manifest. It tells npm what to install and how to run the learner application.

package.json
{
  "name": "edupoly-nextjs-lab",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "typecheck": "tsc --noEmit"
  },
  "dependencies": {
    "next": "16.3.0",
    "react": "19.2.8",
    "react-dom": "19.2.8",
    "mongodb": "7.5.0",
    "better-auth": "1.6.26",
    "server-only": "0.0.1"
  },
  "devDependencies": {
    "typescript": "^5",
    "@types/node": "^20",
    "@types/react": "^19",
    "@types/react-dom": "^19"
  }
}

Read the code

  1. dependencies lists packages needed by the application; devDependencies lists development tools and TypeScript definitions. Install from the folder containing this file.
  2. scripts.dev runs the development server; scripts.build prepares production output; scripts.start serves that output. typecheck checks TypeScript without emitting JavaScript.
  3. When a later lesson replaces this file to add database or auth packages, run npm install again. Keep your generated package-lock.json so subsequent installs use a consistent resolution.

lib/auth.ts

This configures the server authentication provider and its persistent storage adapter.

lib/auth.ts
import "server-only";
import { betterAuth } from "better-auth";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { client, db } from "./db";
export const auth = betterAuth({
  baseURL: process.env.BETTER_AUTH_URL,
  secret: process.env.BETTER_AUTH_SECRET,
  database: mongodbAdapter(db, { client }),
  emailAndPassword: { enabled: true },
});

Read the code

  1. mongodbAdapter reuses the learning database and client. Auth data is stored in provider collections rather than mixed into task documents.
  2. emailAndPassword enables the account method used by the forms. The provider handles password verification and sessions.
  3. The base URL and secret come from server environment variables. Never import this runtime module into an interactive credential form.

lib/auth-client.ts

This creates the browser-facing auth helper used by sign-in and sign-out controls.

lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient();

Read the code

  1. createAuthClient from better-auth/react exposes methods that communicate with the configured provider endpoints.
  2. With the default same-origin setup, the browser uses this application’s auth route. No database URI or server secret is passed to this helper.

app/api/auth/[...all]/route.ts

This mounts the auth provider’s HTTP interface inside the App Router.

app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);

Read the code

  1. The catch-all folder captures multiple /api/auth/... paths handled by the provider. It does not create a rendered page.
  2. toNextJsHandler adapts the configured auth instance, and the named GET and POST exports tell Next.js which request methods it handles.

lib/session.ts

This provides one server-side way to require the current request’s authenticated user.

lib/session.ts
import "server-only";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "./auth";
export async function requireUser() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) redirect("/sign-in");
  return session.user;
}

Read the code

  1. await headers() reads the incoming request context and getSession asks the provider to verify it.
  2. If there is no session, redirect interrupts the current operation and points to /sign-in. Code after that branch assumes an authenticated user.
  3. Returning session.user gives callers a trusted identity source. The caller must still enforce ownership or administrator permissions as appropriate.

.env.example

This is a list of configuration names and placeholder values to copy into .env.local.

.env.example
MONGODB_URI=mongodb://127.0.0.1:27017
MONGODB_DB=edupoly_tasks_lab
BETTER_AUTH_URL=http://localhost:3000
BETTER_AUTH_SECRET=replace-with-your-random-secret

Read the code

  1. MONGODB_URI supplies the database connection and MONGODB_DB selects the learning database. The application and standalone scripts must agree on both.
  2. Where present, BETTER_AUTH_URL is the browser origin and BETTER_AUTH_SECRET must be replaced with a high-entropy secret. Neither value is a user account password.
  3. Do not rename secrets with a NEXT_PUBLIC_ prefix. Keep the completed .env.local private and restart the server after changing it.

4. Run it and check your result

  • The auth endpoint responds without a missing-route error.
  • The secret is absent from source files and browser code.

5. Predict, change and observe

Call requireUser from the Account page in the next lesson, but leave a public About page without it.

Compare your prediction with the expected result

What you should observe

Account requires sign-in, while About remains public.

Why it happens

Protection follows the code paths where you enforce it. Installing an auth library does not automatically make all routes private.

6. Troubleshoot with evidence

A common mistake

Do not prefix database credentials or auth secrets with NEXT_PUBLIC_. These values belong only on the server.

Auth endpoints return a route not found response.

Likely cause: The handler is missing or placed under the wrong route path.

Check and correct: Use app/api/auth/[...all]/route.ts and export both handlers returned by toNextJsHandler.

Signing in fails after changing the local port.

Likely cause: The configured auth origin and the browser’s origin differ.

Check and correct: Set BETTER_AUTH_URL to the actual origin and restart. Keep the server secret in .env.local.

7. Practice and explain it back

Your independent task

Explain the difference between identifying a user and allowing that user to edit a task.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Is the auth secret the same as a password?

No. It is application configuration used by the authentication system. Individual users supply their own passwords through the account flow.

Why pass request headers to getSession?

The session belongs to the current request, usually represented through cookies in its headers. A user object cannot be chosen safely from arbitrary form input.