vanilla-ts-http-route-handler
O que ela faz
Esta skill explica como acrescentar rotas de API a um servidor Node que usa o módulo http integrado e um roteador baseado em switch. É para desenvolvedores que trabalham com pequenos servidores TypeScript.
Quando usar
- ✓Quando o seu servidor usa o módulo http integrado e você precisa de uma nova rota.
- ✓Quando você quer evitar adicionar Express ou outro framework a um servidor pequeno.
- ✓Quando outros arquivos de rota usam um estilo de framework que não combina com o seu servidor.
Link da skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/vanilla-ts-http-route-handler/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Pode acrescentar uma nova rota de verificação de saúde ao meu servidor Node sem instalar o Express?”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente cria um arquivo de rota que usa os tipos de requisição e resposta integrados e depois registra a rota no switch do servidor.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
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 |
Perguntas frequentes
Por que não usar o Express?
A skill é para servidores que já usam Node puro. Adicionar o Express mudaria a forma como todo o servidor funciona.
Como descubro qual estilo o meu servidor usa?
A skill diz para verificar o arquivo principal do servidor em busca de um switch sobre o caminho da requisição.
A rota pode ler o corpo de uma requisição?
Sim. A skill inclui um auxiliar que lê o corpo de requisições POST e PUT.
Detalhes
Descrição original do autor
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.
repo: HKUDS/AgentPilot
Popularidade
- Estrelas no GitHub
- 7,8 mil
- Posição no ranking
- #13088
- Licença
- MIT
- Atualizada em
- 01/11/2026
Comentários
- …
Mais skills deste repositório
agentpilot
7,8 milAjuda seu agente a melhorar um projeto passo a passo, preparando uma tarefa e executando o ciclo do AgentPilot, que propõe, testa e pontua mudanças.
openspace
7,8 milAjuda seu agente a configurar o OpenSpace, uma ferramenta que armazena e busca skills de agentes, e a conectá-la ao seu app de IA pelo MCP.
rsi-arena
7,8 milAjuda seu agente a configurar e rodar testes padrão de benchmark de IA, como AIME e Terminal-Bench, para comparar diferentes métodos de melhoria.
experiment-guide
7,8 milAjuda seu agente a planejar pequenos experimentos, ler seus resultados e registrar descobertas enquanto investiga como melhorar um programa.
Skills parecidas
api-connector-builder
280 milFaz seu agente construir novas conexões com APIs seguindo o padrão já existente. Use quando precisar adicionar mais uma integração sem criar um novo jeito de fazer.
api-design
280 milAjuda seu agente a projetar APIs REST seguindo as melhores práticas. É útil para definir como as APIs se comunicam, como os erros são mostrados e como organizar os dados.
backend-patterns
280 milAjuda seu agente com padrões de arquitetura do lado do servidor e otimização de banco de dados. É útil para construir ou revisar o código que roda no servidor.