Member-only story
How to Unit Test Next.js API Routes with Typescript
If you need env vars, mocked data, and Typescript types, this one’s for you.

Introduction
Next.js is an awesome frontend framework. It’s powered by React under the hood so it plays well with everything React has to offer out of the box: Hooks, Context, hot browser reloading, Typescript integration, and then it takes it a step further than what Create React App has, and offers even more like routing, server side rendering (SSR), static site generation (SSG), all the SEO juice that comes along with both SSR and SSG, and built-in API routing — no extra Node server required to proxy API calls securely to a database, another microservice, or a third party API.
At work, a team of developers and I have been building a new application that we’ve open sourced to help our users get up and running faster with the Internet of Things (IoT) hardware we create.
For our first “accelerator application”, the idea is that a user will get some of our IoT devices, those devices will begin collecting data like temperature, humidity, motion, etc., they’ll send that environmental data to a cloud, and then they’ll fork our “starter application” code to get a dashboard up and running, pulling in their own sensor data from the cloud, and displaying it in the browser.
To build this app, we decided to go with the Next.js framework because it offered so many of the benefits I listed above, one of the most important being the the ability to make secure API calls without having to set up a standalone Node server using Next.js’s API routes. All of the data displayed by the application must be fetched from the cloud (or a database) where the device data is stored after it’s first recorded.
And this being a production-ready application, things like automated unit and end-to-end tests to ensure the various pieces of the application work as expected are a requirement — both to give the developers and our users confidence that as new features are added already existing functionality remains intact.
While by and large, the Next.js documentation is great, one place that it does fall short is when it comes to unit testing these API routes. There is literally nothing…