Skip to lesson content

PROJECT 5 · LESSON 15 OF 18

Make every task private

Enforce ownership in reads and all three mutations.

  • authorization
  • ownership
  • server-side checks

Your workspace: task-app

Continue from lesson 14: Build the account screens. 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

A login screen is not enough to make data private. The server must constrain every read and every write to the current user. This lesson adds ownership at the database boundary so manipulating a URL or hidden input cannot cross that boundary.

Authentication tells you who is signed in. Authorization decides which task that person may read or change. A hidden form field can be edited, so ownership must be part of the database filter.

requireUser runs before each mutation. The user ID is derived from the verified session; the form supplies only task content and the target task ID.

Existing tasks from Project 4 have no owner and become invisible. Leave those learning records alone or remove them manually from your disposable lab database. Never automatically assign unowned records to whoever signs in first.

Make ownership part of the data model

New tasks now store userId from requireUser. The create action does not accept userId from FormData. That prevents a caller from assigning a task to another person by submitting an extra field. createdAt and completed are still determined by the server-side create operation.

Project 4 tasks have no owner and will not match any userId filter. We leave them invisible rather than guessing who should own them. A real migration would need an explicit data policy; “give all old rows to the first person who logs in” would expose shared records arbitrarily.

Apply the same rule to reads and mutations

The list changes from find({}) to find({ userId: user.id }). This prevents another user’s tasks from entering the rendered page at all. Filtering them with JavaScript in the browser would already have disclosed the records before hiding them.

Updates and deletes use both _id and userId in one database filter. Those conditions are combined: the record must have the requested ID and belong to the verified caller. This is stronger than merely checking that somebody is signed in.

Each action calls requireUser independently. The visible page may have been loaded earlier, a session may have ended, and requests can invoke the action without using the current UI. The mutation therefore checks its own caller at execution time.

Interpret a failed match without revealing other users’ data

When B submits A’s ID, the combined filter matches nothing. The action returns the same unavailable-task outcome as a missing record. It should not respond with A’s title or owner details just to explain why access failed.

An atomic filter on the write also avoids separating “check ownership” and “perform update” into unrelated operations. The database applies the requested change only to a document meeting both conditions when that write executes.

This still does not solve every concurrency problem: two tabs belonging to the same user may overwrite each other’s valid edits. Ownership and optimistic concurrency address different requirements.

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. The request session identifies user B.

  2. requireUser supplies B’s trusted ID to the query.

  3. The database looks for the requested task ID together with userId=B.

  4. A’s task fails that combined filter, so it is neither returned nor changed.

Evaluate the ownership filter explicitly

  1. A’s task has _id=X and userId=A.
  2. B submits X in the hidden ID input while using a valid B session.
  3. The update filter becomes {_id: X, userId: B}. The ID condition is true for A’s task, but the owner condition is false.
  4. No document matches. matchedCount is zero and the title remains unchanged. Signing in was necessary but did not grant access to every task.

3. Build it, one file at a time

  1. Replace the page and action module with these protected versions.
  2. Create a new task as account A. Use a separate browser profile for account B.
  3. For a deliberate authorization test, copy A’s task ID from its hidden input, replace B’s hidden task ID in developer tools, and submit B’s form. The write must find no matching task.

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.

app/actions.ts

This module owns the task mutations and their server-side validation.

app/actions.ts
"use server";
import { requireUser } from "@/lib/session";
import { ObjectId } from "mongodb";
import { revalidatePath } from "next/cache";
import { tasks } from "@/lib/tasks";
export type Result = { message: string };
export async function createTask(
  _previous: Result,
  data: FormData,
): Promise<Result> {
  const user = await requireUser();
  const title = String(data.get("title") ?? "").trim();
  if (!title || title.length > 120)
    return { message: "Enter a title between 1 and 120 characters." };
  try {
    await tasks.insertOne({
      title,
      completed: false,
      createdAt: new Date(),
      userId: user.id,
    });
  } catch {
    return { message: "Could not save. Please try again." };
  }
  revalidatePath("/");
  return { message: "Task added." };
}
export async function updateTask(
  _previous: Result,
  data: FormData,
): Promise<Result> {
  const user = await requireUser();
  const id = String(data.get("id") ?? "");
  const title = String(data.get("title") ?? "").trim();
  if (!/^[a-f0-9]{24}$/i.test(id) || !title || title.length > 120)
    return { message: "Check the task ID and title." };
  try {
    const result = await tasks.updateOne(
      { _id: new ObjectId(id), userId: user.id },
      { $set: { title, completed: data.get("completed") === "on" } },
    );
    if (!result.matchedCount) return { message: "Task no longer exists." };
  } catch {
    return { message: "Could not update task." };
  }
  revalidatePath("/");
  return { message: "Task updated." };
}
export async function deleteTask(
  _previous: Result,
  data: FormData,
): Promise<Result> {
  const user = await requireUser();
  const id = String(data.get("id") ?? "");
  if (!/^[a-f0-9]{24}$/i.test(id)) return { message: "Invalid task ID." };
  try {
    const result = await tasks.deleteOne({
      _id: new ObjectId(id),
      userId: user.id,
    });
    if (!result.deletedCount) return { message: "Task no longer exists." };
  } catch {
    return { message: "Could not delete task." };
  }
  revalidatePath("/");
  return { message: "Task deleted." };
}

