Skip to content
Visual explainer 15h to learn 6 steps

Build a full Next.js app (e.g. habit tracker or recipe manager)

A deployed, typed, tested app with auth, a database, server actions and a strong Lighthouse score.

By Invicly Tech, , in Frontend with React & Next.js. About 12 minutes to read.

Topic 36 of 36

In short

The capstone combines everything into one deployed app: typed pages, auth, a database, server actions, tests and good performance. Build in thin vertical slices so something works end to end early.

Explained simply

This is where everything you learned comes together in one real app that people can open on their phones. It has pages, sign-in, a database, forms that save data, tests and a live URL. It is a big job, so you build it one small, complete feature at a time.

Start by creating the project and deploying it right away, even when it only says Hello. From then on, every change you merge goes live automatically. Deployment problems show up on day one, when they are small, instead of on the last day.

Then add features as vertical slices. For add a habit, you build the form, the server code that saves it, the database table and the list that shows it, and you finish all of that before starting the next feature. After each slice you have a working app that does a little more.

Near the end you add tests for the most important flows, check performance with Lighthouse, and write a README with a live link and screenshots. That README is what employers read first.

Press Play on a diagram to walk through it one step at a time.

LayersThe finished app stack
  1. 1
    UI

    Pages, layouts and Tailwind components

  2. 2
    Server logic

    Server components and server actions with Zod

  3. 3
    Auth

    Sessions protect pages and actions

  4. 4
    Database

    Hosted Postgres or similar, per-user rows

  5. 5
    Quality gate

    Vitest, Playwright and Lighthouse in CI

CycleBuild in vertical slices
  1. 1
    Pick one feature

    e.g. add a habit

  2. 2
    Build UI to DB

    Form, action, table, list

  3. 3
    Test it

    Unit or E2E test for the flow

  4. 4
    Deploy preview

    Check it works on a real URL

  5. Back to step 1
FlowSuggested build order for a habit tracker
  1. 1
    Scaffold and deploy

    Hello page live, CI green

  2. 2
    Auth

    Sign in, sign out, protected area

  3. 3
    Add and list habits

    First slice: form, action, table

  4. 4
    Check-ins and stats

    Second slice with constraints

  5. 5
    Tests and polish

    E2E flows, empty and error states

  6. 6
    Performance and README

    Lighthouse on mobile, screenshots

In depth

Scaffolding and project structure

Run npx create-next-app@latest and accept TypeScript, ESLint, Tailwind CSS, the App Router and the src directory, or pass the matching flags. Keep TypeScript strict. A structure that scales: src/app for routes, src/components for shared UI, src/lib for helpers, src/db for the schema and client, and an actions.ts file next to the routes that use it. The @/ import alias, set up by create-next-app, keeps imports short.

Before building features, push to GitHub, import the repository into Vercel and confirm the production URL works. Add environment variables for each environment, plus a CI workflow running lint, type check and tests on pull requests. Then work on branches with small pull requests, even alone: each one gets a preview URL and a green or red check, and your Git history tells the story of the project.

  • npx create-next-app@latest habit-tracker
  • Deploy on day one; keep main always deployable
  • One pull request per vertical slice

Database persistence done safely

Use a hosted Postgres database (Neon, Supabase and others have free tiers, some available through the Vercel Marketplace) with separate databases or branches for development, preview and production. Define tables in your ORM's schema, generate migration files from it (drizzle-kit generate, or prisma migrate dev), commit them, and apply them to production as a deliberate step, not by hand in a SQL console.

Database code must run only on the server: in Server Components, server actions and route handlers. Add import "server-only" at the top of your db module, so the build fails if a client component ever imports it. Create one database client and reuse it, because each serverless function instance opening many connections can exhaust the database's limit; providers offer pooled connection strings or serverless drivers for this. A seed script that inserts demo data makes local development and E2E tests repeatable.

FlowA schema change from laptop to production
  1. 1
    Edit schema.ts

    Add a column or table

  2. 2
    Generate migration

    A SQL file you can read

  3. 3
    Apply locally

    Run the app and tests

  4. 4
    Pull request

    Migration reviewed with the code

  5. 5
    Apply to production

    Before or with the deploy

