Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 72 ยท Projects

More Projects: Quiz, Weather Dashboard, Expense Tracker, Real-Time Chat

Four more Next.js project plans with runnable logic: a quiz app, a weather dashboard with caching, an expense tracker with Server Actions, and a real-time chat using streaming.

You have followed five bigger projects in this chapter: a blog, a dashboard, a todo app, a shop and an app with accounts. This lesson gives you four more, each smaller and each built around a different Next.js idea. You get a plan, the important files and the core logic, so you can build the rest yourself. That is deliberate: the best way to learn a framework is to build something it was not spelled out for.

Next.js cannot run on this site, so the real routes and components are read-only blocks. The logic that makes each project interesting, such as scoring a quiz, summing expenses, mapping weather data and framing a stream of messages, runs live as Node.js stand-ins. When you build the project locally, you move those functions into lib/ files and call them from your routes. Each project also lists stretch goals.

Four projects, four ideas

Quiz app Routes, search params and scoring.
Weather dashboard External API, caching and revalidation.
Expense tracker Server Actions and totals.
Real-time chat A streaming Route Handler.

Pick one and finish it.

1 / 2

Project 1: a quiz app

Idea. A visitor picks a quiz, answers one question at a time and sees a score at the end. It practices dynamic routes, search params and a small amount of client state.

Plan.

TEXT
app/
  page.tsx                      list of quizzes (Server Component)
  quiz/[slug]/page.tsx          the quiz (loads questions, renders <QuizRunner>)
  quiz/[slug]/result/page.tsx   score page that reads ?score=...
components/
  quiz-runner.tsx               "use client": current question, selected answers
lib/
  quizzes.ts                    data and the scoring function

The questions live in a plain TypeScript file at first. Later you can move them to a database (Databases in Next.js). The page loads them on the server, so the answers never need to be fetched separately:

TSX
// app/quiz/[slug]/page.tsx (read-only)
import { notFound } from "next/navigation";
import { getQuiz } from "@/lib/quizzes";
import { QuizRunner } from "@/components/quiz-runner";

export default async function QuizPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const quiz = getQuiz(slug);
  if (!quiz) notFound();

  // Send the questions but not the correct answers to the browser.
  const publicQuestions = quiz.questions.map(({ id, text, options }) => ({ id, text, options }));
  return <QuizRunner slug={slug} questions={publicQuestions} />;
}

There is a real design question hidden here: if the answers are sent to the browser, a visitor can read them in the network tab. For a casual quiz that is acceptable, but a graded test should check answers in a Server Action that receives the choices and returns only the score. The stand-in below does exactly that: the answer key stays inside the scoring function, and the caller only gets numbers and per-question feedback.

Node.js Score a quiz on the server side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stretch goals. Add a timer, shuffle the options, store each attempt for signed-in users (Authentication Basics), and show a leaderboard that is revalidated every minute.

Project 2: a weather dashboard

Idea. Type a city, see the current temperature and a short forecast. It practices fetching from an external API, caching, and handling errors and missing data. You need a free weather API; most require a key, which belongs in .env.local without the NEXT_PUBLIC_ prefix (Environment Variables).

Plan. The city lives in the URL (/weather?city=Berlin), so a result can be bookmarked and shared, as in Search Params and Hooks. The page is a Server Component that calls the API itself. The key never reaches the browser, and the response can be cached for ten minutes:

TSX
// app/weather/page.tsx (read-only)
import { notFound } from "next/navigation";
import { toForecast } from "@/lib/weather";

export default async function WeatherPage({ searchParams }: { searchParams: Promise<{ city?: string }> }) {
  const { city } = await searchParams;
  if (!city) return <p>Enter a city to begin.</p>;

  const res = await fetch(
    `https://api.example-weather.test/v1/forecast?q=${encodeURIComponent(city)}&key=${process.env.WEATHER_KEY}`,
    { next: { revalidate: 600 } } // reuse the answer for ten minutes
  );
  if (res.status === 404) notFound();
  if (!res.ok) throw new Error("Weather service failed"); // shown by error.tsx

  const forecast = toForecast(await res.json());
  return (
    <section>
      <h1>{forecast.city}</h1>
      <p>{forecast.now} now, {forecast.summary}</p>
    </section>
  );
}

Notice encodeURIComponent on the city, because user input must never be placed into a URL as it is, and the revalidation option from Revalidation. With the default dynamic behavior of a page that reads searchParams, each city is rendered per request, but the underlying fetch is shared for ten minutes between visitors.

Real APIs answer in their own shape, in their own units. Put the translation in one function so that the rest of the app sees one clean shape, and so that you can test it without a network. The stand-in maps a made-up API response, converting Kelvin to Celsius and picking a one-line summary:

Node.js Map an API response to the shape your UI wants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stretch goals. Save recent cities in a cookie, show a loading skeleton with loading.tsx while the forecast loads, add a generateMetadata that sets the title to the city name, and let users pick ยฐC or ยฐF with a preference stored in a cookie.

Project 3: an expense tracker

Idea. Add expenses with an amount and a category, list them, and see totals by category and by month. It practices forms, Server Actions, validation and revalidation, and it is the best project here for learning how data flows through the App Router.

