You already know what Next.js is, you've created the agendaviva project and you know what each folder means. This lesson introduces the product you'll build throughout the course and writes its first version: the domain types, an in-memory data module, the root layout with a header and footer, and a home page with the upcoming events.
There isn't much code, but its decisions carry weight: the signatures of the data functions won't change when, in module 4, the in-memory data is replaced with PostgreSQL. Take your time writing it, because every later lesson builds on it.
- The product
AgendaViva is the online cultural events guide for Vallenar del Río, a fictional city. It brings together concerts, plays, exhibitions and workshops. The activities are free but have limited places: there are no payments, but there are bookings.
| Role | What they can do |
|---|---|
| Visitor without an account | Browse the guide, filter by category, district or text, and view event pages |
| Visitor with an account | Also book spots and view or cancel their bookings |
| Organizer | Also create and edit their events in a dashboard and submit them for review |
| Administrator | Review submitted events and publish them |
An event's lifecycle is: an organizer creates it as a draft, submits it for review and the administrators publish it. A published event can be canceled, but it doesn't disappear, because there may be bookings and links pointing to it.
stateDiagram-v2
[*] --> draft
draft --> review: the organizer submits
review --> draft: sent back for changes
review --> published: the administrators approve
published --> canceled: it is called off
canceled --> [*]
1.1. Route map
| Route | Content | Access |
|---|---|---|
/ |
Home page with the upcoming events | Public |
/events |
Event guide with filters: ?category=&district=&q=&page= |
Public |
/events/[slug] |
An event's page and booking | Public; booking requires an account |
/venues |
List of venues | Public |
/venues/[slug] |
A venue and its events | Public |
/sign-in, /sign-up |
Sign-in and sign-up | Public |
/my-bookings |
The user's bookings | With an account |
/dashboard |
Organizer overview | Organizer |
/dashboard/events |
Their events | Organizer |
/dashboard/events/new |
Create an event | Organizer |
/dashboard/events/[id]/edit |
Edit an event | Owning organizer |
/admin |
Review and publishing | Administrator |
Public routes identify events by their slug, which is readable and shareable; dashboard routes use their id, because a draft's title may change.
- The domain model
Create lib/types.ts. It's a file with no dependencies: any part of the project, on the server or in the browser, can import it.
// lib/types.ts
export const CATEGORIES = ['concert', 'theater', 'exhibition', 'workshop'] as const
export type Category = (typeof CATEGORIES)[number]
export type EventStatus = 'draft' | 'review' | 'published' | 'canceled'
export type Role = 'visitor' | 'organizer' | 'admin'
export interface Venue {
id: string
slug: string
name: string
district: string
address: string
capacity: number
}
export interface AgendaEvent {
id: string
slug: string
title: string
summary: string
description: string
category: Category
startsAt: Date
endsAt: Date
venueId: string
organizerId: string
capacity: number
spotsLeft: number
image: string | null
status: EventStatus
}
export interface Booking {
id: string
eventId: string
userId: string
spots: number
createdAt: Date
}
export interface User {
id: string
name: string
email: string
role: Role
}
export interface EventFilters {
category?: Category
district?: string
q?: string
page?: number
}
export interface EventPage {
events: AgendaEvent[]
total: number
page: number
totalPages: number
}The decisions worth understanding:
CATEGORIESis a value andCategorya type derived from it. The list exists at runtime, so it can be used to render the filters and validate the URL; the type stays in sync on its own.- Dates are
Dateobjects, not strings. Server Components can pass aDateto a Client Component without converting it, and the ORM returnsDatetoo. imageacceptsnull. An event may not have a poster. Images arrive in 06-05 and 09-02.- The
idvalues are strings. Today they're hard-coded; in the database they'll be generated identifiers, and nothing will depend on their format.
- The in-memory data module
Until lesson 04-02 the data will live in an array. So that the later change doesn't force us to touch the pages, two things are kept apart: lib/data/memory.ts, which will go away, and the public functions in lib/data/events.ts and lib/data/venues.ts, which will keep their names, parameters and return types.
3.1. The data and the simulated query
// lib/data/memory.ts — will be replaced by the database in 04-02
import { io } from 'next/cache'
import type { AgendaEvent, Venue } from '@/lib/types'
// Behaves like a real query: asynchronous, with a delay and no cache
export async function simulateQuery(milliseconds = 300): Promise<void> {
await io()
await new Promise<void>((resolve) => setTimeout(resolve, milliseconds))
}
export const venues: Venue[] = [
{ id: 'ven-01', slug: 'mill-theater', name: 'Mill Theater',
district: 'Downtown', address: '3 Mill Square', capacity: 320 },
{ id: 'ven-02', slug: 'the-factory', name: 'The Factory',
district: 'Riverside', address: '18 Loom Street', capacity: 180 },
{ id: 'ven-03', slug: 'north-community-center', name: 'North Community Center',
district: 'Northside', address: '40 Linden Avenue', capacity: 60 },
]
type EventData = Omit<
AgendaEvent,
'startsAt' | 'endsAt' | 'organizerId' | 'image' | 'status' | 'description'
> &
Partial<Pick<AgendaEvent, 'organizerId' | 'image' | 'status'>> & {
startsAt: string
minutes: number
}
function createEvent({ startsAt, minutes, ...data }: EventData): AgendaEvent {
const start = new Date(startsAt)
return {
organizerId: 'usr-02',
image: null,
status: 'published',
description: `${data.summary} Free admission while capacity lasts.`,
...data,
startsAt: start,
endsAt: new Date(start.getTime() + minutes * 60_000),
}
}
export const events: AgendaEvent[] = [
createEvent({
id: 'evt-01', slug: 'riverside-quartet', title: 'Riverside Quartet', category: 'concert',
summary: 'Chamber music with repertoire works and a local premiere.',
startsAt: '2028-05-12T20:30:00+02:00', minutes: 90, venueId: 'ven-01', capacity: 320, spotsLeft: 84,
}),
createEvent({
id: 'evt-02', slug: 'pottery-workshop', title: 'Pottery workshop', category: 'workshop',
summary: 'An introduction to hand-building for adults.',
startsAt: '2028-05-13T11:00:00+02:00', minutes: 120, venueId: 'ven-03', capacity: 15, spotsLeft: 4,
}),
createEvent({
id: 'evt-03', slug: 'the-house-across-the-street', title: 'The House Across the Street', category: 'theater',
summary: 'Two neighbors, a courtyard and thirty years of conversations.',
startsAt: '2028-05-19T21:00:00+02:00', minutes: 90, venueId: 'ven-01', capacity: 320, spotsLeft: 0,
}),
createEvent({
id: 'evt-04', slug: 'paper-and-ink', title: 'Paper and Ink', category: 'exhibition',
summary: 'Prints and posters from the neighborhood print shops.',
startsAt: '2028-05-20T18:00:00+02:00', minutes: 90, venueId: 'ven-02', capacity: 80, spotsLeft: 62,
}),
createEvent({
id: 'evt-05', slug: 'jazz-night', title: 'Jazz Night', category: 'concert',
summary: 'Three local bands on a single evening.',
startsAt: '2028-05-26T21:30:00+02:00', minutes: 150, venueId: 'ven-02', capacity: 180, spotsLeft: 35,
}),
createEvent({
id: 'evt-06', slug: 'smartphone-photography', title: 'Smartphone photography', category: 'workshop',
summary: 'Light, framing and basic editing without a professional camera.',
startsAt: '2028-06-03T10:00:00+02:00', minutes: 150, venueId: 'ven-03', capacity: 20, spotsLeft: 11,
}),
createEvent({
id: 'evt-07', slug: 'river-tales', title: 'River Tales', category: 'theater',
summary: 'Oral storytelling for families.',
startsAt: '2028-06-10T12:00:00+02:00', minutes: 60, venueId: 'ven-03', capacity: 60, spotsLeft: 27,
}),
createEvent({
id: 'evt-08', slug: 'summer-choir', title: 'Summer Choir', category: 'concert',
summary: 'End-of-season concert by the municipal choir.',
startsAt: '2028-06-17T20:00:00+02:00', minutes: 75, organizerId: 'usr-03', status: 'review', venueId: 'ven-01', capacity: 320, spotsLeft: 320,
}),
]createEvent only saves repetition: it computes the end time from the duration and fills in the common fields. There are seven published events and one under review, which the public must not see. The dates are fixed and far in the future on purpose, so that the results don't depend on the day you follow the course.
The important function is simulateQuery. An in-memory array would respond instantly, and that would hide exactly what the course teaches: waiting. It combines two things:
await io(), fromnext/cache, tells Next.js that what follows is an input/output operation. When prerendering, the framework stops there and leaves that content for request time; during a real request, it resolves immediately. It's the same treatment a database query gets.- The 300 ms pause mimics latency and lets you see the loading states.
According to the documentation, module imports and pure computations complete during prerendering. Without io() or the pause, the home page could be frozen at build time, and the difference would show up all at once when PostgreSQL is connected. This way it behaves the same from day one.
3.2. The query functions
// lib/data/events.ts
import { events, venues, simulateQuery } from '@/lib/data/memory'
import type { AgendaEvent, EventFilters, EventPage } from '@/lib/types'
export const EVENTS_PER_PAGE = 6
function publishedByDate(): AgendaEvent[] {
return events
.filter((event) => event.status === 'published')
.sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime())
}
export async function listUpcomingEvents(limit = 6): Promise<AgendaEvent[]> {
await simulateQuery()
return publishedByDate().slice(0, limit)
}
export async function listEvents(
filters: EventFilters = {},
): Promise<EventPage> {
await simulateQuery()
const text = filters.q?.trim().toLocaleLowerCase('en')
const matches = publishedByDate().filter((event) => {
const venue = venues.find(({ id }) => id === event.venueId)
if (filters.category && event.category !== filters.category) return false
if (filters.district && venue?.district !== filters.district) return false
if (text && !event.title.toLocaleLowerCase('en').includes(text)) return false
return true
})
const totalPages = Math.max(1, Math.ceil(matches.length / EVENTS_PER_PAGE))
const page = Math.min(Math.max(1, filters.page ?? 1), totalPages)
const offset = (page - 1) * EVENTS_PER_PAGE
return {
events: matches.slice(offset, offset + EVENTS_PER_PAGE),
total: matches.length,
page,
totalPages,
}
}
export async function getEventBySlug(slug: string): Promise<AgendaEvent | null> {
await simulateQuery()
const event = events.find((candidate) => candidate.slug === slug)
const visible = event?.status === 'published' || event?.status === 'canceled'
return event && visible ? event : null
}
export async function listEventsByVenue(venueId: string): Promise<AgendaEvent[]> {
await simulateQuery()
return publishedByDate().filter((event) => event.venueId === venueId)
}// lib/data/venues.ts
import { venues, simulateQuery } from '@/lib/data/memory'
import type { Venue } from '@/lib/types'
export async function listVenues(): Promise<Venue[]> {
await simulateQuery()
return [...venues].sort((a, b) => a.name.localeCompare(b.name, 'en'))
}
export async function getVenueBySlug(slug: string): Promise<Venue | null> {
await simulateQuery()
return venues.find((venue) => venue.slug === slug) ?? null
}
export async function getVenueById(id: string): Promise<Venue | null> {
await simulateQuery()
return venues.find((venue) => venue.id === id) ?? null
}
export async function listDistricts(): Promise<string[]> {
await simulateQuery()
const districts = new Set(venues.map((venue) => venue.district))
return [...districts].sort((a, b) => a.localeCompare(b, 'en'))
}- They're all
asyncand return aPromise, even though today they don't need to. That's what keeps the signature stable. - "Doesn't exist" is
null, not an exception. The caller decides whether that's a 404 (lesson 02-04). - Listings only return published events, and the event page also accepts canceled ones so that their links keep working. The rule lives next to the data, and no page can forget it. The dashboard functions, which will see drafts, will be written separately.
filtercreates a new array, so thesortthat follows doesn't alter the original.listVenueshas nofilter, which is why it copies the array before sorting.listUpcomingEventsdoesn't compare against the current date. Reading the clock during prerendering is an error with Cache Components unless you say how to handle it; we'll add it when we study module 5.
- Date formatting and labels
// lib/format.ts
import type { Category } from '@/lib/types'
export const CATEGORY_LABELS: Record<Category, string> = {
concert: 'Concert',
theater: 'Theater',
exhibition: 'Exhibition',
workshop: 'Workshop',
}
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
day: 'numeric',
month: 'long',
hour: '2-digit',
minute: '2-digit',
timeZone: 'Europe/Madrid',
})
export function formatDateTime(date: Date): string {
return dateTimeFormat.format(date)
}The time zone is explicit. Without it, the zone of the machine running the code would be used: UTC on many servers, the user's own in the browser. The same event would show different times and, in a hydrated component, would trigger a hydration error.
Also create lib/site.ts with export const SITE_NAME = 'AgendaViva' if you didn't do so in the exercise in lesson 01-02.
- The root layout, header and footer
// components/header.tsx
import Link from 'next/link'
import { SITE_NAME } from '@/lib/site'
export function Header() {
return (
<header className="border-b border-slate-200 bg-white">
<div className="mx-auto flex max-w-5xl items-center justify-between px-4 py-4">
<Link href="/" className="text-xl font-bold text-teal-800">
{SITE_NAME}
</Link>
<nav aria-label="Main" className="flex gap-6">
<Link href="/events">Events</Link>
<Link href="/venues">Venues</Link>
</nav>
</div>
</header>
)
}// components/footer.tsx
import { SITE_NAME } from '@/lib/site'
export function Footer() {
return (
<footer className="border-t border-slate-200 py-6 text-center text-sm text-slate-600">
{SITE_NAME}, the cultural events guide for Vallenar del Río
</footer>
)
}// app/layout.tsx
import type { Metadata } from 'next'
import { Header } from '@/components/header'
import { Footer } from '@/components/footer'
import { SITE_NAME } from '@/lib/site'
import './globals.css'
export const metadata: Metadata = {
title: SITE_NAME,
description: 'Concerts, theater, exhibitions and workshops in Vallenar del Río',
}
export default function RootLayout({ children }: LayoutProps<'/'>) {
return (
<html lang="en">
<body className="flex min-h-screen flex-col bg-slate-50 text-slate-900">
<Header />
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-8">{children}</main>
<Footer />
</body>
</html>
)
}Link replaces <a> for internal navigation and is covered in 02-03. The links to /events and /venues will return a 404 until module 2.
We've removed the generator's sample fonts, which are covered in 09-02. Trim app/globals.css down to a single line so you don't carry over its variables:
- The first home page
// components/event-card.tsx
import { CATEGORY_LABELS, formatDateTime } from '@/lib/format'
import type { AgendaEvent } from '@/lib/types'
export function EventCard({ event }: { event: AgendaEvent }) {
return (
<article className="rounded-lg border border-slate-200 bg-white p-4">
<p className="text-sm text-teal-800">{CATEGORY_LABELS[event.category]}</p>
<h3 className="text-lg font-semibold">{event.title}</h3>
<p className="text-sm text-slate-600">{formatDateTime(event.startsAt)}</p>
<p className="mt-2">{event.summary}</p>
<p className="mt-2 text-sm">
{event.spotsLeft > 0 ? `${event.spotsLeft} spots left` : 'Fully booked'}
</p>
</article>
)
}// app/page.tsx
import { Suspense } from 'react'
import { EventCard } from '@/components/event-card'
import { listUpcomingEvents } from '@/lib/data/events'
export default function HomePage() {
return (
<>
<h1 className="text-3xl font-bold">What's on in Vallenar del Río</h1>
<h2 className="mt-8 mb-4 text-xl font-semibold">Upcoming events</h2>
<Suspense fallback={<p>Loading upcoming events…</p>}>
<UpcomingEvents />
</Suspense>
</>
)
}
async function UpcomingEvents() {
const events = await listUpcomingEvents()
return (
<ul className="grid gap-4 sm:grid-cols-2">
{events.map((event) => (
<li key={event.id}>
<EventCard event={event} />
</li>
))}
</ul>
)
}6.1. Why the Suspense is there
HomePage doesn't wait for anything; the wait is inside UpcomingEvents. At build time, Next.js prerenders the shell: header, headings, loading text and footer. When it reaches UpcomingEvents it finds uncached data, leaves a hole and resolves it on every request. The visitor gets the shell immediately and the list afterwards, in the same response.
Without that boundary there would be no way to separate what's known in advance from what isn't, and the whole page would have to wait. That's why Next.js treats it as an error. If you remove the <Suspense>, the development overlay and the build warn you with a message like this one (abridged):
Route "/": Next.js encountered uncached data during prerendering.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] Cache the data access with `"use cache"`
- [block] Set `export const instant = false` to allow a blocking routeFor now we'll always take the first way out. Why streaming works is explained in 04-04, and when caching is worthwhile, in module 5.
6.2. Checking the result
With npm run dev, reload the home page: you'll briefly see the loading text and then six cards. Then run npm run lint, npm run typecheck and npm run build. The build table will show the home page as partially prerendered:
- Technical decisions and course plan
| Decision | Reason |
|---|---|
Data only through lib/data/ |
Change the source without touching the interface |
| Server Components by default | Less JavaScript and direct access to data |
| PostgreSQL with Drizzle ORM from 04-02 | A relational database with typed queries |
| Zod from 06-03 | Validate on the server everything the browser sends |
| Our own cookie-based sessions in 08-01 | Understand the mechanism before handing it off to a library |
| Tailwind with no frills | Keep the focus on Next.js; styling belongs to 09-01 |
| Module | What AgendaViva gains |
|---|---|
| 2 | Public routes, filters in the URL, navigation, loading and errors, event page modal |
| 3 | A deliberate split between server and browser |
| 4 | Database, parallel loading and streaming |
| 5 | Static shells and caching with revalidation |
| 6 | Bookings, creating and editing events, poster uploads |
| 7 | Public API, redirects, webhooks and post-response tasks |
| 8 | Accounts, roles and hardening |
| 9 and 10 | Look and feel, SEO, languages, performance, testing and observability |
| 11 | Complete final project and deployment |
Common Mistakes and Tips
- Putting the
awaitin the page itself, outside any<Suspense>. The wait must be in a component placed inside the boundary; a<Suspense>written in the JSX of the component that's waiting doesn't cover it. - Writing
new Date().getFullYear()in the footer. It's the most common slip: with Cache Components, reading the clock during prerendering is an error.new Date('2028-05-12…'), with an argument, doesn't read the clock and is fine. - Importing
memory.tsfrom a page. It breaks the isolation, and the page will have to be rewritten in 04-02. - Formatting dates without
timeZone. It works on your machine and shows a different time on the server. - Sorting the shared array.
sortmodifies the original, and the change affects every request, because the module is shared between them.
Exercises
Exercise 1: a venues block on the home page
Add a "Venues" section to the home page with each venue's name and district. It must load independently of the events.
Solution
// app/page.tsx (additions)
import { listVenues } from '@/lib/data/venues'
async function VenueList() {
const venues = await listVenues()
return (
<ul>
{venues.map((venue) => (
<li key={venue.id}>
{venue.name} ({venue.district})
</li>
))}
</ul>
)
}
// Inside HomePage's JSX, after the events:
<h2 className="mt-8 mb-4 text-xl font-semibold">Venues</h2>
<Suspense fallback={<p>Loading venues…</p>}>
<VenueList />
</Suspense>Each block has its own <Suspense>, so neither waits for the other: they appear as they resolve. With a single boundary around both, the fallback would stay until both had finished. This is a practice exercise: the course continues with the home page from the lesson, without this block.
Exercise 2: predicting the behavior
Someone replaces the home page with this version. What will happen when you visit it in development and when you build? Fix it.
export default async function HomePage() {
const events = await listUpcomingEvents()
return (
<Suspense fallback={<p>Loading…</p>}>
<p>{events.length} events</p>
</Suspense>
)
}Solution
In development the overlay warns about uncached data during prerendering, and npm run build fails. The <Suspense> doesn't help: by the time React reaches it, the page has already waited. A boundary only covers the waits of the components below it. The read has to move into a child component:
async function EventCount() {
const events = await listUpcomingEvents()
return <p>{events.length} events</p>
}
export default function HomePage() {
return (
<Suspense fallback={<p>Loading…</p>}>
<EventCount />
</Suspense>
)
}Conclusion
AgendaViva now has a typed domain model, a data module that behaves like a database and whose signatures will stay the same, a root layout and a home page that Next.js partially prerenders and completes on every request. You also have the route map and the rule that will accompany all the code in the course: uncached data waits go inside a <Suspense>.
For now only the / route exists, and the header links don't lead anywhere. In module 2 you'll give them somewhere to go. We start with Pages, Layouts and Route Groups, where you'll create the public pages and separate the public section from the dashboard with route groups and nested layouts.
