jwt-koa

Simple mini-lib for secured APIs and servers with Koa and JWT.

NPM version Open Source Love

What includes

Setup

Install it:

npm install jwt-koa --save

or

yarn add jwt-koa

Usage

Import

const jwtKoa = require('jwt-koa');

Set secret key for JWT

process.env.SECRET = 'secret';

Set middleware to secured Router

securedRouter.use(jwtKoa.middleware);
securedRouter.get('/secured', async ctx => {
    ctx.body = { data: 'Secured Data' };
});

Send token to client

notSecuredRouter.post('/send', async ctx => {
    const token = jwtKoa.createToken({ tokenData: 'tokenData' });
    // You can set expire time (3000 by default)
    const tokenWithExpireTime = jwtKoa.createToken(
        { tokenData: 'tokenData' },
        5000
    );
    ctx.response.body = token;
});

Client-side example

fetch('/secured', { method: 'GET', headers: { Authorization: /* There is token from backend*/ } })
    .then(j => j.json())
    .then(data => /* There is secured data*/);

Usage example