Plan. A database table with id, description, amountCents, category and date. Store money as integer cents, never as a floating-point number, because 0.1 + 0.2 is not exactly 0.3 in binary arithmetic. The form posts to a Server Action that validates the input with a schema (Validation with Zod), inserts a row and revalidates the list:

TSX
// app/expenses/actions.ts (read-only)
"use server";

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { db } from "@/lib/db";

const schema = z.object({
  description: z.string().min(1).max(80),
  amount: z.coerce.number().positive().max(1_000_000),
  category: z.enum(["food", "rent", "travel", "fun"]),
});

export async function addExpense(_prev: unknown, formData: FormData) {
  const parsed = schema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors };

  await db.expense.create({
    data: { ...parsed.data, amountCents: Math.round(parsed.data.amount * 100) },
  });
  revalidatePath("/expenses");
  return { errors: {} };
}

The summary logic is plain data work, so keep it in a function you can test (Testing Next.js Apps). The stand-in groups expenses by category and month, works in cents and formats the money only at the end:

Node.js Totals by category and by month, in cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stretch goals. Filter by month with a search param, delete and edit expenses with optimistic updates (Optimistic Updates), export a CSV from a Route Handler, and add a budget per category that warns when exceeded.

Project 4: a real-time chat

Idea. Several visitors see each other's messages without reloading the page. Real-time features are where a serverless-style framework meets its limits, so this project is mostly about choosing the right transport.

Options. (1) Polling: the client asks for new messages every few seconds. Simple, works everywhere, wastes requests. (2) Server-Sent Events (SSE): one long-lived HTTP response through which the server pushes messages. One direction only (server to client), simple, works through most proxies. Messages are sent with ordinary POST requests. (3) WebSockets: two-way, best latency, but needs a server that holds connections open, which does not fit every Next.js hosting platform. For many apps a managed real-time service (such as Pusher or Ably) or a separate WebSocket server is the pragmatic choice.

Here we build SSE, because it works with a plain Route Handler. A Route Handler returns a ReadableStream with the content type text/event-stream (Route Handlers covers streaming):

TypeScript
// app/api/chat/stream/route.ts (read-only)
import { subscribe } from "@/lib/chat-bus";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  const encoder = new TextEncoder();
  const stream = new ReadableStream({
    start(controller) {
      const unsubscribe = subscribe((message) => {
        controller.enqueue(encoder.encode(`data: ${JSON.stringify(message)}\n\n`));
      });
      request.signal.addEventListener("abort", () => {
        unsubscribe();
        controller.close();
      });
    },
  });

  return new Response(stream, {
    headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" },
  });
}
TSX
// components/chat.tsx (read-only)
"use client";
import { useEffect, useState } from "react";

export function Chat() {
  const [messages, setMessages] = useState<{ user: string; text: string }[]>([]);

  useEffect(() => {
    const source = new EventSource("/api/chat/stream");
    source.onmessage = (event) => setMessages((all) => [...all, JSON.parse(event.data)]);
    return () => source.close(); // always clean up
  }, []);

  return <ul>{messages.map((m, i) => <li key={i}><b>{m.user}:</b> {m.text}</li>)}</ul>;
}

The in-memory chat-bus works only while all requests reach the same server process. On a platform that runs many instances, a message posted on one would never reach a listener on another. A production version publishes through Redis or a managed service. Also, serverless platforms limit how long a response may stay open, so the browser's EventSource will reconnect automatically; design for that.

The stand-in below builds the heart of it: a message bus, a function that turns messages into SSE frames, a stream that carries them, and a client that parses the frames back.

Node.js A message bus, SSE frames and a stream reader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stretch goals. Add rooms with the room name in the URL, persist the last 50 messages in a database and load them in a Server Component, show who is typing, escape and length-limit every message (never trust the text, see Authorization and Data Security), and rate-limit the POST route.

How to work on a project

  1. Write the list of pages first. Decide what is a Server Component and where the "use client" boundary goes (Server and Client Composition).
  2. Build the data layer as plain functions, test it, and only then connect pages.
  3. Make it work, then make it correct: validate input, handle missing data and errors with not-found.tsx and error.tsx (Loading, Error and Not Found).
  4. Deploy it (Building and Deploying). A project that is online teaches more than one that is not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a graded quiz check answers in a Server Action instead of in the browser?

    Anything sent to the browser can be inspected. Keeping the key in server-only scoring code means the client only learns the result.
  2. 2. Why store money as integer cents?

    Binary floating point introduces small rounding errors. Cents avoid them, and you format to dollars only when displaying.
  3. 3. What is the main limit of an in-memory chat bus in production?

    Each process has its own memory. Use Redis, a managed real-time service or a dedicated server to share messages between instances.
  4. 4. In the weather project, why does the page call the weather API on the server?

    Server-side fetching keeps the key out of the browser and lets next.revalidate reuse one response for many visitors.

Summary

  • A quiz teaches dynamic routes and keeping the answer key on the server; score in a Server Action.
  • A weather dashboard teaches external APIs: keep the key server-side, encode user input, cache with revalidate, and map the response in one function.
  • An expense tracker teaches forms, Server Actions, Zod validation and revalidation; store money as integer cents.
  • A chat teaches streaming: SSE through a Route Handler is simple, but in-memory buses only work inside one process.
  • For every project, keep logic in plain functions, handle errors, and deploy it.

Next: Exercises