DEV Community

Ivan V.
Ivan V.

Posted on

Next.js API routes with Koa.js

I'll keep this post short and sweet :)

I've been doing some CRUD with Next.js API routes, and I've always liked using Koa.js for creating the API's in Node.js.

I think Koa.js is a great fit for Next.js because it is fully async, error handling is easy, and the codebase is very small so the initialization of the Koa App is very fast.

I've decided to integrate Koa.js (and Koa Router) with the Next.js API routes:

Usage is simple as this (in your API file):

import { KoaApi, withKoaApi } from 'nextjs-koa-api'

const api = new KoaApi({ router: { prefix: '/api' } })

api.use((ctx) => {
  ctx.body = 'Hello World'

//use helper function
export default withKoaApi(API)

//or the standard way
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  return, res)

Enter fullscreen mode Exit fullscreen mode

Check out the repository where you can find complete documentation and a small Next.js demo app.

I'm open to suggestions and contributions.


Top comments (0)