Thuta Learning
Next.js
AdvancedWeb DevelopmentIntermediate

Final Project — Making Myanmar Notes Production-Ready

Next.jsLesson 2890 min

What you'll walk away with

  • Sketch Myanmar Notes' routes, data layer, Server Actions and permissions as one system
  • Finish each feature end to end, from UI to database to tests, as a vertical slice
  • Write acceptance criteria that cover both what users see and what the server enforces
  • Check session, validation and ownership in a fixed order in every Server Action
  • Write a README covering architecture decisions, setup, env, tests and deployment

Explain it simply

Explain it simply

In driving lessons, the instructor sits next to you and can hit the brake. Only on the first day you drive alone do you find out whether you can really drive. Finishing a tutorial is the same: the knowledge becomes yours when you can build a feature start to finish on your own judgement, without a reference.

In this final project the earlier lessons come back together, not as separate pieces but as one system. Routing brings users to pages, the data layer fetches notes, Server Actions save changes safely, and tests and deployment keep it all working.

Problem → Why → Solution

The problem: everything started, nothing finished

Three weeks in, a look at Myanmar Notes shows every feature half done. The note list looks great but shows fake data; the create form writes to the database but has no validation; there is a login page, yet the dashboard lets anyone edit anyone's notes.

Asked for a demo, there is not a single flow that works from start to finish. Asked what is done, the only answer is "about 90%".

status.md
Notes list      UI done        data: hard-coded array
Note detail     UI done        404 page: missing
Create note     form done      validation: none, tests: none
Edit note       started        permission check: none
Login           page done      dashboard: not protected
Deploy          not started    env vars: unknown

Why does this happen?

The work was split by layer: all the UI first, then all the database, then security. Every layer sits at 90%, yet the number of features a user can actually use is zero. Finish one feature through UI, validation, database, permissions and tests before starting the next, and you always have an app you can show.

Core concept: vertical slices through one system

A vertical slice is like cutting a cake from top to bottom instead of peeling off one layer: every piece contains all the layers. An "edit note" slice includes the edit page (route), the form (a Client Component), the Server Action, zod validation, the ownership check, the database update, revalidatePath and redirect, a unit test and one E2E test. Every finished slice leaves you with a better app you can deploy.

Because every slice is part of one system, the architecture needs to be clear first. Myanmar Notes has only two paths for data: reading and changing. When reading, a Server Component calls a function in lib/notes, which queries the database. Public notes are cached, while dashboard data is dynamic per user. When changing, a form calls a Server Action, which checks things in a fixed order: is there a session, is the input valid, may this user edit this note; only then does it update the database and revalidate the cache.

Acceptance criteria define when a slice may be called done. Good criteria are checkable and free of opinion: "trying to edit someone else's note returns 403 and leaves the database unchanged" can be checked, whereas "editing works well" cannot. Link each criterion to a test, and you know automatically that later changes have not broken it.

Order the slices by risk and value. Build the read path first, because every other slice depends on real data showing up. Put authentication second, since edit and delete are meaningless without knowing who the user is. Leave polish such as search, Open Graph images and animations for later: they improve a working app, but cannot rescue a broken one.

text
Myanmar Notes: the read path and the write path
-----------------------------------------------
READ                                   WRITE
browser ─> /notes/[slug]               form submit (Client Component)
             Server Component                 │
                 │                             ▼
                 ▼                       Server Action
           lib/notes.getNote()        1. session?      no  -> 401
                 │                    2. zod valid?    no  -> 400
                 ▼                    3. owner/admin?  no  -> 403
              database  <───────────  4. db update
                 │                    5. revalidatePath + redirect
                 ▼
     HTML (cached for public notes)
Mental model: slice the cake top to bottom
  1. Write one feature's criteria first
  2. Build through UI, action and DB
  3. Pin each server rule with a test
  4. Deploy, then start the next slice

Ask at any moment: if we deployed now, what could users actually do? That answer should keep growing.

General pattern: acceptance criteria for one slice

text
Feature: <name>
As a <role>, I can <action> so that <benefit>.

