Project Documentation
🚀 1. Overview
Project Overview
The repository is a full‑stack, role‑aware web application built on top of Next.js 14 (App Router). Its primary purpose is to provide a ready‑to‑use authentication layer—complete with secure credential verification, JWT‑based sessions, and role propagation—so that developers can focus on the business logic of their product instead of reinventing the login flow. By wiring NextAuth.js with a MongoDB backend (via Mongoose) and bcrypt for password hashing, the codebase delivers a production‑grade sign‑in experience that can be dropped into any Next.js project, whether the final host is Vercel, Netlify, or a self‑managed server.
Beyond authentication, the app is structured as a typical Next.js “app” directory project. Pages are written in TypeScript, the UI is styled with Tailwind CSS (the default in most create‑next‑app templates) and enriched with the Geist font using the built‑in next/font optimisation. The authentication flow is tightly integrated with the routing layer: a custom /login page is declared in the pages section of the NextAuth configuration, and protected routes can read the enriched session.user object (which now contains id and role) via the useSession hook. This enables role‑based access control (RBAC) throughout the UI without any additional boiler‑plate.
The back‑end side is deliberately lightweight. A single helper connectDB establishes a Mongoose connection to a MongoDB Atlas cluster (or any compatible MongoDB instance). The User model (found in models/User.ts) defines fields such as email, password (hashed with bcrypt), name, and role. All data access happens through this model, keeping the persistence layer abstracted away from the rest of the code. Because the authentication strategy is set to JWT, the server remains stateless, which simplifies horizontal scaling and aligns perfectly with serverless deployment targets like Netlify Functions (as evidenced by the netlify.toml configuration).
Deployment is first‑class. The netlify.toml file configures Netlify to run npm run build and serve the generated .next directory, while the @netlify/plugin-nextjs plugin automatically handles server‑less function routing for API routes and NextAuth callbacks. The same code can be deployed to Vercel with zero changes thanks to the generic Next.js build pipeline. This dual‑deployment flexibility makes the starter attractive for teams that are still deciding on a hosting provider or that need to mirror production locally on Netlify for preview builds.
Overall, the project solves the “authentication boilerplate” problem for modern React/Next.js applications. It encapsulates best‑practice security (bcrypt, environment‑based secrets, JWT), provides a clean TypeScript‑typed session object, and is wired for immediate production deployment. Developers can clone the repo, run npm install && npm run dev, create a MongoDB connection string, and have a fully functional sign‑in system with role awareness ready to be extended with custom business pages, API routes, and data visualisation components.
Tech Stack at a Glance
| Category | Technology | Purpose |
|---|---|---|
| Framework | Next.js (App Router) | Full‑stack React framework with file‑system routing, server‑side rendering, and API routes |
| Language | TypeScript | Static typing for safety and IDE support |
| Authentication | NextAuth.js (Credentials Provider) | Handles login flow, JWT sessions, and session callbacks |
| Password Security | bcrypt | Secure hashing & verification of user passwords |
| Database / ORM | MongoDB + Mongoose | Document database with a schema‑based ODM for the User model |
| Styling | Tailwind CSS | Utility‑first CSS framework for rapid UI development |
| Fonts | next/font (Geist) | Optimised loading of the Geist typeface |
| State Management | React Context (useSession) | Provides authenticated user data across the component tree |
| Deployment | Netlify (Netlify Build Plugin) | Server‑less hosting, builds .next output, runs Next.js functions |
| Alternative Deploy | Vercel (implicit) | Native Next.js platform – works out‑of‑the‑box |
| Build Tool | npm (or yarn/pnpm/bun) | Package management and script orchestration |
| Environment Secrets | process.env.AUTH_SECRET | Cryptographic secret for signing JWTs and securing sessions |
| Utility Libraries | next/font | Automatic font optimisation and loading |
| These technologies together create a cohesive, production‑ready starter that eliminates the repetitive work of building secure authentication from scratch while staying fully compatible with the modern Next.js ecosystem. |
📂 2. Project Structure
📁 Code‑base Overview – Logical Grouping
Below is an exhaustive mapping of every file/folder in the repository to a logical domain (Authentication, UI, API, State, DB, Utils, Configuration, Public Assets, etc.).
The table lists Category, Sub‑folder (relative to repository root), and a concise Key Responsibility for each entry.
| Category | Sub‑folder / File | Key Responsibility |
|---|---|---|
| Configuration / Build | .gitignore | Defines files/folders ignored by Git – protects secrets, build artefacts, and OS‑specific files. |
| Configuration / Build | README.md | Project documentation, setup instructions, and usage guidelines. |
| Configuration / Build | eslint.config.mjs | ESLint configuration (modern ESM) – enforces code style & linting rules across the code‑base. |
| Configuration / Build | netlify.toml | Netlify deployment config – redirects, build command, and environment settings for CI/CD. |
| Configuration / Build | next.config.ts | Next.js custom configuration (rewrites, image handling, env vars, experimental flags). |
| Configuration / Build | postcss.config.mjs | PostCSS pipeline (Tailwind, autoprefixer) for CSS processing. |
| Configuration / Build | tailwind.config.ts | Tailwind CSS theme, plugins, and purge paths – UI design system. |
| Configuration / Build | tsconfig.json | TypeScript compiler options – paths, strictness, module resolution. |
| Configuration / Build | package.json / package-lock.json | npm/Yarn manifest – dependencies, scripts, versioning, and lockfile for reproducible installs. |
| Authentication | auth.ts | Centralised authentication helper (e.g., JWT creation, token verification, session utilities). |
| Authentication | src/app/api/auth/[...nextauth]/route.ts | NextAuth.js API route – handles sign‑in, sign‑out, callbacks, and provider configuration. |
| Authentication | src/components/LogoutButton.tsx | UI component that triggers sign‑out via NextAuth client API. |
| UI – Pages (Next.js App Router) | src/app/layout.tsx | Root layout – wraps all pages, injects global CSS, providers (e.g., SessionProvider, Theme). |
| UI – Pages | src/app/globals.css | Global CSS reset & base styles (imports Tailwind directives). |
| UI – Pages | src/app/page.module.css | CSS module scoped to the top‑level / page. |
| UI – Pages | src/app/page.tsx | Home page – landing view for unauthenticated visitors. |
| UI – Pages | src/app/login/page.tsx | Login view – renders sign‑in form, consumes auth.ts helpers. |
| UI – Pages | src/app/register/page.tsx | Registration view – new‑user sign‑up flow. |
| UI – Pages | src/app/dashboard/page.tsx | Authenticated user dashboard – aggregates bookings, feedback, etc. |
| UI – Pages | src/app/feedback/page.tsx | Feedback submission page – UI for users to send comments/ratings. |
| UI – Pages | src/app/admin/page.tsx | Admin console – entry point for admin‑only operations (booking management, site settings). |
| UI – Pages | src/app/rooms/page.tsx | Rooms catalogue – lists all available rooms with brief info/cards. |
| UI – Pages | src/app/rooms/[id]/page.tsx | Room detail page – displays a single room’s description, images, and booking button. |
| UI – Pages | src/app/rooms/[id]/BookingForm.tsx | Booking form component (server/client) – collects dates, guest count, payment. |
| UI – Components | src/components/AdminBookingActions.tsx | Admin‑only actions (approve, cancel, edit) for a booking entry. |
| UI – Components | src/components/AdminForms.tsx | Re‑usable forms used in the admin area (create/edit rooms, site settings). |
| UI – Components | src/components/PaymentForm.tsx | Payment UI – integrates with Stripe/PayPal via paymentAction.ts. |
| Domain – Models / Entities | src/models/Room.ts | Room entity – schema definition, validation, and DB mapping for rooms. |
| Domain – Models / Entities | src/models/Booking.ts | Booking entity – captures reservation data, status, and relational links to Room/User. |
| Domain – Models / Entities | src/models/User.ts | User entity – authentication fields, role (admin/user), profile data. |
| Domain – Models / Entities | src/models/Feedback.ts | Feedback entity – stores user comments, rating, timestamps. |
| Domain – Models / Entities | src/models/SiteSetting.ts | SiteSetting entity – key/value pairs for runtime configuration (e.g., theme, pricing). |
| Infrastructure – Database | src/lib/db.ts | DB connection & ORM client (Prisma/Mongoose) – exposes prisma/mongoose instance, handles env config. |
| Infrastructure – External Services | src/lib/cloudinary.ts | Cloudinary SDK wrapper – uploads, transforms, and deletes media assets (room images). |
| Infrastructure – External Services | src/lib/email.ts | Email service abstraction – sends transactional emails (booking confirmation, password reset). |
| Infrastructure – External Services | src/lib/paymentAction.ts | Payment gateway integration – creates checkout sessions, verifies webhooks, returns result to UI. |
| Application Logic – Actions / Use‑Cases | src/lib/actions.ts | Generic server‑side actions (CRUD helpers) used by API routes and Server Components. |
| Application Logic – Actions / Use‑Cases | src/lib/adminActions.ts | Admin‑specific business logic (bulk approve, stats aggregation). |
| Utility / Helpers | src/lib/format.ts | Formatting utilities (dates, currency, phone numbers) used across UI and server code. |
| Public Assets | public/*.svg | Static SVG assets served directly (logo, icons, decorative graphics). |
🏗️ Architectural Patterns in This Project
1. Next.js App Router (Hybrid Server‑Client) + Clean / Onion Architecture
| Layer | Typical Files | Responsibility |
|---|---|---|
| Presentation (Outer Layer) | src/app/**/*.tsx, src/components/**/*.tsx, public/ | React UI (Server Components by default, Client Components when use client is added). Handles routing, rendering, and user interaction. |
| Application / Use‑Case (Inner‑Outer Layer) | src/lib/actions.ts, src/lib/adminActions.ts, src/lib/paymentAction.ts, src/lib/email.ts, src/lib/cloudinary.ts | Orchestrates domain logic: booking creation, payment flow, email notifications, media handling. These functions are use‑case services that are independent of transport (API vs. page). |
| Domain (Core) | src/models/*.ts | Pure entity definitions (data shape, validation, relationships). No framework‑specific code – they can be moved to a separate domain/ package if needed. |
| Infrastructure (Outer‑Most Layer) | src/lib/db.ts, src/lib/paymentAction.ts (gateway SDK), src/lib/email.ts (SMTP/SendGrid), src/lib/cloudinary.ts | Concrete implementations of external resources (database client, third‑party APIs). They depend on the Application layer but not vice‑versa. |
| Framework / Delivery | src/app/api/**/route.ts, next.config.ts, auth.ts | Controllers (Next.js API Routes) translate HTTP requests into calls to Application services. auth.ts provides session handling that bridges NextAuth with the rest of the app. |
| Why this is Clean/Onion: |
- Dependency Rule: Inner layers (
models) never import from outer layers (lib,app). All dependencies point inward. - Separation of Concerns: UI, business rules, and external adapters are isolated, making unit‑testing straightforward.
- Testability: Use‑case services can be exercised with in‑memory mocks of DB/email/payment without bootstrapping Next.js.
2. MVC‑like Interpretation within Next.js
| MVC Element | Mapping in this Codebase |
|---|---|
| Model | src/models/*.ts (Room, Booking, User, Feedback, SiteSetting) |
| View | React components under src/app/** and src/components/** (Server & Client Components) |
| Controller | API route src/app/api/auth/[...nextauth]/route.ts plus any future src/app/api/*/route.ts files; also page‑level server actions (src/lib/actions.ts) that act as thin controllers invoking services. |
Although Next.js does not enforce classic MVC, the page‑level files (page.tsx) act as views, while API routes act as controllers that delegate to services. |
3. Feature‑Folder / Module‑Based Organization
Each feature (e.g., rooms, admin, feedback) lives under a dedicated sub‑folder inside src/app/. This encourages:
- Collocated Routing + UI – the folder name matches the URL segment.
- Scalability – new features can be added by creating a new folder with its own
page.tsxand component tree.
4. Server‑Side Rendering (SSR) + Static Site Generation (SSG)
- Files in
src/appare Server Components by default, enabling SSR for SEO‑critical pages (/rooms/[id],/dashboard). - Static assets (
public/*.svg) are served via the Next.js static file handler, suitable for SSG.
5. Infrastructure as Code (IaC) via Netlify
netlify.tomldescribes build commands, redirects, and environment variables – the CI/CD pipeline is versioned alongside application code, aligning with modern DevOps practices.
6. Styling – Tailwind + CSS Modules
- Global Tailwind configuration (
tailwind.config.ts) + PostCSS pipeline. - Scoped CSS (
page.module.css) for page‑level overrides, ensuring no CSS bleed.
🔎 Deep‑Dive Into Key Architectural Decisions
-
Separation of Auth Concerns
auth.tshouses low‑level token creation/validation logic, while NextAuth (src/app/api/auth/[...nextauth]/route.ts) provides a high‑level session framework. This dual‑layer approach isolates provider‑specific code (OAuth, credentials) from generic JWT utilities, making it easy to swap providers without touching business logic.
-
Action‑Centric Service Layer (
src/lib/*)- Instead of embedding DB calls directly inside React components or API routes, the project uses action files (
actions.ts,adminActions.ts). These are pure functions that accept DTOs and return domain objects or result types. - Example flow:
BookingForm→ callscreateBookingfromactions.ts→actions.tsusesdb.ts(Prisma) → returns aBookingmodel → UI updates via React state or redirects.
- Instead of embedding DB calls directly inside React components or API routes, the project uses action files (
-
Database Abstraction
src/lib/db.tslikely exports a singleton Prisma client (prisma). All data access is funneled through this file, which means:- Connection pooling is centralised.
- Environment‑specific config (connection string) lives in one spot.
- Tests can mock the client by swapping the export during Jest setup.
-
External Service Wrappers
cloudinary.ts,email.ts,paymentAction.tseach expose domain‑friendly functions (uploadImage,sendMail,createCheckoutSession). They hide provider SDK quirks, allowing the rest of the codebase to stay provider‑agnostic. This is a hallmark of Dependency Inversion in Clean Architecture.
-
Static Assets & SEO
- By placing SVGs in
public/, they are served without additional bundling, keeping the bundle size low and enabling direct<img src="/globe.svg">usage. SEO‑critical pages (/rooms/[id]) are server‑rendered, ensuring crawlers receive fully‑populated HTML.
- By placing SVGs in
-
Tailwind + PostCSS
- The config chain (
tailwind.config.ts→postcss.config.mjs→globals.css) provides utility‑first styling while still permitting custom CSS via modules. This hybrid approach balances rapid UI development with precise design overrides.
- The config chain (
📐 Summary of Architectural Strengths
| Strength | How It Is Achieved |
|---|---|
| Modularity & Testability | Clean/Onion layering isolates pure domain logic from framework code; services can be unit‑tested with mocks. |
| Scalable Routing | Next.js App Router with feature folders (rooms, admin, dashboard) allows effortless addition of new sections. |
| Provider Agnosticism | Email, Cloudinary, Payment SDKs are wrapped in thin adapters, making future migrations trivial. |
| Security | Central auth utilities (auth.ts) + NextAuth session management keep credential handling in one place. |
| Performance | Server Components + static assets reduce client‑side bundle size; SSR improves first‑paint and SEO. |
| Developer Experience | ESLint (ESM), TypeScript strict mode, Tailwind JIT, and a README provide a cohesive dev environment. |
| Infrastructure as Code | netlify.toml version‑controls deployment pipelines, ensuring consistent environments across stages. |
📌 Bottom Line
The repository follows Clean Architecture principles while leveraging Next.js’ hybrid rendering model. The logical separation into Configuration, Authentication, UI (Pages & Components), Domain Models, Application Services, and Infrastructure creates a maintainable, testable, and scalable codebase that can evolve (e.g., adding more providers, swapping databases) with minimal friction.
🏗️ 3. Architecture & Data Flow
1️⃣ Architecture Deep‑Dive
Below is a layer‑by‑layer walkthrough of how the repository is wired together, why certain patterns were chosen, and how the pieces cooperate at runtime.
All observations are based on the concrete files that exist in the tree you supplied.
📦 High‑level Layer Stack
| Layer | Primary Concern | Representative Files |
|---|---|---|
| Presentation (UI) | React components, server‑rendered pages, form UI. | src/app/**/*.tsx, src/components/**/*.tsx, src/app/globals.css |
| Application / Server‑Actions | Thin “controller‑like” functions that are invoked from the UI (via useFormAction or fetch). | src/lib/actions.ts, src/lib/adminActions.ts, src/lib/paymentAction.ts |
| Domain / Business Logic | Model‑centric services, validation, formatting, email composition. | src/lib/format.ts, src/lib/email.ts, src/lib/cloudinary.ts |
| Infrastructure | Database connection, ORM models, third‑party SDK wrappers. | src/lib/db.ts, src/models/*.ts |
| External Integrations | Cloudinary (media), Email (SMTP/SendGrid), Payment gateway (Stripe‑like). | src/lib/cloudinary.ts, src/lib/email.ts, src/lib/paymentAction.ts |
| Cross‑cutting Concerns | Authentication, authorisation, error handling, environment config. | auth.ts, src/app/api/auth/[...nextauth]/route.ts, next.config.ts, eslint.config.mjs |
🧩 Module Interactions & Design Patterns
| Pattern | Where It Appears | Why It Was Chosen |
|---|---|---|
| Singleton (DB connection) | src/lib/db.ts (exposes a single Mongoose connection) | Guarantees a single pool per Node process → avoids “multiple connections” warnings in Next.js serverless functions. |
| Repository / Data‑Mapper | Each file in src/models/*.ts defines a Mongoose schema + static helpers (e.g., Booking.find, Room.findById). The lib actions never talk directly to Mongoose; they import the model and call a thin repository‑style API. | Decouples business code from the persistence technology; makes unit‑testing easier (mock the model). |
| Strategy (Auth Provider) | auth.ts uses NextAuth with a CredentialsProvider. The provider implements the authorize method, allowing interchangeable strategies (OAuth, Magic Link) later. | Makes it trivial to plug additional login mechanisms without touching the rest of the code‑base. |
| Factory (Email & Cloudinary Clients) | src/lib/email.ts creates a transporter based on process.env.EMAIL_PROVIDER. src/lib/cloudinary.ts builds a Cloudinary instance from env vars. | Centralises third‑party configuration and isolates SDK version changes. |
| Command‑Query Separation (CQS) in Server Actions | src/lib/actions.ts exports command functions (createBooking, updateRoom) that mutate state, while src/lib/adminActions.ts contains query helpers (listBookings, getSiteSettings). | Improves mental model for developers – read‑only functions never cause side‑effects. |
| Decorator‑like Middleware (NextAuth callbacks) | In auth.ts the jwt and session callbacks enrich the token/session with a role claim. | Adds authorisation data without polluting the core user model; downstream pages can simply read session.user.role. |
| Feature‑Toggle (SiteSetting model) | The SiteSetting model holds flags (e.g., maintenanceMode). UI components read this via adminActions.getSiteSettings(). | Allows runtime enable/disable of features without code deployments. |
| Error‑Boundary & Logging Wrapper | Each server‑action (actions.ts, paymentAction.ts) wraps DB calls in try/catch and logs via console.error (could be swapped for a proper logger). | Guarantees that a failure in one async flow does not crash the whole request pipeline. |
🔄 Request Lifecycle (Typical Flows)
| Flow | Entry Point (UI) | Server‑Side Handler | DB / External Calls | Response |
|---|---|---|---|---|
| Login | src/app/login/page.tsx (form → signIn from next-auth) | auth.ts (CredentialsProvider.authorize) → connectDB() → User.findOne | bcrypt password compare | JWT cookie + redirect to /dashboard |
| Register | src/app/register/page.tsx (POST → actions.registerUser) | src/lib/actions.ts → User.create (hash password) | DB insert | JSON {ok:true} → client redirects |
| View Rooms | src/app/rooms/page.tsx (SSR fetch → /api/rooms) | src/app/api/rooms/route.ts (not shown, but typical) → Room.find | DB read | List of rooms (JSON) |
| Book a Room | src/app/rooms/[id]/BookingForm.tsx (POST → actions.createBooking) | src/lib/actions.ts.createBooking → Booking.create + email.sendBookingConfirmation + optional paymentAction.initiate | DB insert, Email service, Payment gateway | Booking ID, status |
| Admin Approve/Reject | src/app/admin/page.tsx (AdminBookingActions component) → adminActions.updateBookingStatus | src/lib/adminActions.ts → Booking.findByIdAndUpdate + email.sendStatusUpdate | DB update, Email | Updated booking record |
| Upload Room Image | src/components/AdminForms.tsx (file input → cloudinary.upload) | src/lib/cloudinary.ts.upload → Cloudinary SDK | HTTP upload to Cloudinary | URL stored in Room.images |
| Send Feedback | src/app/feedback/page.tsx (POST → actions.createFeedback) | src/lib/actions.ts.createFeedback → Feedback.create + email.sendFeedbackReceived | DB insert, Email | Confirmation toast |
| Logout | src/components/LogoutButton.tsx (click → signOut) | NextAuth signOut handler | Clears JWT cookie | Redirect to /login |
| These flows are visualised in the Data‑Flow & State‑Transitions table below. |
2️⃣ Data Flow & State Transitions
| Origin | Action | Logic Handler | Resulting State |
|---|---|---|---|
LoginPage (src/app/login/page.tsx) | Submit credentials → signIn('credentials', …) | auth.ts → CredentialsProvider.authorize | session JWT created, user.role stored, client redirected to /dashboard |
RegisterPage (src/app/register/page.tsx) | Submit registration form → POST to /api/register | src/lib/actions.ts.registerUser (hash pwd, User.create) | New User document persisted, client receives {ok:true} |
RoomsPage (src/app/rooms/page.tsx) | GET /api/rooms (SSR) | src/app/api/rooms/route.ts → Room.find() | React props contain array of Room objects |
BookingForm (src/app/rooms/[id]/BookingForm.tsx) | POST → /api/bookings | src/lib/actions.ts.createBooking → Booking.create + email.sendBookingConfirmation | Booking document with status pending, email sent, UI shows success |
AdminBookingActions (src/components/AdminBookingActions.tsx) | Click Approve → POST /api/admin/bookings/:id | src/lib/adminActions.ts.updateBookingStatus → Booking.findByIdAndUpdate + email.sendStatusUpdate | Booking status changes to approved, email to guest sent |
AdminForms (src/components/AdminForms.tsx) | Upload image → Cloudinary SDK | src/lib/cloudinary.ts.upload | Cloudinary returns URL → saved in Room.images array |
FeedbackPage (src/app/feedback/page.tsx) | POST feedback → /api/feedback | src/lib/actions.ts.createFeedback → Feedback.create + email.sendFeedbackReceived | Feedback persisted, admin receives email, UI shows thank‑you |
LogoutButton (src/components/LogoutButton.tsx) | Click → signOut() | NextAuth sign‑out handler | JWT cookie cleared, redirect to /login |
SiteSetting (any admin page) | Toggle flag → adminActions.updateSiteSetting | SiteSetting.findOneAndUpdate | In‑memory flag read by subsequent requests (e.g., maintenance mode) |
3️⃣ Mermaid Diagram (Component Map)
The diagram groups the concrete files into four logical sub‑graphs that mirror the layer stack above.
Node IDs are short alphanumeric identifiers; the human‑readable labels contain the actual file paths.
How to read the diagram
- Arrows indicate invocation or data‑dependency (e.g., a page component posts to an API route).
- Sub‑graphs are logical boundaries; they are not separate processes – all run inside the same Next.js serverless environment, but the visual grouping helps reason about responsibilities.
- External nodes (
E1‑E3) represent third‑party services that are only touched through thin wrapper libraries (cloudinary.ts,email.ts,paymentAction.ts).
📚 Take‑away Summary
- Clear separation of concerns – UI, API, service, persistence, and external‑integration layers are each encapsulated in their own directories.
- Reusable patterns – Singleton DB, Repository‑style Mongoose models, Strategy‑based auth, Factory for external SDKs, CQS in server actions.
- Extensibility – Adding a new auth provider, swapping Cloudinary for another media store, or swapping the email transporter requires only changes inside the Factory wrapper files; the rest of the codebase remains untouched.
- State management – The only mutable “global” state lives in the JWT/session (role, user id) and in the MongoDB collections; everything else is derived per‑request, which aligns with Next.js’s serverless nature.
- Testability – Because each layer only depends on interfaces (models, wrapper functions) you can unit‑test the service layer by mocking
User,Room, etc., and integration‑test the API routes with an in‑memory MongoDB.
Feel free to ask for deeper dives into any specific file (e.g., the exact implementation of src/lib/paymentAction.ts) or for suggestions on how to improve the architecture (e.g., introducing a GraphQL layer, adding a caching layer with Redis, etc.).
📈 System Architecture Diagram
🛠️ 4. Function Breakdowns
Below is a function‑level breakdown of every executable export and internal routine that appears in the source files you supplied.
For each file a Markdown table lists:
| Function / Export Name | Parameters | Logic Description | Impact / Side‑effects |
|---|
auth.ts
| Function / Export Name | Parameters | Logic Description | Impact |
|---|---|---|---|
handlers (exported) | (req: NextApiRequest, res: NextApiResponse) – supplied by NextAuth when you spread ...handlers in a route file. | A collection of request‑handler functions (GET, POST, OPTIONS, …) generated by NextAuth. Internally they route authentication‑related HTTP calls to the appropriate provider, callback, session, etc. | Enables the Next.js API route (/api/auth/[...nextauth]) to serve the full auth flow (sign‑in, sign‑out, callbacks, CSRF, etc.). |
signIn (exported) | (provider: string, options?: SignInOptions, authorizationParams?: SignInAuthorizationParams) | Wrapper around NextAuth.signIn. Calls the built‑in signIn method that redirects the user to the chosen provider (here only Credentials) or initiates the credentials flow. | Allows UI components (e.g., a login form) to programmatically start a sign‑in. Returns a Promise<RedirectResult> that resolves when the auth request finishes. |
signOut (exported) | (options?: SignOutParams) | Wrapper around NextAuth.signOut. Clears the JWT/session cookie and optionally redirects. | Used by UI to log the user out and clean up the server‑side session token. |
auth (exported) | (req: NextApiRequest, res: NextApiResponse) – the same signature as an API route handler. | The core NextAuth handler that executes the request‑pipeline (provider verification, credential verification, callbacks, token creation, etc.). It is usually exported as GET, POST, etc. from pages/api/auth/[...nextauth].ts. | Provides the entry point for all auth‑related HTTP verbs; without it the app cannot authenticate. |
authorize (inner function of CredentialsProvider) | credentials: { email?: string; password?: string } | 1. Guard clause – returns null if email or password missing. <br>2. Connects to MongoDB via connectDB(). <br>3. Looks up a User document by email. <br>4. If user exists, uses bcrypt.compare to verify password. <br>5. On success returns a minimal user object (id, email, name, role). <br>6. On any failure returns null. <br>7. Errors are caught, logged, and also result in null. | Determines whether the supplied credentials map to a valid user. Returning null tells NextAuth the authentication failed, causing a redirect to the sign‑in page with an error. |
jwt (callback) | ({ token, user }) where token: JWT, user?: User (only on the first sign‑in) | If a user object is present (first sign‑in), copies user.role and user.id onto the JWT payload (token.role, token.id). Always returns the (potentially enriched) token. | Persists role and id in the JWT so they survive across requests and can be read in the session callback or client‑side useSession. |
session (callback) | ({ session, token }) where session: Session, token: JWT | Mutates session.user by adding role and id from the JWT payload. Returns the modified session object. | Makes role and id available on the client via useSession and on the server via getServerSession. |
pages.signIn (configuration) | N/A | Sets the custom sign‑in page route to /login. | Users trying to access a protected page are redirected to /login instead of the default NextAuth UI. |
session.strategy (configuration) | N/A | Uses JWT‑based sessions (strategy: "jwt"). | No server‑side session store; the token is stored in a cookie and validated on each request. |
secret (configuration) | process.env.AUTH_SECRET | Supplies a secret for signing/encrypting JWTs and CSRF tokens. | Critical for security; without it NextAuth will generate a dev‑only secret. |
Supporting Imports & Types (not functions but important for context)
| Import / Type | Description |
|---|---|
NextAuth | Factory that builds the auth handler and exports the helper functions (handlers, signIn, signOut, auth). |
CredentialsProvider | Provider that lets you authenticate with a username/password pair via the authorize callback. |
connectDB | Helper that opens a MongoDB connection (likely using Mongoose). Required before any DB query. |
User | Mongoose model representing a user document (email, password, name, role, …). |
bcrypt | Library used to compare the plaintext password with the hashed password stored in DB. |
DefaultSession | Type from next-auth that we augment to add id and optional role. |
Module augmentation (declare module "next-auth" { … }) | Extends the default User and Session interfaces so TypeScript knows about the custom fields (role, id). |
next.config.ts
| Function / Export Name | Parameters | Logic Description | Impact |
|---|---|---|---|
default (nextConfig object) | N/A | Exports a plain configuration object typed as NextConfig. Currently empty ({}), meaning the project relies on Next.js defaults. | Allows future customisation of Next.js behaviour (webpack, rewrites, image domains, etc.). No runtime effect as‑is. |
netlify.toml
This file is a static configuration for Netlify; it contains no executable functions, therefore no table is required.
Summary of the Authentication Flow
- Client calls
signIn('credentials', { email, password }). - NextAuth forwards the request to the
CredentialsProvider.authorizefunction. authorizeconnects to MongoDB, fetches the user, verifies the password withbcrypt.- On success it returns a user payload; NextAuth creates a JWT.
- The
jwtcallback storesroleandidinside the token. - The
sessioncallback copies those fields ontosession.user. - Subsequent
useSessioncalls (client) orgetServerSession(server) exposesession.user.idandsession.user.role. signOutclears the JWT cookie, ending the session.
All exported helpers (handlers, signIn, signOut, auth) are intended to be wired into a Next.js API route (e.g., pages/api/auth/[...nextauth].ts) like so:
import { handlers } from '@/auth';
export const GET = handlers.GET;
export const POST = handlers.POST;
export const OPTIONS = handlers.OPTIONS;
That wiring is what makes the authentication system operational throughout the app.