The guide already lists events, but none of them has its own page and you can't filter. Both things depend on reading the URL. An event page like /events/riverside-quartet carries a piece of data in the path; a filter like /events?category=theater&page=2 carries it in the search params.

Next.js delivers both as promises, and with Cache Components that has consequences: they're request data, unknown at build time, and they have to be read inside a <Suspense>. In this lesson you'll create the event and venue pages, and turn the URL into the state of the filters and pagination, validating everything that comes from the browser.

  1. Dynamic segments

You're not going to create a folder per event. A dynamic segment is a folder whose name is in square brackets; it accepts any value in that position and delivers it under that name:

File URL Resolved params
events/[slug]/page.tsx /events/jazz-night { slug: 'jazz-night' }
dashboard/events/[id]/edit/page.tsx /dashboard/events/evt-01/edit { id: 'evt-01' }
[city]/[event]/page.tsx /vallenar/cinema { city: 'vallenar', event: 'cinema' }

The [slug] segment accepts just one segment: /events/jazz-night/times doesn't match. And static segments take precedence: if you create events/featured/page.tsx, the URL /events/featured is handled by that file and not by [slug].

Choose a name that describes the value: [slug] for a readable identifier, [id] for an internal one. In AgendaViva the difference is intentional: the public section uses the slug and the dashboard uses the id.

1.1. Catch-all segments

With an ellipsis, the segment captures several path parts and delivers them in an array:

Folder /help /help/bookings /help/bookings/cancel
help/[topic] No match { topic: 'bookings' } No match
help/[...topic] No match { topic: ['bookings'] } { topic: ['bookings', 'cancel'] }
help/[[...topic]] {} (topic is undefined) { topic: ['bookings'] } { topic: ['bookings', 'cancel'] }

A catch-all fits when the depth is decided by the content: a help center with nested sections or the pages of a content management system. The optional variant lets the same file handle the root too. If you know in advance how many levels there are, use regular segments: each one will have its own name, its own layout and its own type. AgendaViva doesn't need any catch-all segment.

  1. params: request data

params is a promise. In a Server Component it's resolved with await:

export default async function EventDetailPage({ params }: PageProps<'/events/[slug]'>) {
  const { slug } = await params
  return <h1>{slug}</h1>
}

PageProps<'/events/[slug]'> is the global type for pages. From the route it knows that params contains slug: string, and writing a different route or reading a different name is a compile-time error. It isn't imported; it's generated by next dev, next build or next typegen.

The type is string and not something more specific because anyone can type anything into the address bar. TypeScript doesn't validate values at runtime: making sure an event with that slug exists is your code's job.

2.1. Why Suspense is needed

The previous example is correct TypeScript and yet, with Cache Components, it produces a prerendering error. At build time, Next.js tries to generate the fixed part of /events/[slug], but it doesn't know which slug will arrive. await params waits for a value that only exists when there's a request, exactly like an uncached query. Since it's in the page, outside any boundary, there's nothing left to prerender.

The solution is the one you already know: move the wait down into a component inside a <Suspense>. To do so, you pass it the promise, unresolved:

export default function EventDetailPage({ params }: PageProps<'/events/[slug]'>) {
  return (
    <Suspense fallback={<p>Loading the event…</p>}>
      <EventContent params={params} />
    </Suspense>
  )
}
sequenceDiagram
    participant C as Build
    participant S as Server
    participant N as Browser
    C->>C: Prerenders the shell with the loading text
    N->>S: GET /events/jazz-night
    S-->>N: Shell
    S->>S: Resolves params and queries the event
    S-->>N: Event page, in the same response

There's another way: declaring the values in advance with generateStaticParams, so that Next.js knows the slugs at build time. It's covered in 05-05, together with the caching that makes it useful.

Layouts inside a dynamic segment also receive params, with the same advice: don't await the promise in the layout itself, pass it down. And a client component can read them with the useParams hook, which we'll see in module 3.

  1. An event's page

