Type-safe API Routes in Next.js

January 9, 2024 · 3 min read

Since the release of Next.js 14, I’ve been moving all of my products (old and new) to the app directory and Server Components. It’s been fun, with its fair share of bumps in the road. But one of my favorite new features is Route Handlers. Built on web standards, these handlers let you return anything from a route: a JSON API response, an image, a stream, React Components… anything!

But all that flexibility comes with very few guard-rails. These handlers are minimal by default, and since you can return anything from them, there’s no contract that you’re responding with the right thing, or even responding at all. And if you are responding with something, is it what you promised?

The missing API features for Next.js

So I built typed-route-handler, a small node module for Next.js Route Handlers. With a couple of lines, you get a type-safe API endpoint, automatic validation handling, and request logging and timing.

Here’s a minimal example of how it works:

import { handler } from "typed-route-handler"

type ResponseData = {
  result: string
  over: number
}

export const GET = handler<ResponseData>((req) => {
  // This response must match ResponseData
  return NextResponse.json({
    result: "this response is type-checked",
    over: 9000
  })
})

Or, a more complete example with URL parameter types:

import { handler } from "typed-route-handler"

import { auth } from "@/auth"

type ResponseData = {
  result: string
  over: number
}

type Context = {
  params: {
    id: string
  }
}

/**
 * GET /api/articles/:id
 */
export const GET = handler<ResponseData, Context>(async (req, context) => {
  // If the user is not authenticated, we can call `unauthorized()` which will
  // automatically be caught by the handler, and respond with an HTTP 401.
  const session = await auth()
  if (!session) {
    unauthorized()
  }

  // `context` is type-safe here
  const article = findArticle(context.params.id)

  // This response must match ResponseData
  return NextResponse.json({
    result: "this response is type-checked",
    over: 9000
  })
})

Going further with zod

I use zod for schema validation all the time, and wanted to bring some of that to typed-route-handler.

If you use zod within a handler, any validation errors get caught and returned to the client as a 400 Validation Error. This works even if you don’t specify any return types. For example:

import { z } from "zod"

const bodySchema = z.object({
  name: z.string().min(3),
  age: z.number()
})

/**
 * POST /api/settings
 */
export const POST = handler(async (req) => {
  // Any parsing error here will throw a Validation Error
  const { name, age } = bodySchema.parse(await req.json())

  return NextResponse.json({
    ok: true
  })
})

You can use zod with route parameters, search params, and pretty much everything else, and typed-route-handler will handle it.

Making your APIs better

While building this, I realized it was the missing API endpoint layer for Next.js. Wrapping my existing API routes with handler gave me a handful of basic features that I’d expect Next.js to ship with:

  • Response type-checking: Make sure your API endpoints are honoring their side of the contract.
  • Request Parameter type-checking: Your route can be defined with a zod schema, so you can validate and coerce URL parameters. You can validate that a token is a uuid/cuid, or coerce an ID to a number.
  • Deep zod compatibility: When you call a zod schema’s parse method within a handler, any exceptions are caught and returned as a 400 Validation Error
  • Helpful error methods: Following Next’s notFound() standard, we exposed unauthorized() (HTTP 401) and validationError() (HTTP 400) methods, which are of type never so they can be used anywhere in the handler.
  • And, at a more basic level, I get request logging and timing.

Give it a try

npm i typed-route-handler

# or better yet:
pnpm add typed-route-handler

Check out the README for more examples, and let me know what you think.

The code is MIT-licensed and free to use. As always, pull requests and improvements are welcome!