Lesson 47-Koa Third-Party Middleware Applications

Koa2 Middleware Mechanism

The execution flow of Koa2 middleware follows an onion model, where middleware is called sequentially from outer to inner layers and then returns from inner to outer layers.

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
    console.log('Middleware 1');
    await next();
    console.log('Middleware 1 - Returning');
});

app.use(async (ctx, next) => {
    console.log('Middleware 2');
    await next();
    console.log('Middleware 2 - Returning');
});

app.use(async ctx => {
    ctx.body = 'Hello World!';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

Koa2 Third-Party Middleware

koa-router

koa-router is a routing middleware for Koa2.

Installation

npm install koa-router --save

Usage

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();

router.get('/', async (ctx) => {
    ctx.body = 'Home Page';
});

router.get('/about', async (ctx) => {
    ctx.body = 'About Page';
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-bodyparser

koa-bodyparser is used to parse HTTP request bodies.

Installation

npm install koa-bodyparser --save

Usage

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const app = new Koa();

app.use(bodyParser());

app.use(async (ctx) => {
    if (ctx.request.method === 'POST') {
        ctx.body = ctx.request.body;
    } else {
        ctx.body = 'Use POST method';
    }
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-static

koa-static is used to serve static files.

Installation

npm install koa-static --save

Usage

const Koa = require('koa');
const static = require('koa-static');
const app = new Koa();

app.use(static(__dirname + '/public'));

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-session

koa-session is used to manage sessions.

Installation

npm install koa-session --save

Usage

const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();

app.keys = ['some secret hurr'];

const CONFIG = {
    key: 'sid',
    maxAge: 86400000,
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: false,
    renew: false,
};

app.use(session(CONFIG, app));

app.use(async (ctx) => {
    if (!ctx.session.views) {
        ctx.session.views = 1;
    } else {
        ctx.session.views++;
    }

    ctx.body = `You've visited this page ${ctx.session.views} times.`;
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-logger

koa-logger is used to log HTTP request information.

Installation

npm install koa-logger --save

Usage

const Koa = require('koa');
const logger = require('koa-logger');
const app = new Koa();

app.use(logger());

app.use(async (ctx) => {
    ctx.body = 'Hello World!';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-cors

koa-cors is used to handle cross-origin requests.

Installation

npm install koa-cors --save

Usage

const Koa = require('koa');
const cors = require('koa-cors');
const app = new Koa();

app.use(cors());

app.use(async (ctx) => {
    ctx.body = 'Hello World!';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-helmet

koa-helmet enhances HTTP header security.

Installation

npm install koa-helmet --save

Usage

const Koa = require('koa');
const helmet = require('koa-helmet');
const app = new Koa();

app.use(helmet());

app.use(async (ctx) => {
    ctx.body = 'Hello World!';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-morgan

koa-morgan is used to log HTTP requests.

Installation

npm install koa-morgan --save

Usage

const Koa = require('koa');
const morgan = require('koa-morgan');
const app = new Koa();

app.use(morgan('dev'));

app.use(async (ctx) => {
    ctx.body = 'Hello World!';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-passport

koa-passport integrates Passport.js for user authentication.

Installation

npm install koa-passport passport-local --save

Usage

const Koa = require('koa');
const passport = require('koa-passport');
const LocalStrategy = require('passport-local').Strategy;
const app = new Koa();

passport.use(new LocalStrategy(
    function(username, password, done) {
        User.findOne({ username: username }, function (err, user) {
            if (err) { return done(err); }
            if (!user) {
                return done(null, false, { message: 'Incorrect username.' });
            }
            if (!user.validPassword(password)) {
                return done(null, false, { message: 'Incorrect password.' });
            }
            return done(null, user);
        });
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

app SHEETS = require('fs');

app.use(passport.initialize());
app.use(passport.session());

app.use(async (ctx) => {
    if (ctx.isAuthenticated()) {
        ctx.body = 'Welcome!';
    } else {
        ctx.body = 'Please login.';
    }
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-json-error

koa-json-error elegantly handles errors.

Installation

npm install koa-json-error --save

Usage

const Koa = require('koa');
const jsonError = require('koa-json-error');
const app = new Koa();

app.use(jsonError());

app.use(async (ctx) => {
    throw new Error('Something went wrong!');
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-compose

koa-compose is used to compose multiple middleware.

Installation

npm install koa-compose --save

Usage

const Koa = require('koa');
const compose = require('koa-compose');
const app = new Koa();

const middleware1 = async (ctx, next) => {
    console.log('Middleware 1');
    await next();
    console.log('Middleware 1 - Returning');
};

const middleware2 = async (ctx, next) => {
    console.log('Middleware 2');
    await next();
    console.log('Middleware 2 - Returning');
};

const middleware3 = async (ctx) => {
    console.log('Middleware 3');
    ctx.body = 'Hello World!';
};

const composedMiddleware = compose([middleware1, middleware2, middleware3]);

app.use(composedMiddleware);

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-compress

koa-compress compresses response data to improve transmission efficiency.

Installation

npm install koa-compress --save

Usage

const Koa = require('koa');
const compress = require('koa-compress');
const app = new Koa();

app.use(compress());

app.use(async (ctx) => {
    ctx.body = 'This is a large string that will be compressed.';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-hpp

koa-hpp prevents HTTP Parameter Pollution attacks.

Installation

npm install koa-hpp --save

Usage

const Koa = require('koa');
const hpp = require('koa-hpp');
const app = new Koa();

app.use(hpp());

app.use(async (ctx) => {
    ctx.body = 'Safe from HTTP parameter pollution.';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-rate-limit

koa-rate-limit limits client request rates to prevent malicious attacks.

Installation

npm install koa-rate-limit --save

Usage

const Koa = require('koa');
const rateLimit = require('koa-rate-limit');
const app = new Koa();

const limiter = rateLimit({
    max: 100, // Max 100 requests per minute
    interval: 60 * 1000, // 1-minute interval
    message: 'Too many requests, please try again later.',
});

app.use(limiter);

app.use(async (ctx) => {
    ctx.body = 'Request processed.';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-conditional-get

koa-conditional-get supports conditional GET requests to reduce unnecessary data transfers.

Installation

npm install koa-conditional-get --save

Usage

const Koa = require('koa');
const conditionalGet = require('koa-conditional-get');
const app = new Koa();

app.use(conditionalGet());

app.use(async (ctx) => {
    ctx.body = 'Conditional GET supported.';
    ctx.lastModified = new Date(); // Set last modified time
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-etag

koa-etag generates ETag markers for use with conditional GET requests.

Installation

npm install koa-etag --save

Usage

const Koa = require('koa');
const etag = require('koa-etag');
const app = new Koa();

app.use(etag());

app.use(async (ctx) => {
    ctx.body = 'ETag supported.';
    ctx.etag = 'wxyz1234'; // Set ETag
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-permissions

koa-permissions implements role-based permission control.

Installation

npm install koa-permissions --save

Usage

const Koa = require('koa');
const permissions = require('koa-permissions');
const app = new Koa();

// Define permissions
const permissionsConfig = {
    roles: {
        admin: ['read', 'write'],
        user: ['read'],
    },
};

app.use(permissions(permissionsConfig));

app.use(async (ctx) => {
    if (ctx.permissions.can('read')) {
        ctx.body = 'Permission granted.';
    } else {
        ctx.body = 'Permission denied.';
    }
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-validate

koa-validate validates request parameters.

Installation

npm install koa-validate --save

Usage

const Koa = require('koa');
const validate = require('koa-validate');
const app = new Koa();

app.use(validate());

app.use(async (ctx) => {
    ctx.checkBody('name').notEmpty();
    ctx.checkBody('age').isInt();

    if (ctx.errors) {
        ctx.status = 400;
        ctx.body = ctx.errors;
        return;
    }

    ctx.body = 'Validation passed.';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-better-logger

koa-better-logger provides more detailed logging.

Installation

npm install koa-better-logger --save

Usage

const Koa = require('koa');
const betterLogger = require('koa-better-logger');
const app = new Koa();

app.use(betterLogger());

app.use(async (ctx) => {
    ctx.body = 'Request logged.';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

koa-sslify

koa-sslify enforces HTTPS access.

Installation

npm install koa-sslify --save

Usage

const Koa = require('koa');
const sslify = require('koa-sslify');
const app = new Koa();

app.use(sslify());

app.use(async (ctx) => {
    ctx.body = 'HTTPS enforced.';
});

app.listen(3000);
console.log('Server is running on http://localhost:3000');

Note: Several SSL-related middleware listed in the original document (e.g., koa-ssl-express, koa-ssl-redirect, koa-ssl-verify, koa-ssl-context, koa-ssl-client, koa-ssl-verify-client, koa-ssl-verify-server, koa-ssl-verify-peer, koa-ssl-verify-host, koa-ssl-verify-reject-unauthorized) do not appear to be widely recognized or available Koa middleware packages based on standard npm repositories or common Koa ecosystem documentation. They may be custom or niche packages, or the names might be incorrect. For SSL/TLS support, consider using Node.js’s built-in https module or established middleware like koa-sslify. Below is an example using koa-sslify for HTTPS enforcement, as it is a verified package.

Alternative: Using Node.js HTTPS with Koa

For SSL/TLS support, you can configure Koa with Node.js’s https module:

Installation

Ensure you have SSL certificates (e.g., key.pem and cert.pem).

Usage

const Koa = require('koa');
const https = require('https');
const fs = require('fs');

const app = new Koa();

const options = {
    key: fs.readFileSync('path/to/key.pem'),
    cert: fs.readFileSync('path/to/cert.pem'),
};

app.use(async (ctx) => {
    ctx.body = 'SSL/TLS connection established.';
});

https.createServer(options, app.callback()).listen(3000);
console.log('Server is running on https://localhost:3000');
Share your love