We'll separate three responsibilities: the page composes, one component waits for the data and another presents it. The presentational one goes in its own file because it will be reused.

// app/(public)/events/_components/event-details.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { getVenueById } from '@/lib/data/venues'
import { CATEGORY_LABELS, formatDateTime } from '@/lib/format'
import type { AgendaEvent } from '@/lib/types'

export function EventDetails({ event }: { event: AgendaEvent }) {
  return (
    <article>
      <p className="text-teal-800">{CATEGORY_LABELS[event.category]}</p>
      <h1 className="text-3xl font-bold">{event.title}</h1>
      {event.status === 'canceled' && (
        <p className="mt-2 font-semibold text-red-700">This event has been canceled.</p>
      )}
      <p className="mt-2">{formatDateTime(event.startsAt)}</p>
      <Suspense fallback={<p>Loading the venue…</p>}>
        <EventLocation venueId={event.venueId} />
      </Suspense>
      <p className="mt-6">{event.description}</p>
      <p className="mt-4 font-medium">
        {event.spotsLeft > 0
          ? `${event.spotsLeft} of ${event.capacity} spots left`
          : 'Fully booked'}
      </p>
    </article>
  )
}

async function EventLocation({ venueId }: { venueId: string }) {
  const venue = await getVenueById(venueId)
  if (!venue) return null

  return (
    <p>
      <Link href={`/venues/${venue.slug}`} className="underline">
        {venue.name}
      </Link>
      , {venue.address} ({venue.district})
    </p>
  )
}
// app/(public)/events/[slug]/page.tsx
import { Suspense } from 'react'
import { getEventBySlug } from '@/lib/data/events'
import { EventDetails } from '../_components/event-details'

type Props = PageProps<'/events/[slug]'>

export default function EventDetailPage({ params }: Props) {
  return (
    <Suspense fallback={<p>Loading the event…</p>}>
      <EventContent params={params} />
    </Suspense>
  )
}

async function EventContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  const event = await getEventBySlug(slug)

  if (!event) {
    return <p>There's no event at this address.</p>
  }

  return <EventDetails event={event} />
}
  • Pick<Props, 'params'> reuses the page's type for the child. If you rename the folder, TypeScript will flag both places.
  • The venue has its own <Suspense>. It can't be fetched until the event is known, because its venueId is needed. With a separate boundary, the title and date appear without waiting for it. How to shorten these chains is covered in 04-03.
  • null is handled with a placeholder text. The right response is a 404 page, which you'll add in 02-04.

The card can now link to the event page. Change only the title in components/event-card.tsx, and don't forget to import Link:

<h3 className="text-lg font-semibold">
  <Link href={`/events/${event.slug}`}>{event.title}</Link>
</h3>

3.1. A venue's page

// app/(public)/venues/[slug]/page.tsx
import { Suspense } from 'react'
import { EventCard } from '@/components/event-card'
import { listEventsByVenue } from '@/lib/data/events'
import { getVenueBySlug } from '@/lib/data/venues'

type Props = PageProps<'/venues/[slug]'>

export default function VenueDetailPage({ params }: Props) {
  return (
    <Suspense fallback={<p>Loading the venue…</p>}>
      <VenueContent params={params} />
    </Suspense>
  )
}

async function VenueContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  const venue = await getVenueBySlug(slug)

  if (!venue) {
    return <p>There's no venue at this address.</p>
  }

  return (
    <>
      <h1 className="text-3xl font-bold">{venue.name}</h1>
      <p className="mt-2">
        {venue.address} ({venue.district}). Capacity: {venue.capacity} people.
      </p>
      <h2 className="mt-8 mb-4 text-xl font-semibold">Upcoming events</h2>
      <Suspense fallback={<p>Loading events…</p>}>
        <VenueEvents venueId={venue.id} />
      </Suspense>
    </>
  )
}