Done when:
  - <what the user sees on success>
  - <what the user sees on invalid input, empty data or loading>
  - <the rule the server enforces, with its status code>
  - <the test that proves each rule>
  - <it works on the preview deployment>

Each line must be a checkable sentence. A slice is truly end to end only when the UI side, the server side and the tests are all covered.

Example: the Myanmar Notes Definition of Done

The checklist below is the Definition of Done for the whole project. It is not meant to be worked through from top to bottom. Each slice moves several lines forward a little: the "create note" slice, for example, advances validation, server-side authorization, loading and error states, and tests all at once. Only when every line is ticked can the app be called production-ready.

text
Final Project Definition of Done

✓ Public notes list + detail routes
✓ Login-protected dashboard
✓ Create / edit / delete with validation
✓ Server-side authorization
✓ Loading / error / not-found states
✓ Search, metadata, sitemap and OG image
✓ Responsive and keyboard accessible UI
✓ Tests and successful production build
✓ Preview + production deployment
✓ Logs, Web Vitals and rollback plan

Code breakdown

  1. Public read path✓ Public notes list + detail routes

    /notes and /notes/[slug] are public pages readable without logging in. They should be static or cached for speed, and appear in metadata and the sitemap. An unknown slug shows the 404 page through notFound().

  2. Rules live on the server✓ Server-side authorization

    Hiding the Edit button is a UI convenience, not security. Anyone can call a Server Action directly, so every action must check the session and ownership itself.

  3. Every state, not just success✓ Loading / error / not-found states

    Give every important route a loading.tsx, error.tsx and not-found.tsx. New users with no notes need an empty state too, because it is the first screen every new user sees.

  4. Proof, not hope✓ Tests and successful production build

    Unit tests cover the validation and permission rules, one E2E test covers creating a note, and pnpm build passes without new warnings.

  5. Life after launch✓ Logs, Web Vitals and rollback plan

    Shipping is not the end. With structured logs, a Web Vitals dashboard and a known rollback version, you notice problems before users report them and can back out within minutes.

You should see
You end up with a production-ready Myanmar Notes app you can explain and maintain yourself, from the fundamentals through to deployment.

Folder layout

This layout combines the route groups, dynamic routes and separated data layer from earlier lessons. The single rule is that app/ holds routes and UI only, while code that makes decisions (validation, permissions, queries) lives in lib/, where it is easy to test.

text
app/
  (public)/notes/page.tsx            list, ?q= search, ?page= pagination
  (public)/notes/[slug]/page.tsx     detail + generateMetadata
  dashboard/layout.tsx               redirects signed-out users to /login
  dashboard/notes/new/page.tsx       create form
  dashboard/notes/[id]/edit/         edit form + actions.ts ("use server")
  api/health/route.ts                liveness / readiness
  sitemap.ts, robots.ts
lib/
  db.ts            database client (server-only)
  notes.ts         queries: getPublicNotes, getNote, ...
  validation.ts    zod schemas shared by actions and tests
  permissions.ts   canEdit(session, note)
e2e/create-note.spec.ts

A milestone plan

MilestoneProof that it is done
1. Read path: list, detail and 404The preview URL shows real notes from the database
2. Auth: login and a protected dashboardOpening /dashboard signed out redirects to /login
3. Create sliceAn E2E test creates a note and lands on its detail page
4. Edit and delete sliceA unit test confirms 403 for someone else's note
5. Search, metadata and sitemap/sitemap.xml lists the public notes
6. Production and monitoringThe smoke test passes and the dashboard shows the release

A security review for every Server Action

1. Get the session inside the action

Never take the user ID from a hidden form field; the browser can send anything. Read the session from the cookie inside the action yourself, and stop immediately if there is none.

2. Validate all input with a schema

Every FormData value is a string or a File and could contain anything. Check trimming, length and allowed values with a zod schema, and ignore fields the schema does not list.

3. Load the resource and check ownership

Load the note by ID from the database: 404 if it does not exist, 403 if the user is neither the owner nor an admin. Keeping this check in lib/permissions means every action applies the same rule.

