Skip to lesson content

PROJECT 4 · LESSON 10 OF 18

Read tasks from a database

Start a separate task application and render durable data on the server.

  • MongoDB
  • environment variables
  • async Server Components
  • loading UI

Your workspace: task-app

Start a new practice folder. The completed checkpoint includes all configuration and source files.

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

Browser storage teaches persistence on one device. A database makes records available across requests and devices. We switch to a small task application so database concepts can be learned without also reasoning about prices, carts and stock.

Pause EduShop and create a separate task-app folder. Download this checkpoint to get the starter files. Use a new learning database, never your EduPoly production database.

Provision a MongoDB Atlas learning cluster or a local MongoDB instance. Create a database user with access only to the learning database, configure network access for your machine, and put its connection URI in .env.local. Do not commit that file.

The server queries the database directly. There is no need to call your own API from a Server Component. force-dynamic keeps this beginner example request-rendered; caching can be added deliberately later.

Understand the database vocabulary before connecting

A MongoDB database contains collections, and a collection contains documents. Our learning database is edupoly_tasks_lab, its collection is tasks, and each document describes one task. MongoDB adds an _id when we insert without supplying one. title, completed and createdAt are our application fields.

Atlas is a service that hosts MongoDB. Your Atlas website account manages the cluster; a database user is a separate credential used by the application. Network access rules also need to allow your development machine. A correct password alone does not overcome a blocked network connection.

Keep the connection on the server

lib/db.ts reads MONGODB_URI from the process environment and constructs MongoClient. The client manages database connections; do not create a new client in each row component or every form handler. The development global prevents repeated hot reloads from creating unnecessary new clients.

client.db selects a database handle. collection selects a collection handle. These handles describe where operations will run; the actual query is awaited in the page. The MongoDB driver establishes connections as needed. import server-only makes accidental inclusion in a client module graph a build error.

Copy .env.example to .env.local in the project root. Replace the placeholder URI using your own learning credentials and retain the learning database name. Never copy EduPoly’s site credentials into a student app. Restart the dev server after editing environment configuration.

Read the query from left to right

find({}) selects every task because the filter has no conditions. sort({ createdAt: -1 }) requests newest first. limit(100) caps the list for this small lab. toArray executes and collects the cursor results into the array the page can render. Without that last step, you have a cursor, not the task array.

The async Server Component can await this query directly. There is no browser fetch to an API we would only create to call the same database. force-dynamic makes the example request-rendered. This lesson deliberately avoids adding caching until students understand where freshness comes from.

An empty result produces No tasks yet. A failed query reaches error.tsx instead. loading.tsx provides pending UI at the route boundary; a fast response may finish before a user notices it. These represent three different states: waiting, successful but empty, and failed.

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 requests the task page.

  2. The server obtains the tasks collection handle from the server-only data module.

  3. MongoDB executes the find, sort and limit query and returns documents.

  4. The Server Component renders task titles or the empty state; a query failure reaches the error boundary.

Follow one stored task

  1. Imagine a document with title Read routing notes, completed false, and a createdAt date.
  2. The query includes it because the empty filter matches all documents.
  3. The page converts its ObjectId to a string for the React key, then displays the title and Open.
  4. Refreshing reads the database again. The record survives because it lives outside the React component and server process.

3. Build it, one file at a time

  1. Copy .env.example to .env.local and replace the URI placeholder. Use MONGODB_DB=edupoly_tasks_lab.
  2. Run npm install and npm run dev in the new folder after stopping the store server.
  3. Open /. An empty list is a valid starting state; the next lesson adds records.
Terminal
npm install
# Copy .env.example to .env.local and configure MongoDB.
npm run dev

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",
    "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.

tsconfig.json

This configures TypeScript and module resolution; it does not define a browser route.

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "skipLibCheck": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

