5 Steps to create professional API routes in Next.js

Kolby Sisk
Udacity Eng & Data
Published in
3 min readAug 29, 2022

--

Intro

Next.js provides a solution to build an API within your Next.js codebase. It’s a nice solution that makes use of their file based routing system. When you create your first API route, you’ll notice it’s very bare. The example on their docs show a function that is injected with req and res objects, and returns a response. However, in a production application you’ll need to include many additional features to achieve API best practices. Here are the 5 steps that I use in all of my Next.js projects to ensure my handlers are ready for production.

Type your handler response

Type safety is an important part of any professional project. Thankfully, Next.js makes it easy to type the handler response by accepting a generic in the NextApiResponse type.

In this example we have an endpoint that will return a User. We create the User type and pass it as a generic into the response type: NextApiResponse<User>. Now if anything other than { userId: string } is returned from the handler, TypeScript will yell at us. 👍

Check for allowed methods

Next’s API routes get called for every HTTP method that may make a request. It’s important to reject methods that you’re not expecting, and return a 405 status code.

To achieve this we can create a list of allowed methods, then compare against the request’s status.

Capture errors

It’s important to capture any errors that could occur in your handler, and return the appropriate 500 status code. This is also a good pattern for utilizing error tracking tools like Sentry.

To achieve this we can wrap our code in a try…catch:

Validate incoming data

I’ve written before about how important data validation is on the client side, but it’s much more important on the server side. I use Zod for all of my validation needs and I highly recommend it.

The first step in the above code is to create a Zod schema. Next, we prepare the body and run Zod’s safeParse. If validation doesn’t pass we return a 400 along with the error.

What I like most about this approach is you can utilize the same schema on the client and have e2e type safety. 🤌

Middleware

Now we have a lot of best practices included in our handler, but there’s a lot of code and we haven’t even done anything with our handler. Not to mention this will be reused for every API route we have. That’s what I was thinking when I decided to create the next-api-route-middleware package. With this, we’re able to abstract this repeatable code into composable middleware functions.

Much better! The next-api-route-middleware package exports a use function, which accepts middleware functions and a handler.

Checkout my post about middleware in Nextjs to learn more about middleware and the next-api-route-middleware package.

Conclusion

Utilizing the 5 steps above will make your API handlers safer, cleaner, and faster to create. Make sure to checkout my post about middleware in Next.js to learn more about composing middleware functions in your API handlers.

If you want to keep up with the latest in webdev make sure to follow me here and on Twitter @Kolbysisk. 🙏

--

--

Builder of software with a passion for learning. I specialize in web development and user experience design. www.kolbysisk.com