Next.js API routes with Koa.js
Ivan V.

Ivan V. @ivandotv

About: Full-stack web developer

Location:
Novi Sad, Serbia
Joined:
Mar 6, 2019

Next.js API routes with Koa.js

Publish Date: May 16 '22
9 0

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):

//pages/api/[[...demo]].ts
import { KoaApi, withKoaApi } from 'nextjs-koa-api'

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

api.use((ctx) => {
  ctx.body = 'Hello World'
})
.router.get('/:todo',....)
.post('/:todo',....)
.delete('/:todo',....)

//use helper function
export default withKoaApi(API)

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

Enter fullscreen mode Exit fullscreen mode

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

https://github.com/ivandotv/nextjs-koa-api

I'm open to suggestions and contributions.

Thanks!

Comments 0 total

    Add comment