koa

$npx mdskill add partme-ai/full-stack-skills/koa

Guides developers in building lightweight Node.js web applications and APIs using the Koa.js framework.

  • Helps with creating HTTP services, middleware composition, and application structure for Koa projects.
  • Integrates with tools like koa-router and koa-bodyparser for routing and request handling.
  • Recommends best practices based on Koa's onion-model and async/await patterns for middleware.
  • Delivers results through code examples, step-by-step workflows, and configuration guidance.

SKILL.md

.github/skills/koaView on GitHub ↗
---
name: koa
description: "Provides comprehensive guidance for Koa.js framework including middleware composition, context API, async/await patterns, and application structure. Use when the user asks about Koa, needs to create lightweight Node.js web applications, implement middleware, or build APIs with Koa."
license: Complete terms in LICENSE.txt
---

## When to use this skill

Use this skill whenever the user wants to:
- Build Node.js HTTP services with Koa and its onion-model middleware
- Configure routing (koa-router), body parsing, error handling, and static files
- Compose async middleware with `ctx` and `next` patterns
- Create lightweight REST APIs or web applications

## How to use this skill

### Workflow

1. **Create app** — instantiate Koa and add middleware in order
2. **Add routing** — use `@koa/router` for route definitions
3. **Handle errors** — add error middleware at the top of the stack
4. **Deploy** — run behind reverse proxy with HTTPS

### Quick Start Example

```javascript
const Koa = require('koa');
const Router = require('@koa/router');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
const router = new Router();

// Error handling middleware (top of stack)
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { error: err.message };
    ctx.app.emit('error', err, ctx);
  }
});

// Body parser
app.use(bodyParser());

// Routes
router.get('/api/items', async (ctx) => {
  const items = await Item.findAll();
  ctx.body = { items };
});

router.post('/api/items', async (ctx) => {
  const { name, price } = ctx.request.body;
  const item = await Item.create({ name, price });
  ctx.status = 201;
  ctx.body = item;
});

router.get('/api/items/:id', async (ctx) => {
  const item = await Item.findById(ctx.params.id);
  if (!item) {
    ctx.throw(404, 'Item not found');
  }
  ctx.body = item;
});

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

app.listen(3000, () => console.log('Server running on port 3000'));
```

### Onion Model Middleware

```javascript
// Logging middleware — demonstrates onion execution order
app.use(async (ctx, next) => {
  const start = Date.now();
  await next(); // <-- downstream
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
```

### Custom Middleware Example

```javascript
// Authentication middleware
function requireAuth() {
  return async (ctx, next) => {
    const token = ctx.get('Authorization')?.replace('Bearer ', '');
    if (!token) {
      ctx.throw(401, 'Authentication required');
    }
    ctx.state.user = await verifyToken(token);
    await next();
  };
}

router.get('/api/profile', requireAuth(), async (ctx) => {
  ctx.body = ctx.state.user;
});
```

## Best Practices

- Use `async/await` correctly with `next()` — always `await next()` in middleware
- Place error handling middleware at the top of the middleware stack
- Use `ctx.throw()` for HTTP errors; listen to `app.on('error')` for logging
- Deploy behind a reverse proxy (nginx) with HTTPS in production
- Use `@koa/cors` for CORS configuration; keep middleware chain lean

## Reference

- Official documentation: https://koajs.com/

## Keywords

koa, Node.js, middleware, onion model, async/await, context, routing, REST API

More from partme-ai/full-stack-skills

SkillDescription
adobe-xd"Guides creation of UI/UX designs, interactive prototypes, reusable components, and design specs in Adobe XD. Use when the user asks about Adobe XD artboards, prototype links, repeat grids, component states, design tokens export, or developer handoff."
angular"Provides comprehensive guidance for Angular framework including components, modules, services, dependency injection, routing, forms, and TypeScript integration. Use when the user asks about Angular, needs to create Angular applications, implement Angular components, or work with Angular features."
ansible"Provides comprehensive guidance for Ansible automation including playbooks, roles, inventory, and module usage. Use when the user asks about Ansible, needs to automate IT tasks, create Ansible playbooks, or manage infrastructure with Ansible."
ant-design-mini"Builds mini-program UIs with Ant Design Mini components for Alipay and WeChat mini-programs. Covers Button, Form, List, Modal, Tabs, NavBar, and 60+ components with theme customization and CSS variable theming. Use when the user needs to create mini-program interfaces with Ant Design Mini, configure themes, or implement mini-program-specific UI patterns."
ant-design-mobile"Builds React mobile UIs with Ant Design Mobile (antd-mobile) components including Button, Form, List, Modal, Picker, Tabs, PullToRefresh, InfiniteScroll, and 50+ mobile-optimized components. Use when the user needs to create mobile-first React interfaces, implement mobile navigation, forms, or data display with Ant Design Mobile."
ant-design-react"Builds enterprise React UIs with Ant Design (antd) including 60+ components (Button, Form, Table, Select, Modal, Message), design tokens, TypeScript support, and ConfigProvider theming. Use when the user needs to create React applications with Ant Design, build forms with validation, display data tables, or customize the Ant Design theme."
ant-design-vueProvides comprehensive guidance for Ant Design Vue (AntDV) component library for Vue 3. Covers installation, usage, API reference, templates, and all component categories. Use when building enterprise-class UI with Vue 3 and Ant Design.
api-doc-generator"Generate API documentation by scanning Controller classes, extracting endpoint URLs, HTTP methods, parameters, and response structures, then producing standardized docs from templates. Use when the user explicitly mentions generating API documentation, creating API docs, scanning interfaces, or documenting REST APIs. Do not trigger for generic documentation requests without explicit API mention."
appium"Provides comprehensive guidance for Appium mobile testing including mobile app automation, element location, gestures, and cross-platform testing. Use when the user asks about Appium, needs to test mobile applications, automate mobile apps, or write Appium test scripts."
ascii-ansi-colorizer"Add an ANSI color layer to existing ASCII/plain-text output (gradient/rainbow/highlights) with alignment-safe rules and a required no-color fallback. Use when the user wants to colorize terminal output, add rainbow effects to CLI text, or style ASCII art with ANSI colors."