Authentication and authorisation

Use a proven auth library or service rather than writing password storage yourself: Auth.js, Better Auth and Clerk are common choices for Next.js. They handle sign-in providers, secure httpOnly session cookies and CSRF protection. Your job is to check the session in the right places.

Authentication asks who you are; authorisation asks what you may do. A check in a layout improves the experience, but it is not enough for security: layouts do not re-run on every navigation, and server actions and route handlers can be called directly. So read the session again in every page that loads private data and in every server action. Then authorise each query by filtering on the owner: where id = habitId and userId = session user id. Forgetting this lets any signed-in user read or delete another user's data just by changing an id in the URL, a bug called an insecure direct object reference.

  • Check the session in each page and each server action
  • Every query: where userId = the session's user id
  • Return notFound() for other users' ids, not their data

Mutations with server actions

A server action is an async function marked with "use server". Pass it to a form's action prop and React submits the form data to it with a POST request, even before JavaScript has loaded. Inside, you authenticate, validate with Zod's safeParse, write to the database, then call revalidatePath("/habits") so the next render shows fresh data, or redirect() to another page.

To show errors and a pending state, wrap the action with React's useActionState in a client component. It returns the latest state the action returned (for example { error: "Name is required" }), a form action to pass to the form, and an isPending flag. Treat every server action as a public API endpoint: anyone can call it with any input, so never trust ids or values coming from the client without checking them. For instant feedback on small toggles, useOptimistic can show the new state before the server confirms.

SequenceSubmitting the add habit form
Browser form
Server action
Database
Page
  1. 1POST form data (name)
    Browser form to Server action: POST form data (name)
  2. 2Check session, safeParse with Zod
    Server action to Server action: Check session, safeParse with Zod
  3. 3INSERT habit with userId
    Server action to Database: INSERT habit with userId
  4. 4revalidatePath('/habits')
    Server action to Page: revalidatePath('/habits')
  5. 5SELECT habits for this user
    Page to Database: SELECT habits for this user
  6. 6New state and updated page
    Server action to Browser form: New state and updated page

Tests, performance and a strong finish

Test where bugs would hurt. Unit test Zod schemas and pure helpers such as streak calculations with Vitest. Component test the interactive client pieces, like the add form's error message, with Testing Library. Write two or three Playwright tests for the critical flows: sign in, add a habit, check in, against a seeded test database. Run them all in CI before merging.

For Lighthouse, test the deployed production URL on mobile. The usual wins: next/image for every image with sizes set, next/font instead of a font stylesheet, keeping client components small so less JavaScript ships, and loading.tsx skeletons with fixed sizes to avoid layout shift. @next/bundle-analyzer shows which packages bloat your client bundle. Fix accessibility issues Lighthouse reports too: labels, contrast and button names. Finally, write the README: live URL, screenshots, features, tech stack, how to run it locally with env vars, and how to run the tests.

  • Vitest: schemas and logic; RTL: client forms; Playwright: 2 or 3 key flows
  • Lighthouse on the production URL, mobile setting
  • README: live link, screenshots, setup, tests

Learn it in 6 short steps

About 2h 30m each. Track them with a timer in your plan.

  1. 1
    Scaffold the app with TypeScript and Tailwind~2h 30m
  2. 2
    Build pages, layouts and components~2h 30m
  3. 3
    Add auth and database persistence~2h 30m
  4. 4
    Implement mutations with server actions~2h 30m
  5. 5
    Write unit and E2E tests~2h 30m
  6. 6
    Deploy and reach a strong Lighthouse score~2h 30m

Key points

  • Deploy on day one, then keep every merge deployable.
  • Finish one feature end to end before starting the next.
  • Cover sign-in and the main task with E2E tests.
  • Aim for strong Lighthouse scores on mobile, not just desktop.
  • Write a README with a live link, screenshots and setup steps.

Key terms

Tap a card to flip it. 0/4 known

Examples