4. Refresh the cache after the change

Only after the database update succeeds, call revalidatePath or revalidateTag and redirect. Otherwise the public list keeps showing the old note.

What the README must contain

  • What the project is, with the live URL and a screenshot
  • Architecture decisions and why (for example "public notes are cached; the dashboard is dynamic")
  • Local setup: Node version, install command, how to start the database, seed data
  • A list of environment variables: name, purpose and whether it is secret (never real values)
  • How to run tests, how to deploy and how to roll back

In real projects

In real projects

Product teams break big features down in exactly this way. At the end of a sprint, nobody says "the UI is 80% done"; they demo "users can now edit notes, here is the preview link". When work is split into tickets, each slice gets acceptance criteria, and a ticket closes only when every criterion is backed by a test.

This project also matters for your portfolio. Engineers who hire tend to read the README rather than admire the design: why were decisions made, are there tests, is it deployed, are permissions checked on the server? A live URL, a clean commit history and a README with a "what I would do differently next time" section show that you have handled a real project.

Common mistakes

Common mistakes

  • Starting every feature at once and finishing none end to end. If all the UI is built before the backend begins, the big integration problems all surface at the same moment.
  • Assuming hiding the Edit and Delete buttons from non-owners is enough. A Server Action can be called directly from the browser once its ID is known, so without an ownership check inside the action anyone can edit.
  • Building only the happy path and forgetting empty, loading, error and 404 states. The very first screen a new user sees is the empty state with no notes.
  • Stopping checks of logs, metrics and dependency updates once the app is deployed. Security patches fall behind, and you only learn about slowdowns when users complain.

Mini challenge

Try it yourself: the server side of the "edit note" slice

Write the server-side logic of the "edit note" slice without the UI: a zod schema, a canEdit permission function and an updateNote action. Use a Map instead of a real database, run each acceptance criterion as a case and print the results. In the real project the action reads the session from the cookie itself; here it is passed in as a parameter so it can be tested.

  • Return 401 without a session, and 400 when the trimmed title is under 3 or over 80 characters
  • Return 404 when the note does not exist, and 403 when the user is neither owner nor admin
  • On success save the trimmed title, with isPublic false when the checkbox is absent
  • Check in this order: session, validation, note exists, ownership, then save
edit-note-slice.ts
import { z } from "zod";

type Session = { userId: string; role: "member" | "admin" } | null;
type Note = {
  id: string;
  ownerId: string;
  title: string;
  body: string;
  isPublic: boolean;
};
type ActionResult =
  | { ok: true; note: Note }
  | { ok: false; status: 400 | 401 | 403 | 404; message: string };

// TODO: an in-memory db with findNote(id) and saveNote(note)
// TODO: EditNoteSchema: id, title (trim, 3-80), body (max 5000), isPublic ("on" | "off")

export function canEdit(session: Session, note: Note): boolean {
  // TODO: owner or admin
  return false;
}

export async function updateNote(
  session: Session,
  form: FormData,
): Promise<ActionResult> {
  // TODO: session -> validation -> find note -> canEdit -> save
  return { ok: false, status: 400, message: "not implemented" };
}

// TODO: run five cases (signed out, stranger, short title, missing note, owner edit)
// and print one line per case

Expected: Five lines: "signed out -> 401", "stranger -> 403", "short title -> 400", "missing note -> 404" and "owner edit -> saved \"Mohinga, my way\" (public: false)", each with its message.

Show hint

Object.fromEntries(form) turns FormData into an object you can pass straight to schema.safeParse(). z.string().trim().min(3) measures length after trimming. An unchecked checkbox is missing from the form entirely, so handle isPublic with .default("off").

Show solution
edit-note-slice.ts
import { z } from "zod";

// One vertical slice of Myanmar Notes: "edit a note", without the UI.
type Session = { userId: string; role: "member" | "admin" } | null;
type Note = {
  id: string;
  ownerId: string;
  title: string;
  body: string;
  isPublic: boolean;
};
type ActionResult =
  | { ok: true; note: Note }
  | { ok: false; status: 400 | 401 | 403 | 404; message: string };

