The previous module ended with a distinction: Server Actions are the doors people walk through from our pages, and what's left are the ones other programs use. You've already written three without stopping to look at them: the spots polled by LiveAvailability, the search suggestions and the images. Each one is a Route Handler, a route.ts file that receives an HTTP request and returns an HTTP response, with no interface in between.
When you write one, you work directly with the protocol: methods, status codes, headers and bodies. In a page, Next.js decides all of that; here you do, and whoever calls isn't going to interpret a nice message, but a number and some JSON. In this lesson you'll put some order into what you were already using, and you'll build a public events API for third parties and a calendar download.
- The route.ts file
A route.ts publishes an endpoint at its folder's URL. It exports one function for each method it supports: GET, HEAD, POST, PUT, PATCH, DELETE or OPTIONS.
// Example only
import type { NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
return Response.json({ path: request.nextUrl.pathname })
}There are only a few rules:
- It can live in any folder in
app/.api/is a habit, not a router convention. The images live inapp/images/and work just the same. - It can't sit next to a
page.tsxin the same segment. Each one handles every method on its route, and having both is a build error. - It doesn't take part in layouts or in client-side navigation.
loading.tsx,error.tsxandnot-found.tsxdon't apply either. - A method that isn't exported returns
405 Method Not Allowed. There are two exceptions: if you don't writeOPTIONS, Next.js responds with theAllowheader listing the ones that exist; and if there's aGETbut noHEAD, it handlesHEADwith it, without sending the body. - It's public. Anyone can call it with
curl, even if only your page uses it.
1.1. Request, Response and their extensions
The function receives a Request and returns a Response, the same classes fetch uses in the browser. Next.js also provides an extended version with a few conveniences:
| Need | Web API | Next.js extension |
|---|---|---|
| URL parameters | new URL(request.url).searchParams |
request.nextUrl.searchParams |
| Reading a cookie | Parsing the Cookie header |
request.cookies.get('name') |
| Returning JSON | Response.json(data, { status }) |
NextResponse.json(data, { status }) |
| Writing a cookie | Set-Cookie header by hand |
response.cookies.set(…) |
| Redirecting | Response.redirect(url, 307) |
NextResponse.redirect(url) |
The course's rule is to use the standard class for as long as it's enough. NextRequest pays off as soon as you read parameters; NextResponse, when you need to write cookies or in proxy.ts. You can also call cookies() and headers() from next/headers, just as in a page; and here redirect and notFound do produce a real 307 and 404, because the response hasn't started.
The second argument carries params, which is a promise. RouteContext<'/api/events/[slug]/availability'> types it from the route; it's global and generated by next dev, next build or next typegen.
- The public API's contract
Other websites in the city want to show the guide. This is what we'll offer them:
| Endpoint | Returns |
|---|---|
GET /api/v1/filters |
Available categories and districts |
GET /api/v1/events?category=&district=&page= |
Current events, paginated |
GET /api/v1/events/{slug} |
One event |
POST /api/v1/availability |
Exact spots for several events |
The version goes in the path for a practical reason. Your interface and your server are deployed together, and you can change both at once; a third party can't. As long as v1 exists, its fields don't change name or meaning. Adding one is compatible; removing it or reinterpreting it requires a v2. Internal routes, like the spots or the suggestions, are outside that commitment, and that's why they have no version.
The most important decision follows from this: what goes out isn't a database row. If AgendaEvent were returned as is, organizerId would be published, and any new column would leak out the day it's created.
// lib/api/events.ts
import 'server-only'
import { imageUrl } from '@/lib/images'
import { SITE_URL } from '@/lib/site'
import type { EventWithVenue } from '@/lib/types'
function absolute(path: string): string {
return new URL(path, SITE_URL).href
}
// The shape third parties see in v1: don't change it, extend it
export function toPublicEvent(event: EventWithVenue) {
return {
slug: event.slug,
url: absolute(`/events/${event.slug}`),
title: event.title,
summary: event.summary,
category: event.category,
canceled: event.status === 'canceled',
startsAt: event.startsAt.toISOString(),
endsAt: event.endsAt.toISOString(),
hasSpots: event.spotsLeft > 0,
image: event.image ? absolute(imageUrl(event.image)) : null,
venue: {
slug: event.venue.slug,
name: event.venue.name,
district: event.venue.district,
},
}
}It's an allowlist, written field by field. hasSpots instead of the number repeats the reasoning behind the cards (05-02): the data comes from a cache, and an exact figure would often be wrong. Dates are written in UTC with toISOString; the consumer decides which time zone to show them in. And addresses are absolute, because whoever receives them is on another domain.
- Consistent errors
An API client makes decisions based on the error. It needs the right HTTP status code and a body that always has the same shape, whatever the endpoint. The RFC 9457 standard defines one; a smaller one is enough here:
// lib/api/responses.ts
import 'server-only'
const HTTP_STATUSES = {
'bad-request': 400,
unauthorized: 401,
'not-found': 404,
'too-large': 413,
'unsupported-type': 415,
'invalid-data': 422,
'too-many-requests': 429,
internal: 500,
unavailable: 503,
} as const
export type ErrorCode = keyof typeof HTTP_STATUSES
interface Options {
fields?: Record<string, string[] | undefined>
headers?: HeadersInit
}
export function errorResponse(
code: ErrorCode,
message: string,
{ fields, headers }: Options = {},
): Response {
return Response.json(
{ error: { code, message, fields } },
{ status: HTTP_STATUSES[code], headers },
)
}
// Turns an exception into a 500 with no internal details
export async function guarded(
operation: () => Promise<Response>,
headers?: HeadersInit,
): Promise<Response> {
try {
return await operation()
} catch (error) {
console.error('API error:', error)
return errorResponse('internal', 'An error occurred.', { headers })
}
}code is for programs and doesn't change; message is for the person debugging and can be reworded. JSON.stringify leaves out fields when it's undefined.
Without guarded, an exception still produces a 500, but without our body or our headers. With it, there's one thing to be careful about: Next.js uses its own exceptions for redirect, notFound and to stop a prerender, and a catch-all catch would swallow them. The clean way to avoid this is to read whatever depends on the request before calling it, and not to use redirect or notFound inside. There's unstable_rethrow to tell them apart, but it's still marked as unstable.
The codes that get mixed up most often:
| Code | When |
|---|---|
| 400 | The request can't be understood: broken JSON, a malformed parameter |
| 401 / 403 | I don't know who you are / I know who you are and you can't |
| 404 | It doesn't exist, or you don't want to reveal that it exists |
| 409 | It conflicts with the current state, like a second booking |
| 422 | It's understood, but the data isn't valid |
| 429 | Too many requests; send it with Retry-After |
| 500 / 502 / 503 | Our fault / a service we depend on / temporarily unavailable |
A 200 with { ok: false } forces everyone to look inside: caches, monitoring and retries go by the number. Also update the spots 404, which had a different shape:
// app/api/events/[slug]/availability/route.ts
if (!availability) return errorResponse('not-found', "The event doesn't exist.")
- Reading: the list of events
// lib/schemas/api.ts
import * as z from 'zod'
import { integer } from '@/lib/schemas/common'
import { CATEGORIES } from '@/lib/types'
export const eventsQuerySchema = z.strictObject({
category: z.enum(CATEGORIES, 'Unknown category.').optional(),
district: z.string().trim().min(1).max(60).optional(),
page: integer({ min: 1, max: 1000 }).optional(),
})
export const availabilitySchema = z.object({
slugs: z.array(z.string().min(1).max(140)).min(1).max(50),
})// lib/api/cors.ts
import 'server-only'
export const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
}
export function respondToPreflight(): Response {
return new Response(null, { status: 204, headers: CORS_HEADERS })
}// app/api/v1/events/route.ts
import type { NextRequest } from 'next/server'
import * as z from 'zod'
import { CORS_HEADERS, respondToPreflight } from '@/lib/api/cors'
import { toPublicEvent } from '@/lib/api/events'
import { guarded, errorResponse } from '@/lib/api/responses'
import { listEvents } from '@/lib/data/events'
import { eventsQuerySchema } from '@/lib/schemas/api'
const HEADERS = {
...CORS_HEADERS,
'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300',
}
export const OPTIONS = respondToPreflight
export async function GET(request: NextRequest) {
const { origin, pathname, searchParams } = request.nextUrl // Outside guarded
return guarded(async () => {
const result = eventsQuerySchema.safeParse(Object.fromEntries(searchParams))
if (!result.success) {
const { fieldErrors, formErrors } = z.flattenError(result.error)
return errorResponse('bad-request', formErrors[0] ?? 'Check the parameters.', {
fields: fieldErrors,
headers: CORS_HEADERS,
})
}
const requested = result.data.page ?? 1
const { events, total, page, totalPages } = await listEvents(result.data)
const next = new URL(pathname, origin)
for (const [name, value] of searchParams) next.searchParams.set(name, value)
next.searchParams.set('page', String(page + 1))
return Response.json(
{
// listEvents clamps the page; past the last one, the API returns an empty list
data: page === requested ? events.map(toPublicEvent) : [],
page: requested,
totalPages,
total,
next: requested < totalPages ? next.pathname + next.search : null,
},
{ headers: HEADERS },
)
}, CORS_HEADERS)
}- The same
lib/data/function as the page. Rules and cache in a single place; the Route Handler translates. - Here, incorrect parameters are rejected. On
/eventsthey were ignored, because a person with an odd URL would rather see the guide. A program sendingcategry=workshopneeds to find out about the typo:strictObjectrejects unknown keys, with Zod's own English message, which is fine here. If a client repeats a key,Object.fromEntrieskeeps the last one. datainside an object, not a bare array, so fields can be added without breaking anyone.nextsaves the client from building addresses. Walking through the API means repeating until it'snull. It's relative to the site: that way it doesn't depend on the caller'sHostheader.- The clamped page is detected by comparing. Without that, a client asking for page 99 would get the last one over and over again.
Paginating by number has a known flaw (04-02): if an event is published while someone is walking through, an item can be repeated or skipped. For anyone syncing an entire catalog, a cursor is the better choice; for showing the guide, this is enough.
// app/api/v1/events/[slug]/route.ts
import { CORS_HEADERS, respondToPreflight } from '@/lib/api/cors'
import { toPublicEvent } from '@/lib/api/events'
import { guarded, errorResponse } from '@/lib/api/responses'
import { getEventDetails } from '@/lib/data/events'
export const OPTIONS = respondToPreflight
export async function GET(
_request: Request,
{ params }: RouteContext<'/api/v1/events/[slug]'>,
) {
const { slug } = await params
return guarded(async () => {
const details = await getEventDetails(slug)
if (!details) {
return errorResponse('not-found', "The event doesn't exist.", {
headers: CORS_HEADERS,
})
}
const event = toPublicEvent({ ...details.event, venue: details.venue })
return Response.json({ data: event }, { headers: CORS_HEADERS })
}, CORS_HEADERS)
}curl -s 'localhost:3000/api/v1/events?category=workshop'
curl -s -i 'localhost:3000/api/v1/events?categry=workshop' # 400, with the reason
curl -s -i localhost:3000/api/v1/events/does-not-exist # A real 404
curl -s -i -X DELETE localhost:3000/api/v1/events # 405
- CORS
A browser won't let code from another-site.example read a response from our domain unless we allow it. That's CORS: Access-Control-Allow-Origin says who can read from a browser.
*is correct for public data without cookies. With credentials it isn't allowed: you have to return a specific origin, chosen from a list, plusVary: Origin.- It doesn't protect anything.
curland any server ignore CORS. It's a permission for browsers, not access control. - Some requests ask first. A
POSTwithContent-Type: application/jsontriggers a priorOPTIONSrequest (the preflight). If the response doesn't allow it, the real one isn't sent.Max-Ageavoids asking again; each browser applies its own cap. - Errors carry the headers too. Otherwise, the client would see a generic network failure instead of the reason.
Internal routes don't carry them: only our page calls them. For many routes at once, the headers can be set in headers in next.config.ts or in the proxy.
- Receiving a body
The body is read with json(), formData(), text() or arrayBuffer(), and only once: a second read fails. json() returns any and rejects if the text isn't JSON. The four checks on an input are written once:
// lib/api/body.ts
import 'server-only'
import type * as z from 'zod'
import { errorResponse } from '@/lib/api/responses'
const MAX_SIZE = 64 * 1024
type BodyResult<T> = { valid: true; data: T } | { valid: false; response: Response }
export async function readJson<T>(
request: Request,
schema: z.ZodType<T>,
headers?: HeadersInit,
): Promise<BodyResult<T>> {
function reject(...[code, message, options]: Parameters<typeof errorResponse>) {
return {
valid: false as const,
response: errorResponse(code, message, { ...options, headers }),
}
}
// 1. The declared type
const type = request.headers.get('content-type')?.split(';')[0].trim().toLowerCase()
if (type !== 'application/json') {
return reject('unsupported-type', 'Send application/json.')
}
// 2. The size: first the announced one, then the real one
if (Number(request.headers.get('content-length')) > MAX_SIZE) {
return reject('too-large', 'The body is too large.')
}
const text = await request.text()
if (Buffer.byteLength(text) > MAX_SIZE) {
return reject('too-large', 'The body is too large.')
}
// 3. The syntax
let content: unknown
try {
content = JSON.parse(text)
} catch {
return reject('bad-request', 'The body is not JSON.')
}
// 4. The shape
const result = schema.safeParse(content)
if (!result.success) {
const fields: Record<string, string[]> = {}
for (const { path, message } of result.error.issues) {
const field = path.map(String).join('.') // For example, 'slugs.3'
fields[field] = [...(fields[field] ?? []), message]
}
return reject('invalid-data', 'Check the data.', { fields })
}
return { valid: true, data: result.data }
}The announced size may be missing or lie, which is why it's measured again; even so, the text is already in memory, so the real limit must also be set by the server or platform in front. Requiring application/json has a useful side effect: an HTML form on another site can't send it, and with fetch it triggers the preflight.
// lib/data/events.ts (addition)
export async function getAvailabilityForMany(
slugs: string[],
): Promise<(Availability & { slug: string })[]> {
const db = await getDb()
return db
.select({ slug: events.slug, spotsLeft: events.spotsLeft, capacity: events.capacity })
.from(events)
.where(and(isCurrent(), inArray(events.slug, slugs)))
}// app/api/v1/availability/route.ts
import { CORS_HEADERS, respondToPreflight } from '@/lib/api/cors'
import { readJson } from '@/lib/api/body'
import { guarded } from '@/lib/api/responses'
import { getAvailabilityForMany } from '@/lib/data/events'
import { availabilitySchema } from '@/lib/schemas/api'
export const OPTIONS = respondToPreflight
export async function POST(request: Request) {
return guarded(async () => {
const body = await readJson(request, availabilitySchema, CORS_HEADERS)
if (!body.valid) return body.response
const data = await getAvailabilityForMany(body.data.slugs)
return Response.json({ data }, { headers: CORS_HEADERS })
}, CORS_HEADERS)
}It's a POST that doesn't change anything, and there's a reason: fifty slugs don't fit comfortably in a URL, and we don't want any intermediary storing the response. The opposite, a GET that writes, is a real mistake. A POST is never prerendered, so the await on the body can sit inside guarded.
- A GET's cache
With Cache Components, a GET follows the same model as pages. At build time, Next.js tries to run it:
What the GET does |
Result |
|---|---|
| Neither reads the request nor waits for uncached data | It's prerendered (○) |
Calls a function with 'use cache' |
It's prerendered, and renewed according to its cacheLife |
Reads nextUrl, headers, cookies or the body |
It runs on every request (ƒ) |
| Queries the database without a cache, uses the clock or randomness | It runs on every request |
Dynamic route with generateStaticParams |
It's prerendered for those values |
The directive can't go on the GET itself; it goes on the function it calls. The filters endpoint fits the second row:
// app/api/v1/filters/route.ts
import { CORS_HEADERS, respondToPreflight } from '@/lib/api/cors'
import { listDistricts } from '@/lib/data/venues'
import { CATEGORY_LABELS } from '@/lib/format'
import { CATEGORIES } from '@/lib/types'
export const OPTIONS = respondToPreflight
export async function GET() {
const categories = CATEGORIES.map((id) => ({ id, name: CATEGORY_LABELS[id] }))
return Response.json(
{ categories, districts: await listDistricts() },
{ headers: CORS_HEADERS },
)
}In next build it shows up as ○ /api/v1/filters. invalidateVenue renews it, because it inherits the venues tag. It's also the most common trap: a GET you read as "returns the current state" that was computed once at build time. Don't use the old dynamic = 'force-static' or revalidate here: with Cache Components they're an error.
There's a second cache, the HTTP one. The list carries s-maxage=60: if there's a CDN, it will store the response for a minute and serve it without calling our code. For public data, that's exactly what you want. For something that depends on who's asking, it would be a leak: neither the session check nor the rate limit would ever run. Anything personal carries Cache-Control: private, no-store.
- A download: the calendar
A Route Handler can return any type of content. An .ics file lets you add the event to your phone's calendar:
// lib/calendar.ts
import { SITE_URL } from '@/lib/site'
import type { EventDetailsData } from '@/lib/types'
const encoder = new TextEncoder()
// Characters with a special meaning are escaped (RFC 5545)
function escape(text: string): string {
return text.replace(/[\;,]/g, '\\$&').replace(/\r?\n/g, '\\n')
}
function toIcsTime(date: Date): string {
return date.toISOString().replace(/[-:]|\.\d{3}/g, '') // 20280512T183000Z
}
// No line may exceed 75 bytes; continuation lines start with a space
function fold(line: string): string {
const parts: string[] = []
let current = ''
for (const char of line) {
if (encoder.encode(current + char).length > 74) {
parts.push(current)
current = ''
}
current += char
}
return [...parts, current].join('\r\n ')
}
export function createCalendar({ event, venue }: EventDetailsData, now: Date): string {
const lines = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//AgendaViva//EN',
'BEGIN:VEVENT',
`UID:${event.id}@agendaviva.example`,
`DTSTAMP:${toIcsTime(now)}`,
`DTSTART:${toIcsTime(event.startsAt)}`,
`DTEND:${toIcsTime(event.endsAt)}`,
`SUMMARY:${escape(event.title)}`,
`DESCRIPTION:${escape(event.summary)}`,
`LOCATION:${escape(`${venue.name}, ${venue.address}`)}`,
`URL:${new URL(`/events/${event.slug}`, SITE_URL).href}`,
`STATUS:${event.status === 'canceled' ? 'CANCELLED' : 'CONFIRMED'}`,
'END:VEVENT',
'END:VCALENDAR',
]
return lines.map(fold).join('\r\n') + '\r\n'
}// app/api/events/[slug]/calendar/route.ts
import { errorResponse } from '@/lib/api/responses'
import { createCalendar } from '@/lib/calendar'
import { getEventDetails } from '@/lib/data/events'
export async function GET(
_request: Request,
{ params }: RouteContext<'/api/events/[slug]/calendar'>,
) {
const { slug } = await params
const details = await getEventDetails(slug)
if (!details) return errorResponse('not-found', "The event doesn't exist.")
return new Response(createCalendar(details, new Date()), {
headers: {
'Content-Type': 'text/calendar; charset=utf-8',
'Content-Disposition': `attachment; filename="${details.event.slug}.ics"`,
'X-Content-Type-Options': 'nosniff',
},
})
}// lib/api-routes.ts (addition)
export function calendarPath(slug: string): string {
return `/api/events/${slug}/calendar`
}
// EventDetails, below the date
<a href={calendarPath(event.slug)} className="underline">
Add to calendar
</a>- The file name comes from the database, not from the URL. Visitor text in a header is an injection vector, and
Headersrejects line breaks by throwing an exception. - A stable
UID: when it's downloaded again, the calendar updates the event instead of duplicating it. - It uses
<a>, not<Link>: it isn't an in-app navigation, and prefetching it or resolving it on the client makes no sense. createCalendarreceives the time. It's a pure function that can be tested without faking the clock (10-03).
- Responses in chunks
A Response body can be a ReadableStream, and then it travels as it's produced. With text/event-stream you get SSE (Server-Sent Events): the browser keeps the connection open with EventSource and receives messages.
// Example only: spots pushed by the server every five seconds
export async function GET(_request: Request, { params }: RouteContext<'/api/events/[slug]/availability'>) {
const { slug } = await params
const encoder = new TextEncoder()
const stream = new ReadableStream<Uint8Array>({
async pull(controller) { // It stops being called when the client leaves
const availability = await getAvailability(slug)
if (!availability) return controller.close()
controller.enqueue(encoder.encode(`data: ${JSON.stringify(availability)}\n\n`))
await new Promise((resolve) => setTimeout(resolve, 5000))
},
})
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' },
})
}It doesn't replace our polling. This code also queries every five seconds, for each visitor, and it holds a connection open on top of that; it wins when there's something that signals the change (for example, PostgreSQL's LISTEN/NOTIFY) and a long-running server. On serverless platforms, the connection is cut when it reaches the maximum duration. There are no WebSockets in a Route Handler either. For data that can tolerate a twenty-second delay, SWR is simpler and cheaper.
- Server Action or Route Handler
| Server Action | Route Handler | |
|---|---|---|
| Who calls | Your React interface | Anyone |
| Address and contract | Decided by Next.js, and they change | Decided by you, and you maintain them |
| Method | Always POST |
Whichever fits |
| After writing | Returns the refreshed screen in the same round trip | Nothing: the client decides |
| Cache notifications | updateTag, refresh, revalidateTag, revalidatePath |
revalidateTag, revalidatePath |
| Without JavaScript | Works in forms | Only with a hand-written <form method="post"> |
| Foreign origin | The origin is checked (08-06) | Not checked: that's up to you |
| Reading data | No: they run one at a time and aren't cached | Yes, with GET |
| Content | Serializable values | Anything: files, XML, streams |
And on the server, neither: a Server Component calls lib/data/ directly (04-01). If the same operation needs both, both will be a thin layer over the same function.
Common Mistakes and Tips
- Returning the database row in a public API.
- A
GETthat writes. A crawler or a prefetch will run it. - Believing CORS restricts access.
- Expecting
error.tsxor a layout to protect aroute.ts. - Putting
'use cache'on theGETitself, or exportingdynamicorrevalidatewith Cache Components. - Not noticing that a
GETwith no request data was computed at build time. Cache-Control: publicon personal responses.- Sending
error.messageto the client. It may contain SQL, paths or credentials. - Reading the body twice, or using
json()without catching its rejection. - A
catchthat swallowsredirectornotFound. - Changing the meaning of a published field.
Exercises
Exercise 1: choosing the mechanism
Choose between Server Component, Server Action and Route Handler: (a) marking a notice as read in the dashboard; (b) exporting an event's bookings to CSV; (c) a mobile app that shows the guide; (d) the event page's title; (e) autocompleting an address as you type; (f) a survey service that notifies you when one is completed.
Solution
- (a) Server Action: it writes from our interface and has to refresh it.
- (b) Route Handler
GETwithContent-Disposition. It doesn't write, and the result is a file. It must check the session on every call and carryprivate, no-store. - (c) Route Handler: the
v1API, untouched. - (d) Server Component that calls
lib/data/. - (e) Route Handler
GET, like the suggestions: it's a repeated read from the browser. - (f) Route Handler
POST. How to know it is who it claims to be is covered in 07-03.
Exercise 2: exporting to CSV
Create GET /api/v1/events.csv, with the upcoming events (title, start, venue). Keep in mind that a title can contain quotes and commas, and that some spreadsheets run cells starting with =, +, - or @ as formulas. Will it be prerendered?
Solution
// app/api/v1/events.csv/route.ts
import { CORS_HEADERS } from '@/lib/api/cors'
import { listUpcomingEvents } from '@/lib/data/events'
function cell(text: string): string {
const safe = /^[=+\-@\t\r\n]/.test(text) ? `'${text}` : text
return `"${safe.replaceAll('"', '""')}"`
}
export async function GET() {
const events = await listUpcomingEvents(100)
const rows = events.map(({ title, startsAt, venue }) =>
[title, startsAt.toISOString(), venue.name].map(cell).join(','),
)
const content = ['title,startsAt,venue', ...rows].join('\r\n')
return new Response(content, {
headers: { ...CORS_HEADERS, 'Content-Type': 'text/csv; charset=utf-8' },
})
}Yes: it only waits for a function with 'use cache', so it's generated at build time and renewed with the listings profile and the events tag. A folder name can contain a dot. Quotes are doubled, and the leading apostrophe disables the formula. The course doesn't keep this endpoint.
Exercise 3: reviewing an endpoint
Find the problems in this code and fix it without adding authentication, which arrives in module 8.
// app/api/bookings/cancel/route.ts
export async function GET(request: NextRequest) {
try {
const id = request.nextUrl.searchParams.get('id')!
const user = request.nextUrl.searchParams.get('user')!
await cancelBooking(user, id)
return Response.json({ ok: true })
} catch (error) {
return Response.json({ ok: false, error: String(error) })
}
}Solution
- It writes with
GET. - The caller chooses the user: it would cancel other people's bookings.
- It doesn't validate the input;
!only silences the compiler. - It responds 200 to a failure and publishes the internal error.
- It doesn't send the cache notifications.
- It shouldn't exist: only our interface uses it, and that's what
cancelMyBookingis for.
// If another client really needed it: app/api/bookings/[id]/route.ts
export async function DELETE(
_request: Request,
{ params }: RouteContext<'/api/bookings/[id]'>,
) {
const { id } = await params
if (!identifier.safeParse(id).success) {
return errorResponse('bad-request', 'Invalid identifier.')
}
return guarded(async () => {
const user = await getPlaceholderUser()
const result = await cancelBooking(user.id, id)
if (result.status === 'canceled') {
notifyIfAvailabilityChanges(result.spotsBefore, result.spotsAfter)
}
return new Response(null, { status: 204 })
})
}notifyIfAvailabilityChanges uses revalidateTag, which is allowed here; refresh isn't. Canceling something that doesn't exist also returns 204: the operation is idempotent.
Conclusion
A Route Handler is HTTP with no middlemen: one function per method, Request and Response, and you decide the status codes, headers and shape. What you publish for third parties is a contract: a version in the path, fields chosen one by one, errors with a fixed shape, strict parameters and pagination the client only has to follow. A GET obeys the Cache Components rules, with the possibility of being computed at build time, and Cache-Control governs whatever happens outside. AgendaViva now has its v1 API and a calendar download, built on the same functions as the interface.
Route Handlers respond once the request has already reached their route. Sometimes you need to step in earlier: redirecting an old address, adding a header or answering with a real 404 before the shell goes out, as we promised in 02-04. That's the job of Proxy: Intercepting and Redirecting Requests.