Read the code

  1. strict enables stronger checks for missing values and mismatched types. noEmit lets Next.js own compilation while TypeScript checks correctness.
  2. The @/* paths mapping points imports at the project root. @/lib/products therefore resolves to lib/products, not a network address.
  3. include identifies files to check and exclude avoids checking installed dependency source. Next.js can add framework-required settings when it builds.

next-env.d.ts

This declaration file makes Next.js and image-import types available to TypeScript.

next-env.d.ts
/// <reference types="next" />
/// <reference types="next/image-types/global" />

Read the code

  1. The triple-slash references load framework type declarations, not executable browser code.
  2. Next.js manages this file during development. Put application types in your own modules instead of adding business logic here.

next.config.ts

This is the learner application’s framework configuration.

next.config.ts
export default {};

Read the code

  1. The empty export uses the framework defaults for this course. It deliberately does not enable Cache Components.
  2. Do not confuse this file with a page or an environment file. Changing framework configuration may require restarting the development server.

.gitignore

This keeps generated files and local secrets out of your practice repository.

.gitignore
node_modules/
.next/
.env*
!.env.example
*.tsbuildinfo

Read the code

  1. node_modules and .next can be regenerated from source and dependencies. They should not be committed.
  2. .env* excludes local environment files, while !.env.example allows a safe placeholder template. Ignoring a file does not remove a secret already committed to history.

app/globals.css

This shared stylesheet makes the practice application readable without introducing a styling framework.

app/globals.css
* {
  box-sizing: border-box;
}
body {
  margin: 0 auto;
  max-width: 1000px;
  padding: 24px;
  font: 17px/1.6 system-ui;
  color: #17243c;
}
nav {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 16px 0;
  border-bottom: 1px solid #ccd4e0;
}
a {
  color: #174b93;
}
main {
  padding: 24px 0;
}
article,
form {
  border: 1px solid #ccd4e0;
  padding: 18px;
  margin: 16px 0;
  border-radius: 10px;
}
label {
  display: block;
  margin: 8px 0;
}
input,
button,
select {
  font: inherit;
  padding: 8px;
  max-width: 100%;
}
button {
  cursor: pointer;
}
button:disabled {
  cursor: wait;
  opacity: 0.6;
}
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}
:focus-visible {
  outline: 3px solid #d74819;
  outline-offset: 3px;
}

Read the code

  1. The layout imports this stylesheet once so its element and class rules apply throughout the app.
  2. The .grid rule adapts cards to the available width. The focus-visible rule gives keyboard users a visible focus indicator.
  3. These are ordinary CSS rules; none of them creates a route, fetches data or changes React state.

app/layout.tsx

This defines the document and shared structure surrounding the selected page.

app/layout.tsx
import type { ReactNode } from "react";
import Link from "next/link";
import "./globals.css";
export const metadata = { title: "My task lab" };
export default function Layout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <nav>
          <Link href="/">Tasks</Link>
        </nav>
        <main>{children}</main>
      </body>
    </html>
  );
}

Read the code

  1. html and body belong to this root layout. children is the selected route content and must appear in the returned tree.
  2. Shared navigation belongs here so individual pages do not copy it. Link destinations are URL paths, not source filenames.
  3. The stylesheet import applies the shared presentation. The metadata export describes the document rather than rendering visible content.

.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

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.

lib/db.ts

This creates and shares the server-side database client and selects the learning database.

lib/db.ts
import "server-only";
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Set MONGODB_URI in .env.local");
const globalDB = globalThis as typeof globalThis & {
  courseClient?: MongoClient;
};
export const client = globalDB.courseClient ?? new MongoClient(uri);
if (process.env.NODE_ENV !== "production") globalDB.courseClient = client;
export const db = client.db(process.env.MONGODB_DB ?? "edupoly_tasks_lab");

Read the code

  1. import server-only prevents this runtime module from being pulled into a Client Component. The URI stays in server configuration.
  2. The explicit missing-URI check produces an actionable configuration error. MongoClient is reused during development to avoid creating clients on every hot reload.
  3. client.db selects the configured database. Collection and query modules use this handle; pages should not rebuild the connection themselves.

lib/tasks.ts

This names the tasks collection and describes its application fields.

lib/tasks.ts
import "server-only";
import { db } from "./db";
export type Task = {
  title: string;
  completed: boolean;
  createdAt: Date;
  userId?: string;
};
export const tasks = db.collection<Task>("tasks");

Read the code

  1. collection<Task>("tasks") tells TypeScript what task records should contain. MongoDB still needs runtime input validation before writes.
  2. createdAt is a Date in the database, not a formatted browser string. userId is optional at first so shared records from Project 4 remain representable.
  3. The handle itself is not a list of tasks. Call find and consume its cursor in the server page.

app/page.tsx

This Server Component reads the task list and composes the appropriate task controls.

app/page.tsx
import { tasks } from "@/lib/tasks";
export const dynamic = "force-dynamic";
export default async function TasksPage() {
  const rows = await tasks
    .find({})
    .sort({ createdAt: -1 })
    .limit(100)
    .toArray();
  return (
    <>
      <h1>Tasks</h1>
      {rows.map((task) => (
        <article key={task._id.toString()}>
          {task.title} — {task.completed ? "Done" : "Open"}
        </article>
      ))}
      {!rows.length && <p>No tasks yet.</p>}
    </>
  );
}

Read the code

  1. The async page awaits a database cursor converted to an array. sort requests newest first and limit bounds the teaching example.
  2. force-dynamic keeps the task read request-rendered. An empty array renders the empty message rather than an exception.
  3. MongoDB ObjectIds are converted to strings before becoming component keys or client editor props.

app/loading.tsx

This provides the pending view for the route while server content is being prepared.

app/loading.tsx
export default function Loading() {
  return <p role="status">Loading tasks…</p>;
}

Read the code

  1. The role=status text communicates loading without pretending the task result is empty.
  2. Fast requests may complete before the loading UI is noticeable. Do not add artificial delays to production logic merely to keep it visible.

app/error.tsx

This route error boundary supplies a recovery screen for unexpected failures.

app/error.tsx
"use client";
export default function ErrorPage({ reset }: { reset: () => void }) {
  return (
    <>
      <h1>We could not load your tasks</h1>
      <p>Check the server connection and try again.</p>
      <button onClick={reset}>Try again</button>
    </>
  );
}

Read the code

  1. The boundary is a Client Component because reset is an interactive recovery operation. The button asks the framework to retry rendering the boundary’s contents.
  2. Show a useful general message here, and investigate the detailed exception in server diagnostics. Do not display database credentials or raw error internals to visitors.

4. Run it and check your result

  • The empty state appears with a valid database connection.
  • An unavailable database produces the error screen; details remain in server logs.

5. Predict, change and observe

Stop the development server, start it again, and revisit the task list after adding records in the next lesson.

Compare your prediction with the expected result

What you should observe

The database records remain even though the application process restarted.

Why it happens

Persistence belongs to MongoDB. A module-level array would be recreated when the server starts and is not an equivalent storage layer.

6. Troubleshoot with evidence

A common mistake

A connection URI is not an HTTP URL. Restart the dev server after changing .env.local. This unauthenticated CRUD lab is local practice only.

MongoDB reports an authentication failure.

Likely cause: The URI has incorrect database-user credentials or an incorrectly encoded password.

Check and correct: Use the database user created for this cluster, not the Atlas website login. Copy the driver URI and encode special characters in credential segments.

The connection waits and then times out.

Likely cause: The cluster, network rule, hostname or local server may be unavailable.

Check and correct: Check cluster availability and network access. For a local URI, ensure MongoDB is running. Do not solve it by exposing credentials to the browser.

7. Practice and explain it back

Your independent task

Explain why lib/db.ts must never be imported into a Client Component.

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

What does find({}) mean?

It has no filtering conditions, so every task is eligible. Later we replace it with a userId filter to make reads private.

Why is No tasks yet different from an error?

An empty array means the database operation succeeded with zero matches. A connection or query failure means the application could not establish the result.