Read the code

  1. Every action calls requireUser. Create records the session user ID; update and delete include that same owner ID in the database filter. Caller-provided IDs cannot bypass this condition.
  2. use server marks its exported async operations as Server Functions. Through useActionState they receive the previous result and submitted FormData.
  3. createTask trims the title, checks length, inserts normalized data and then revalidates the list route. Expected failures return message objects instead of exposing raw exceptions.
  4. updateTask validates the string ID before constructing ObjectId, then uses $set for editable fields. matchedCount distinguishes a missing target from an unchanged valid task.
  5. deleteTask validates the target ID and checks deletedCount. Successful mutations revalidate the same list route.

app/page.tsx

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

app/page.tsx
import { requireUser } from "@/lib/session";
import { tasks } from "@/lib/tasks";
import NewTask from "@/components/new-task";
import TaskEditor from "@/components/task-editor";
export const dynamic = "force-dynamic";
export default async function TasksPage() {
  const user = await requireUser();
  const rows = await tasks
    .find({ userId: user.id })
    .sort({ createdAt: -1 })
    .limit(100)
    .toArray();
  return (
    <>
      <h1>{user.name}’s tasks</h1>
      <NewTask />
      {rows.map((task) => (
        <TaskEditor
          key={task._id.toString() + task.title + task.completed}
          task={{
            id: task._id.toString(),
            title: task.title,
            completed: task.completed,
          }}
        />
      ))}
      {!rows.length && <p>No tasks yet.</p>}
    </>
  );
}

Read the code

  1. requireUser supplies the owner identity before the query. find({ userId: user.id }) excludes every other user’s records on the server.
  2. The async page awaits a database cursor converted to an array. sort requests newest first and limit bounds the teaching example.
  3. force-dynamic keeps the task read request-rendered. An empty array renders the empty message rather than an exception.
  4. MongoDB ObjectIds are converted to strings before becoming component keys or client editor props.
  5. NewTask owns form feedback. The page still owns the database read; the mutation revalidates this route to obtain updated rows.
  6. TaskEditor receives only id, title and completed. Its key changes with saved fields so uncontrolled inputs receive refreshed defaults.

4. Run it and check your result

  • A sees only A’s tasks; B sees only B’s tasks.
  • B cannot update or delete A’s task even with its ID.
  • Signed-out visits redirect to /sign-in and mutations require a session.

5. Predict, change and observe

Using two isolated browser sessions, attempt to edit A’s task through B’s form by substituting its hidden ID.

Compare your prediction with the expected result

What you should observe

B gets an unavailable-task message and A’s stored record is unchanged.

Why it happens

This tests the server rule directly. Merely checking that A’s task is absent from B’s screen would not verify the write protection.

6. Troubleshoot with evidence

A common mistake

Hiding edit buttons or checking only a layout is insufficient. Every read and mutation must enforce ownership.

Users still see all tasks.

Likely cause: The page query remains find({}) even though writes were protected.

Check and correct: Filter the read on the server with the current session user ID.

Old tasks disappear after adding ownership.

Likely cause: Those shared lab records do not contain userId.

Check and correct: Create new owned tasks to verify the flow. Do not automatically attach unowned records to the current user.

7. Practice and explain it back

Your independent task

Add a due date while preserving the ownership filter in every operation.

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

Why is a hidden ID not an authorization mechanism?

It is caller-controlled form input. It identifies what the caller wants to change but does not establish a right to change it.

Why must createTask also require a session?

The action needs a verified owner and must reject signed-out creation. Protecting only the list page would leave the write boundary incomplete.