vanilla-ts-http-route-handler
Screenshots
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "vanilla-ts-http-route-handler" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-c4bdee824907b16e04ee61aa2b2874fac1deb3c4a01065f9948657ee8ac21315. Verify the upstream source and version against https://github.com/HKUDS/OpenSpace before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
This package example shows how to use Node's http.createServer in a pure TypeScript project and correctly add route handlers when implementing routing manually with switch/case. It focuses on basic techniques for matching request paths, branching by HTTP method, registering and invoking handler functions, and organizing route logic without introducing Express Router or Next.js routing patterns—allowing you to mount each route handler clearly on the native http server with minimal dependencies.
Introduction source: third_party · HKUDS · 0.0.1 Reference
SkillPi interpretation
- Tasks
- How to correctly add route handlers in a vanilla TypeScript project that uses http.createServer with a manual switch/case router — without introducing Express Router or Next.js patterns.
- Testing
- Not tested
Browse files
Frontmatter
name: vanilla-ts-http-route-handler
description: How to correctly add route handlers in a vanilla TypeScript project that uses http.createServer with a manual switch/case router — without introducing Express Router or Next.js patterns.Adding Route Handlers to a Vanilla TypeScript HTTP Server
Use this skill whenever you need to add a new route to a TypeScript project
that uses Node's built-in http module and a switch/case pathname router
without Express or Next.js.
Step 0 — Confirm the routing style
Before writing any code, inspect server/index.ts (or whichever file starts
the HTTP server). Look for:
http.createServer((req, res) => {
const { pathname } = new URL(req.url!, `http://${req.headers.host}`);
switch (pathname) {
case '/api/foo': ...
}
});
If you see this pattern, follow the steps below.
Do NOT use express.Router, next/server, or any framework-specific
handler signature — even if other files in server/routes/ happen to
use those patterns.
Step 1 — Create the route file
Create server/routes/<feature>.ts.
Use only the native Node types: http.IncomingMessage and
http.ServerResponse.
// server/routes/health.ts
import http from 'http';
export async function handleHealth(
req: http.IncomingMessage,
res: http.ServerResponse
): Promise<void> {
// Parse body for POST/PUT if needed
const body = await readBody(req); // helper shown in Step 3
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
}
Rules for the route file:
- Export the handler as a named async function (
handle<Feature>). - Accept exactly
(req: http.IncomingMessage, res: http.ServerResponse). - Return
Promise<void>. - Do not call
next()or return aResponseobject. - Handle errors internally and write an appropriate HTTP status + JSON body.
Step 2 — Import the handler in server/index.ts
Add a named import at the top of the file alongside any existing imports:
import { handleHealth } from './routes/health';
Step 3 — Add a case entry to the switch block
Locate the existing switch (pathname) block and add a new case:
switch (pathname) {
case '/api/health':
await handleHealth(req, res);
break;
// … existing cases …
default:
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
- Match the exact pathname string used by the client.
- Always
break(orreturn) after calling the handler. - Keep the
defaultcase last.
Step 4 — Optional: shared body-reading helper
If multiple routes need to parse a JSON request body, add a small utility rather than duplicating the logic:
// server/utils/readBody.ts
import http from 'http';
export function readBody(req: http.IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => (data += chunk));
req.on('end', () => {
try {
resolve(data ? JSON.parse(data) : {});
} catch {
reject(new Error('Invalid JSON'));
}
});
req.on('error', reject);
});
}
Import and use it inside any route handler that needs it.
Checklist
- [ ]
server/routes/<feature>.tsexists and exports a named async handler. - [ ] Handler signature is
(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>. - [ ] Handler always calls
res.writeHead(...)andres.end(...)on every code path. - [ ] Handler is imported in
server/index.ts. - [ ] A matching
caseentry is present in theswitch (pathname)block. - [ ] No Express / Next.js / Koa types or patterns were introduced.
Anti-patterns to avoid
| ❌ Wrong | ✅ Correct |
|---|---|
import { Router } from 'express' |
import http from 'http' |
export default function handler(req: NextApiRequest, ...) |
export async function handleFoo(req: http.IncomingMessage, ...) |
router.get('/foo', ...) |
case '/api/foo': await handleFoo(req, res); break; |
| Returning a value from the handler | Calling res.end(...) and returning void |
Current listing version
0.0.1
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 针对纯 TypeScript + Node.js 原生 http 模块的手动路由场景,解决开发者在不使用框架时的常见痛点
- 提供端到端完整实现路径,实用价值高,受众明确
Highlights
- 触发描述精准,明确排除 Express/Next.js 等框架,边界清晰,不易误触
Areas to improve
-
缺少显式 When to Use 章节 Reported severity: Minor
文档开头已说明使用场景,但未使用标准 'When to Use' 标题
Recommendation: 建议添加显式 'When to Use' 章节以提升规范性
Highlights
- 步骤划分清晰(Step 0-4),含完整代码示例、清单和反模式对比
- frontmatter 完整,文档结构良好,易于理解和执行
Highlights
- 代码示例完整且类型安全,包含错误处理机制(如 JSON 解析异常)
- 使用 Node.js 原生模块,无需额外依赖,执行可靠
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.