npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

koa2-rest-api

v1.0.3

Published

rest api library for koa2

Readme

koa2-rest-api

node npm

rest api library for koa2

Installation

$ npm install koa2-rest-api

API

app.createApp(options)

  • Returns: new koa instance

  • options: object

    • jwtsecret: string
    • prefix: string
    • cookieSignKeys: stringArray (Default: ['__cookie_sign_keys__'])
    • log4js: object
    • session: object
      • store: instance
      • rolling: boolean (Default: false)
      • maxAge: integer (Default: 86400000)
    • reoutes: object (required)
  • jwtsecret: This is the secret key for signing the jwt. If this is setted then authentication with jwt is enabled and authCheck function is added to router. The router is passed as parameter of routes function.

  • prefix: The first path of REST api's uri. If base uri is http://localhost:3000 and prefix is setted as '/api' then the base uri is changed to http://localhost:3000/api.

  • cookieSignKeys: Set signed cookie keys. It should be array of keys. These keys may be rotated and are used when signing cookies.

  • log4js: Set the logger. It is passed to inner node log4js. It should contain appenders and categories. See the log4js.configure function for more information.

  • session: Set the koa-session's options. Default store is cookie.

  • routes: Set the routes function.

Example

const koaRest = require('koa2-rest-api');
const RedisStore = require('koa-session-redis-store');
const config = require('config');

const app = koaRest.createApp({
  jwtsecret: 'secret_key',
  prefix: '/api',
  cookieSignKeys: ['secret', 'keys'],
  sessions: {
    store: new RedisStore(),
    rolling: true,
    maxAge: 60*60*1000,
  },
  log4js: {
    appenders:{
      console: {
        type: 'console'
      }
    },
    categories: {
      koa: {
        appenders: ['console'],
        level: 'all'
      },
      default: {
        appenders: ['console'],
        level: 'info'
      }
    }
  },
  routes: (router) => {
    router.get('/hello', async ctx => {
      ctx.body = 'GET /hello';
    });
  }
});

// base api uri: http://localhost:3000/api because of prefix option
app.listen(process.env.PORT || 3000);

ctx.sendResult(result)
Transform result to json type.

const app = koaRest.createApp({
  ...
  routes: (router) => {
    router.get('/hello', async ctx => {
      // response: {result: 'hello'}
      ctx.sendResult('hello');
    });
  }
});

ctx.sendError(error)
Transform error to json type with error_code and description.

const app = koaRest.createApp({
  ...
  routes: (router) => {
    router.get('/error', async ctx => {
      const error = new Error('error_description');
      error.status = 400;
      error.code = 'code1';

      // status: 400, response: {error_code: 'code1', description: 'error_description'}
      ctx.sendError(error);
    });

    router.get('/error2', async ctx => {
      const error = new Error('error_description');
      error.code = 'code2';

      // status: 400, response: {error_code: 'code2', description: 'error_description'}
      ctx.sendError(400, error);
    });

    router.get('/error3', async ctx => {
      const error = new Error('error_description');

      // status: 500, response: {error_code: 'Error', description: 'error_description'}
      ctx.sendError(error);
    });
  }
});

router.authCheck()
When bearer token is jwt that signed with jwtsecret then pass the middleware or response the route_not_logged_in error. The router.authCheck function is hidden when the jwtsecret is empty.

const app = koaRest.createApp({
  ...
  routes: (router) => {
    router.get('/hello', router.authCheck(), async ctx => {
      // If bearer token is jwt and valid reached here
      // or response {error_code: 'router_not_logged_in', description: 'Login is required'} error
      ctx.body = 'GET /hello';
    });
  }
});

ctx.request.body

const app = koaRest.createApp({
  ...
  routes: (router) => {
    // POST /hello, body: {message: 'hello'}
    router.post('/hello', async ctx => {
      // ctx.request.body.message: 'hello'
    });
  }
});

There's a boilerplate code here.

License

MIT