async function VenueEvents({ venueId }: { venueId: string }) {
  const events = await listEventsByVenue(venueId)
  if (events.length === 0) return <p>No events scheduled.</p>

  return (
    <ul className="grid gap-4 sm:grid-cols-2">
      {events.map((event) => (
        <li key={event.id}>
          <EventCard event={event} />
        </li>
      ))}
    </ul>
  )
}

In venues/page.tsx, import Link and turn the name into a link:

<h2 className="font-semibold">
  <Link href={`/venues/${venue.slug}`}>{venue.name}</Link>
</h2>

  1. searchParams: state in the URL

A page's second prop is searchParams, another promise. It resolves to a plain object, not a URLSearchParams:

URL Resolved value
/events {}
/events?category=theater { category: 'theater' }
/events?category=theater&page=2 { category: 'theater', page: '2' }
/events?category=theater&category=workshop { category: ['theater', 'workshop'] }
/events?q= { q: '' }

Only pages receive it; you already know why layouts don't. Its type is Promise<Record<string, string | string[] | undefined>>, and it's worth taking it literally: a parameter can be missing, come empty or be repeated.

4.1. Why in the URL and not in useState

A list's filters could be kept in a client component's state. In the URL you get more with less code:

  • It can be shared. The link carries the filter with it.
  • It survives a reload and the back and forward buttons.
  • The server reads it, queries only what's needed and returns complete HTML.
  • It works without JavaScript, because they're ordinary links.

The rule: if someone else opening the same address should see the same thing, it goes in the URL. If it's transient (an open menu, half-typed text), it's component state.

To filter data that's already loaded in the browser, there's the useSearchParams hook; you'll see it in 02-03. When the filter affects the query, as it does here, you use the prop.

  1. Validating and normalizing

Search params are user input. Nothing stops anyone from requesting /events?category=dogs&page=-3, and that value will end up in a query. The raw object has to be turned into a reliable EventFilters in a single place.

// lib/filters.ts
import { CATEGORIES, type Category, type EventFilters } from '@/lib/types'

export type RawSearchParams = Record<string, string | string[] | undefined>

const MAX_TEXT_LENGTH = 80

// Keeps the first value, trimmed; an empty value counts as missing
function firstValue(value: string | string[] | undefined): string | undefined {
  const text = Array.isArray(value) ? value[0] : value
  return text?.trim() || undefined
}

function isCategory(value: string | undefined): value is Category {
  return CATEGORIES.some((category) => category === value)
}

export function normalizeFilters(searchParams: RawSearchParams): EventFilters {
  const category = firstValue(searchParams.category)
  const page = Number(firstValue(searchParams.page))

  return {
    category: isCategory(category) ? category : undefined,
    district: firstValue(searchParams.district),
    q: firstValue(searchParams.q)?.slice(0, MAX_TEXT_LENGTH),
    page: Number.isInteger(page) && page > 0 ? page : 1,
  }
}

// The inverse operation: builds the guide's URL from a set of filters
export function createEventsUrl(filters: EventFilters): string {
  const params = new URLSearchParams()
  if (filters.category) params.set('category', filters.category)
  if (filters.district) params.set('district', filters.district)
  if (filters.q) params.set('q', filters.q)
  if (filters.page && filters.page > 1) {
    params.set('page', String(filters.page))
  }

  const query = params.toString()
  return query ? `/events?${query}` : '/events'
}
  • Invalid values are ignored. An unknown category is treated as "no filter" instead of failing. For a search page that's reasonable: an old or badly copied link still shows the guide. In a form that modifies data we'll do the opposite: reject and explain (06-03).
  • isCategory is a type predicate. It compares against CATEGORIES at runtime and, if it matches, TypeScript narrows the type. There's no need for an as Category, which would silence the compiler without checking anything.
  • Number(undefined) is NaN, and Number.isInteger(NaN) is false. The same condition covers a missing value, letters, decimals and, with page > 0, negatives.
  • The maximum page number isn't checked, because it isn't known here. listEvents already clamps the number to the existing range.
  • createEventsUrl leaves out the default values. That way each result has a single address: /events, and not /events?page=1 as well. Besides, URLSearchParams encodes spaces and accented characters.

