npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

rapiserver

v2.1.1

Published

API con Bun, Hono y rutas dinámicas

Readme

⚡ Rapiserver – APIs ultrarrápidas con Bun + Hono + Routing por archivos

Rapiserver es una librería minimalista para crear APIs modernas con Bun y Hono, sin routers manuales ni configuración innecesaria.
Sólo define archivos y carpetas. Nosotros hacemos el resto. 🙌


📚 Tabla de contenido


🚀 ¿Qué hace Rapiserver?

  • 📁 Cada archivo .ts es una ruta HTTP (get.ts, post.ts, etc.)
  • 🧱 Cada carpeta puede tener su propio middleware (_middleware.ts)
  • 🧠 OpenAPI se genera automáticamente
  • 🏁 Servidor arranca en menos de 3 ms
  • ✅ 100% compatible con TypeScript
  • 🪄 Routing automático con soporte para rutas dinámicas como [id]

🧰 Instalación

bun add rapiserver

Requiere tener Bun instalado


📁 Estructura mínima recomendada

src/
├── api/                     # Aquí defines tus endpoints
│   ├── ping/get.ts          # GET /ping
│   └── user/[id]/get.ts     # GET /user/:id
├── middleware/              # Middlewares reutilizables opcionales
│   └── auth.ts              # Puedes importarlos en cualquier _middleware.ts
├── scripts/                 # Scripts útiles (como openapi)
└── index.ts                 # Punto de entrada del servidor
  • api/: contiene todos tus endpoints organizados por carpeta. Cada archivo representa un método HTTP.
  • middleware/: no necesita configuración. Úsala para mantener middlewares reutilizables y luego impórtalos desde los _middleware.ts en cada carpeta de api/.
  • scripts/: para utilidades como generación de OpenAPI.
  • index.ts: inicializa el servidor llamando a createServer.

✨ Crear una ruta

// src/api/ping/get.ts
import type { Context } from 'rapiserver';

export default async function handler(ctx: Context) {
  return ctx.text('pong');
}
  • El nombre del archivo define el método HTTP.
  • La ubicación define el path.
  • handler viene tipado desde Rapiserver.

🔐 ¿Qué es un middleware?

Un middleware es una función que se ejecuta antes del handler de la ruta. Sirve para tareas como:

  • Autenticación
  • Validación de datos
  • Agregar cabeceras
  • Logging

🛡️ Ejemplo de middleware

// src/middleware/auth.ts
import type { Context, Next, Middleware } from 'rapiserver';

export default async function auth(ctx: Context, next: Next) {
  console.log('🔐 Usuario autenticado');
  return await next();
}

📦 Aplicar un middleware a una carpeta

// src/api/private/_middleware.ts
import auth from '../../middleware/auth';

export default [auth]; // se aplicará a todas las rutas dentro de /private
// src/api/private/profile/get.ts
import type { Context } from 'rapiserver';

export default async function handler(ctx: Context) {
  return ctx.json({ message: 'Perfil privado' });
}

📌 Rutas dinámicas

Puedes usar rutas como [id], que se transforman automáticamente en :id.

// src/api/user/[id]/get.ts
import type { Context } from 'rapiserver';

export default async function handler(ctx: Context) {
  const id = ctx.req.param('id');
  return ctx.json({ userId: id });
}

🧠 Tipos incluidos

Rapiserver exporta los tipos necesarios para que no tengas que importar nada desde hono:

import type { Context, Next, Middleware } from 'rapiserver';
  • Context: el objeto de la petición/respuesta
  • Next: función para continuar al siguiente middleware
  • RouteHandler: tipo para handlers de rutas
  • Middleware: tipo para middlewares

🧪 Iniciar el servidor

// src/index.ts
import { createServer } from 'rapiserver';

export default async function start() {
  createServer({
    production: process.env.NODE_ENV,
    port: 3000,
    apiFolder: 'src/api',
  });
}

start();

Ejecuta en modo desarrollo:

bun src/index.ts

📚 ¿Cómo generar openapi.json?

Rapiserver expone una función generateOpenAPI() que puedes usar desde tu proyecto para generar documentación automática.

  1. Crea el archivo scripts/openapi.ts:
// scripts/openapi.ts
import { generateOpenAPI } from 'rapiserver';

export default async function gen() {
  await generateOpenAPI('src/api');
}
  1. Añade el script en tu package.json:
"scripts": {
  "generate:openapi": "bun scripts/openapi.ts"
}
  1. Ejecuta el script:
bun run generate:openapi

✨ Personalización por handler

Dentro de cualquier ruta, puedes exportar un objeto openapi:

export const openapi = {
  summary: 'Obtener perfil del usuario',
  responses: {
    200: {
      description: 'Perfil cargado correctamente',
    },
  },
};

Esto se incluirá automáticamente en el archivo generado.


🧩 Comandos útiles

bun dev                     # Modo desarrollo con hot reload
bun run build               # Compilar para producción
bun run serve               # Iniciar en modo producción
bun run generate:openapi    # Generar openapi.json para Swagger

🚀 Empezar rápido

bun add rapiserver
// src/index.ts
import { createServer } from 'rapiserver';

export default async function start() {
  createServer({
    port: 3000,
    apiFolder: 'src/api',
  });
}

start();
// src/api/hello/get.ts
import type { Context } from 'rapiserver';

export default async function handler(ctx: Context) {
  return ctx.text('Hola mundo');
}
bun src/index.ts

Accede a: http://localhost:3000/hello


🙋‍♂️ ¿Dudas frecuentes?

  • ¿Qué pasa si tengo rutas dinámicas como [id]? → Rapiserver las convierte automáticamente en :id.

  • ¿Puedo usar middlewares por ruta? → No directamente, pero puedes componerlos dentro del mismo archivo o handler.

  • ¿Puedo añadir validaciones? → Sí, puedes usar zod, valibot, yup o cualquier librería dentro de tus handlers o middlewares.

  • ¿Puedo usar Rapiserver con Node.js? → No. Está diseñado para correr solo en el runtime Bun.


📄 Licencia

MIT © 2025 – David Dávila


Disfruta creando APIs en segundos con ⚡ Rapiserver


---