// lib/db.ts (an in-memory stand-in for the real database layer)
const notes = new Map<string, Note>([
  ["n1", { id: "n1", ownerId: "u1", title: "Mohinga recipe", body: "", isPublic: true }],
]);
const db = {
  findNote: async (id: string) => notes.get(id) ?? null,
  saveNote: async (note: Note) => {
    notes.set(note.id, note);
    return note;
  },
};

// lib/validation.ts
const EditNoteSchema = z.object({
  id: z.string().min(1),
  title: z.string().trim().min(3, "Title is too short").max(80, "Title is too long"),
  body: z.string().max(5000),
  isPublic: z.enum(["on", "off"]).default("off"),
});

// lib/permissions.ts
export function canEdit(session: Session, note: Note): boolean {
  return !!session && (session.role === "admin" || session.userId === note.ownerId);
}

// app/dashboard/notes/[id]/edit/actions.ts ("use server" in the real file,
// where the session comes from the cookie inside the action, never from the form)
export async function updateNote(
  session: Session,
  form: FormData,
): Promise<ActionResult> {
  if (!session) return { ok: false, status: 401, message: "Please sign in" };

  const parsed = EditNoteSchema.safeParse(Object.fromEntries(form));
  if (!parsed.success) {
    return { ok: false, status: 400, message: parsed.error.issues[0].message };
  }
  const note = await db.findNote(parsed.data.id);
  if (!note) return { ok: false, status: 404, message: "Note not found" };
  if (!canEdit(session, note)) {
    return { ok: false, status: 403, message: "Not your note" };
  }

  const saved = await db.saveNote({
    ...note,
    title: parsed.data.title,
    body: parsed.data.body,
    isPublic: parsed.data.isPublic === "on",
  });
  // The real action would now call revalidatePath("/notes") and redirect.
  return { ok: true, note: saved };
}

// Acceptance checks for the slice
function form(fields: Record<string, string>) {
  const fd = new FormData();
  for (const [key, value] of Object.entries(fields)) fd.set(key, value);
  return fd;
}

async function demo() {
  const owner: Session = { userId: "u1", role: "member" };
  const stranger: Session = { userId: "u2", role: "member" };
  const cases: [string, Session, Record<string, string>][] = [
    ["signed out", null, { id: "n1", title: "Hacked", body: "" }],
    ["stranger", stranger, { id: "n1", title: "Hacked", body: "" }],
    ["short title", owner, { id: "n1", title: "Hi", body: "" }],
    ["missing note", owner, { id: "n9", title: "Shan noodles", body: "" }],
    ["owner edit", owner, { id: "n1", title: "  Mohinga, my way ", body: "Fish broth" }],
  ];
  for (const [name, session, fields] of cases) {
    const result = await updateNote(session, form(fields));
    const detail = result.ok
      ? `saved "${result.note.title}" (public: ${result.note.isPublic})`
      : `${result.status} ${result.message}`;
    console.log(`${name.padEnd(12)} -> ${detail}`);
  }
}

demo();

Quick quiz 1 / 3

What does building Myanmar Notes in vertical slices mean?

Quick quiz 2 / 3

Only a note's owner may edit it. Where must that rule be enforced?

Quick quiz 3 / 3

In the challenge solution, the owner edits with title " Mohinga, my way " and no isPublic checkbox. What gets printed?

What to remember

  • Finish features one at a time as vertical slices, from UI to database to tests, instead of layer by layer
  • Write checkable acceptance criteria for each slice and back every criterion with a test
  • In every Server Action check session, validation, existence and ownership, in that order, on the server
  • Count empty, loading, error and 404 states, plus monitoring after deploy, as part of done
  • Document architecture decisions, setup, env, tests, deployment and rollback in the README

Next.js — Production Checklist — Next.js

Next.js — Production Checklist — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Final Project — Making Myanmar Notes Production-Ready | Thuta Learning