This module doesn't depend on React or Next.js, so it's easy to test. You'll do that in 10-03.

  1. Filters and pagination

Pagination is a shared component. It knows nothing about events: it receives a function that tells it which address each page points to.

// components/pagination.tsx
import Link from 'next/link'

interface Props {
  page: number
  totalPages: number
  createHref: (page: number) => string
}

export function Pagination({ page, totalPages, createHref }: Props) {
  if (totalPages <= 1) return null

  return (
    <nav aria-label="Pagination" className="mt-8 flex items-center justify-between">
      {page > 1 ? <Link href={createHref(page - 1)}>Previous</Link> : <span />}
      <span>
        Page {page} of {totalPages}
      </span>
      {page < totalPages ? (
        <Link href={createHref(page + 1)}>Next</Link>
      ) : (
        <span />
      )}
    </nav>
  )
}

Passing a function as a prop is possible because both the component passing it and the one receiving it are Server Components. You couldn't hand it to a client component; the reason is in 03-03.

For the filters, links by category are enough for now. In 02-03 you'll replace them with a complete form.

// app/(public)/events/_components/category-filter.tsx
import Link from 'next/link'
import { createEventsUrl } from '@/lib/filters'
import { CATEGORY_LABELS } from '@/lib/format'
import { CATEGORIES, type EventFilters } from '@/lib/types'

export function CategoryFilter({ filters }: { filters: EventFilters }) {
  const options = [undefined, ...CATEGORIES]

  return (
    <ul className="mb-6 flex flex-wrap gap-3">
      {options.map((category) => (
        <li key={category ?? 'all'}>
          <Link
            href={createEventsUrl({ ...filters, category, page: 1 })}
            className={filters.category === category ? 'font-bold underline' : ''}
          >
            {category ? CATEGORY_LABELS[category] : 'All'}
          </Link>
        </li>
      ))}
    </ul>
  )
}

Each link starts from the current filters and changes its own part. Choosing a category takes you back to page 1: staying on page 5 of a result that only has 2 is the classic bug in filtered lists.

The page brings it all together:

// app/(public)/events/page.tsx
import { Suspense } from 'react'
import { Pagination } from '@/components/pagination'
import { EventCard } from '@/components/event-card'
import { listEvents } from '@/lib/data/events'
import { createEventsUrl, normalizeFilters } from '@/lib/filters'
import { CategoryFilter } from './_components/category-filter'

type Props = PageProps<'/events'>

export default function EventsPage({ searchParams }: Props) {
  return (
    <>
      <h1 className="mb-6 text-3xl font-bold">Event guide</h1>
      <Suspense fallback={<p>Loading the guide…</p>}>
        <EventResults searchParams={searchParams} />
      </Suspense>
    </>
  )
}

async function EventResults({ searchParams }: Pick<Props, 'searchParams'>) {
  const filters = normalizeFilters(await searchParams)
  const { events, total, page, totalPages } = await listEvents(filters)

  return (
    <>
      <CategoryFilter filters={filters} />
      <p className="mb-4 text-sm text-slate-600">
        {total === 0 ? 'No events match your search.' : `${total} events`}
      </p>
      <ul className="grid gap-4 sm:grid-cols-2">
        {events.map((event) => (
          <li key={event.id}>
            <EventCard event={event} />
          </li>
        ))}
      </ul>
      <Pagination
        page={page}
        totalPages={totalPages}
        createHref={(pageNumber) => createEventsUrl({ ...filters, page: pageNumber })}
      />
    </>
  )
}

The await searchParams is inside EventResults, under the <Suspense>. The shell of /events (header, heading and footer) is the same for every filter, and whatever depends on them arrives afterwards.

For the pagination we use the page returned by the query, already clamped, and not filters.page. With ?page=99 the last page is shown and the links are consistent with it.

