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.
PROJECT 5 · LESSON 13 OF 18
Connect an authentication library to the existing learning database.
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.
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.
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.
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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
A browser calls an /api/auth/* endpoint through the client helper.
The catch-all handler delegates to the configured auth instance.
The provider verifies credentials or sessions using the auth database.
Application server code reads the current request’s session before using its user identity.
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.
This is the project’s dependency and command manifest. It tells npm what to install and how to run the learner application.
{
"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"
}
}
This configures the server authentication provider and its persistent storage adapter.
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 },
});
This creates the browser-facing auth helper used by sign-in and sign-out controls.
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient();
This mounts the auth provider’s HTTP interface inside the App Router.
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);
This provides one server-side way to require the current request’s authenticated user.
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;
}
This is a list of configuration names and placeholder values to copy into .env.local.
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
Call requireUser from the Account page in the next lesson, but leave a public About page without it.
Account requires sign-in, while About remains public.
Protection follows the code paths where you enforce it. Installing an auth library does not automatically make all routes private.
Do not prefix database credentials or auth secrets with NEXT_PUBLIC_. These values belong only on the server.
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.
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.
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.
No. It is application configuration used by the authentication system. Individual users supply their own passwords through the account flow.
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.