Skip to content

nyxblabs/http-lean

Repository files navigation

cover npm version npm downloads bundle JSDocs License

⚑️ http-lean

✨ http-lean is a minimal h(ttp) framework built for high performance and portability. ⚑️

✨ Features

  • 🌐 Portable: Works perfectly in Serverless, Workers, and Node.js
  • 🌳 Minimal: Small and tree-shakable
  • πŸ”„ Modern: Native promise support
  • πŸ”§ Extendable: Ships with a set of composable utilities but can be extended
  • πŸ›£οΈ Router: Super fast route matching using nyxblabs/radix-rapid
  • 🀝 Compatible: Compatibility layer with node/connect/express middleware

πŸ“₯ Install

# nyxi
nyxi http-lean

# pnpm
pnpm add http-lean

# npm
npm install http-lean

# yarn
yarn add http-lean

πŸ“ Usage

import { createServer } from 'node:http'
import { createApp, eventHandler, toNodeListener } from 'http-lean'

const app = createApp()
app.use(
   '/',
   eventHandler(() => 'Hello world!')
)

createServer(toNodeListener(app)).listen(process.env.PORT || 3000)

Example using πŸ‘‚earlist for an elegant listener:

import { createApp, eventHandler, toNodeListener } from 'http-lean'
import { listen } from 'earlist'

const app = createApp()
app.use(
   '/',
   eventHandler(() => 'Hello world!')
)

listen(toNodeListener(app))

πŸ›£οΈ Router

The app instance created by http-lean uses a middleware stack (see how it works) with the ability to match route prefix and apply matched middleware.

To opt-in using a more advanced and convenient routing system, we can create a router instance and register it to app instance.

import { createApp, createRouter, eventHandler } from 'http-lean'

const app = createApp()

const router = createRouter()
   .get(
      '/',
      eventHandler(() => 'Hello World!')
   )
   .get(
      '/hello/:name',
      eventHandler(event => `Hello ${event.context.params.name}!`)
   )

app.use(router)

πŸ’‘ Tip: We can register the same route more than once with different methods.

Routes are internally stored in a Radix Tree and matched using nyxblabs/radix-rapid.

πŸ“š More app usage examples

// Handle can directly return object or Promise<object> for JSON response
app.use('/api', eventHandler(event => ({ url: event.node.req.url })))

// We can have better matching other than quick prefix match
app.use('/odd', eventHandler(() => 'Is odd!'), { match: url => url.substr(1) % 2 })

// Handle can directly return string for HTML response
app.use(eventHandler(() => '<h1>Hello world!</h1>'))

// We can chain calls to .use()
app.use('/1', eventHandler(() => '<h1>Hello world!</h1>'))
   .use('/2', eventHandler(() => '<h1>Goodbye!</h1>'))

// We can proxy requests and rewrite cookie's domain and path
app.use('/api', eventHandler(event => proxyRequest('https://example.com', {
   // f.e. keep one domain unchanged, rewrite one domain and remove other domains
   cookieDomainRewrite: {
      'example.com': 'example.com',
      'example.com': 'somecompany.co.uk',
      '*': '',
   },
   cookiePathRewrite: {
      '/': '/api'
   },
})))

// Legacy middleware with 3rd argument are automatically promisified
app.use(fromNodeMiddleware((req, res, next) => { req.setHeader('x-foo', 'bar'); next() }))

// Lazy loaded routes using { lazy: true }
app.use('/big', () => import('./big-handler'), { lazy: true })

πŸ› οΈ Utilities

http-lean introduces the concept of composable utilities that accept the event (from eventHandler((event) => {})) as their first argument. This approach offers several performance benefits compared to injecting them into the event or app instances in global middleware, which is commonly used in Node.js frameworks like Express. By using composable utilities, only the required code is evaluated and bundled, allowing the rest of the utilities to be tree-shaken when not used. πŸ› οΈπŸŒ³βš‘οΈ

βš™οΈ Built-in

  • πŸ“– readRawBody(event, encoding?)
  • πŸ“– readBody(event)
  • πŸͺ parseCookies(event)
  • πŸͺ getCookie(event, name)
  • πŸͺ setCookie(event, name, value, opts?)
  • πŸͺ deleteCookie(event, name, opts?)
  • ❓ getQuery(event)
  • πŸ›£οΈ getRouterParams(event)
  • πŸ“€ send(event, data, type?)
  • πŸ”„ sendRedirect(event, location, code=302)
  • πŸ“₯ getRequestHeaders(event, headers) (alias: getHeaders)
  • πŸ“₯ getRequestHeader(event, name) (alias: getHeader)
  • πŸ“€ setResponseHeaders(event, headers) (alias: setHeaders)
  • πŸ“€ setResponseHeader(event, name, value) (alias: setHeader)
  • πŸ“€ appendResponseHeaders(event, headers) (alias: appendHeaders)
  • πŸ“€ appendResponseHeader(event, name, value) (alias: appendHeader)
  • πŸ“œ writeEarlyHints(event, links, callback)
  • πŸ“€ sendStream(event, data)
  • ❗ sendError(event, error, debug?)
  • πŸ“₯ getMethod(event, default?)
  • ❓ isMethod(event, expected, allowHead?)
  • ❗ assertMethod(event, expected, allowHead?)
  • 🚫 createError({ statusCode, statusMessage, data? })
  • πŸ”„ sendProxy(event, { target, ...options })
  • πŸ”„ proxyRequest(event, { target, ...options })
  • 🌐 fetchWithEvent(event, req, init, { fetch? })
  • 🌐 getProxyRequestHeaders(event)
  • πŸ“€ sendNoContent(event, code = 204)
  • πŸ“€ setResponseStatus(event, status)
  • πŸ“₯ getResponseStatus(event)
  • πŸ“₯ getResponseStatusText(event)
  • πŸ“– readMultipartFormData(event)
  • πŸ”„ useSession(event, config = { password, maxAge?, name?, cookie?, seal?, crypto? })
  • πŸ”„ getSession(event, config)
  • πŸ”„ updateSession(event, config, update)
  • πŸ”„ clearSession(event, config)
  • πŸ”„ sealSession(event, config)
  • πŸ”„ unsealSession(event, config, sealed)
  • πŸ”„ handleCors(options) (see h3-cors for more detail about options)
  • ❓ isPreflightRequest(event)
  • ❓ isCorsOriginAllowed(event)
  • πŸ”„ appendCorsHeaders(event, options) (see h3-cors for more detail about options)
  • πŸ”„ appendCorsPreflightHeaders(event, options) (see h3-cors for more detail about options)
  • 🌐 getRequestHost(event)
  • 🌐 getRequestProtocol(event)
  • 🌐 getRequestURL(event)

πŸ‘‰ You can learn more about usage in JSDocs Documentation.

πŸ“¦ Community Packages

You can use more http-lean event utilities made by the community.

Please check their READMEs for more details.

PRs are welcome to add your packages.

πŸ“œ License

MIT - Made with πŸ’ž