Try these addresses: /events?page=2 (one event), /events?category=theater (two), /events?category=dogs (all of them; the value is ignored) and /events?district=Riverside&q=jazz (one). The build adds two routes, both partial: ◐ /events/[slug] and ◐ /venues/[slug].

Common Mistakes and Tips

  • Reading params.slug without await. It's a promise; TypeScript flags it.
  • Resolving params or searchParams in the page itself, with no <Suspense> or loading.tsx above it. Pass the promise to the component that needs it.
  • Trusting the string type. The compiler doesn't know whether the slug exists or whether the category is valid.
  • Forgetting repeated values. ?category=a&category=b delivers an array, and calling .trim() on it fails at runtime.
  • Using as Category to silence an error. It lets any text through to the query.
  • Keeping the page number when a filter changes.
  • Building the query string by concatenating text. An & or an accented character in the search breaks the URL; use URLSearchParams.
  • Putting sensitive data in the URL. It ends up in the history, in the logs and in shared links.

Exercises

Exercise 1: resolving routes

Given app/blog/new/page.tsx, app/blog/[slug]/page.tsx and app/docs/[[...path]]/page.tsx, state which file handles each URL and with which params: /blog/new, /blog/whats-new, /blog/2028/may, /docs, /docs/guides/getting-started.

Solution

URL File params
/blog/new blog/new/page.tsx {}: the static one takes precedence
/blog/whats-new blog/[slug]/page.tsx { slug: 'whats-new' }
/blog/2028/may None: 404 [slug] accepts a single segment
/docs docs/[[...path]]/page.tsx {}, with path undefined
/docs/guides/getting-started docs/[[...path]]/page.tsx { path: ['guides', 'getting-started'] }

Exercise 2: only with spots left

We want to support ?available=1 to show only events with spots left. Describe the changes to the type, the normalization, the URL building and the query. The parameter should only be enabled by the exact value 1.

Solution

// lib/types.ts, in EventFilters
onlyAvailable?: boolean

// lib/filters.ts, in the object returned by normalizeFilters
onlyAvailable: firstValue(searchParams.available) === '1',

// lib/filters.ts, in createEventsUrl
if (filters.onlyAvailable) params.set('available', '1')

// lib/data/events.ts, inside listEvents' filter
if (filters.onlyAvailable && event.spotsLeft === 0) return false

The page doesn't change: it receives the normalized filter and passes it to the query. That's the benefit of having the conversion in a single module. The category and pagination links also keep the filter, because they start from ...filters. This is a practice exercise: the course continues without this parameter.

Exercise 3: reviewing a venue page

This page fails to build and, even if it built, it would have another flaw. Find them and fix it.

export default async function VenueDetailPage({ params }: PageProps<'/venues/[slug]'>) {
  const { slug } = await params
  const venue = await getVenueBySlug(slug)

  return (
    <Suspense fallback={<p>Loading…</p>}>
      <h1>{venue!.name}</h1>
    </Suspense>
  )
}

Solution

  • The page awaits params and the data outside any boundary. The <Suspense> it returns comes too late: it only covers its children.
  • venue! asserts that it's never null. With a nonexistent slug it will fail at runtime.
type Props = PageProps<'/venues/[slug]'>

export default function VenueDetailPage({ params }: Props) {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <VenueName params={params} />
    </Suspense>
  )
}

async function VenueName({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  const venue = await getVenueBySlug(slug)
  return venue ? <h1>{venue.name}</h1> : <p>Venue not found.</p>
}

Conclusion

Segments in square brackets turn part of the path into data, and search params turn the URL into shareable state. Both arrive as promises because they belong to the request; that's why they're passed unresolved to the component that needs them, under a <Suspense>. And both are user input, so they're normalized in a single module before they reach the data.

You can now browse all of AgendaViva, but only with basic links: nothing tells you which section you're in, and filtering takes a collection of links. In the next lesson, Navigating with Link and useRouter, you'll see what Link does under the hood, highlight the active section and build a search form that navigates without reloading.

© Copyright 2026. All rights reserved