bash
npx create-next-app@latest habit-tracker --ts --tailwind --app --eslint
cd habit-tracker
npm install zod
npm install -D vitest @testing-library/react @playwright/test
npm run dev

Scaffold a typed Next.js app with Tailwind and test tools.

A server action that authenticates, validates and saves

Step 1: "use server" makes every export a server action. Step 2: read the session; return an error state if it is missing. Step 3: validate the form data with Zod and return a friendly message on failure. Step 4: insert with the session's userId, never one from the form. Step 5: revalidatePath refreshes the list. The auth and db imports stand for your own auth library helper and database client.

ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { auth } from '@/auth';
import { db } from '@/db';
import { habits } from '@/db/schema';
export async function createHabit(_prev: { error?: string }, formData: FormData) {
  const session = await auth();
  if (!session?.user?.id) return { error: 'Please sign in again.' };
  const parsed = z.object({ name: z.string().trim().min(1).max(60) }).safeParse({ name: formData.get('name') });
  if (!parsed.success) return { error: 'Name must be 1 to 60 characters.' };
  await db.insert(habits).values({ userId: session.user.id, name: parsed.data.name });
  revalidatePath('/habits');
  return {};
}

The form that calls it, with errors and a pending state

Step 1: the form is a small client component, so the page around it stays on the server. Step 2: useActionState wraps createHabit and starts with an empty state. Step 3: the form's action is the wrapped version, and the button is disabled while pending. Step 4: an error from the action appears in an element with role alert, so screen readers announce it and tests can find it.

tsx
'use client';
import { useActionState } from 'react';
import { createHabit } from './actions';

export function AddHabitForm() {
  const [state, formAction, pending] = useActionState(createHabit, {});
  return (
    <form action={formAction}>
      <label htmlFor="name">Habit name</label>
      <input id="name" name="name" required maxLength={60} />
      <button disabled={pending}>{pending ? 'Adding...' : 'Add habit'}</button>
      {state.error && <p role="alert">{state.error}</p>}
    </form>
  );
}

Quick reference

  • npx create-next-app@latest, push to GitHub, import into Vercel on day one
  • Build vertical slices: form, action, table and list for one feature at a time
  • import "server-only" in database modules to keep them off the client
  • Generate and commit migrations; never edit the production schema by hand
  • Check the session in every private page and every server action
  • Filter every query by the session's userId, never by an id from the client
  • useActionState(action, initial) gives [state, formAction, isPending]
  • revalidatePath("/habits") after a mutation refreshes that page's data

Common mistakes

  • Building all UI first and wiring up data at the end.
  • Leaving deployment until the last day and hitting config surprises.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why is an auth check in the (app) layout alone not enough?

Question 2

2A user changes /habits/42 to /habits/43 in the URL and sees someone else's habit. What is missing?

Question 3

3What should a server action do after inserting a habit so the list shows it?

Question 4

4Which statement about server actions is true?

Question 5

5What does import "server-only" in src/db/index.ts protect against?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Make the /habits page redirect to /login when there is no session.

  2. Exercise 2medium

    Write a deleteHabit(habitId) server action that only deletes the habit if it belongs to the signed-in user.

  3. Exercise 3hard

    Write toggleCheckIn(habitId, day) that removes today's check-in if it exists, otherwise adds it, safely under double clicks and only for the owner.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What should a Next.js portfolio project include?
A live URL, sign-in, a real database, at least one create, update and delete flow, tests in CI, good mobile Lighthouse scores and a README with screenshots. Clean commits and small pull requests are a bonus reviewers notice.
Should I use server actions or API routes?
Use server actions for mutations from your own forms and buttons: less code and built-in progressive enhancement. Use route handlers when something outside your app calls you, such as a webhook or a mobile client.
Which free database works with Vercel?
Hosted Postgres providers such as Neon and Supabase offer free tiers and connect easily, some through the Vercel Marketplace. Check the current limits on their pricing pages before you rely on them.
How long does a capstone like this take?
Plan for about 15 to 25 focused hours for a small app with auth, a database, two features, tests and deployment. Keeping scope small is what makes it finishable.
ShareXLinkedInWhatsApp