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 🙏

© 2024 – Pkg Stats / Ryan Hefner

wowter

v1.0.11

Published

It's a really simple, barebones router for node.js. It's called wowter because that's what it sounds like when a cute child tries to say router, and the design is so naive and simple that it's like a child made it.

Downloads

28

Readme

Wowter 😲

A simple router for node.js

A VERY barebones router for node.js. It's called wowter because that's what it sounds like when a cute child tries to say router, and the design is so naive and simple that it's like a child made it.

Installation

npm install wowter || yarn add wowter || pnpm add wowter || bun install wowter

Usage

Examples

  1. Basic Setup Creating a simple HTTP server with wowter is very straightforward. You define your routes, handlers, and then create the server.
import { createRouter } from "wowter"

const homeHandler = (req, res) => {
  res.writeHead(200, { "Content-Type": "application/json" })
  res.end(JSON.stringify({ message: "Welcome to the home page!" }))
}

const routes = {
  "/": { GET: { handler: homeHandler } },
}

const server = createRouter({ routes })

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000")
})
  1. Middleware Middleware functions operate on every request. They are powerful tools for doing things like logging, authentication, and more.

a. Global Middleware You can apply middleware globally to every route by providing an array of middleware functions in the createRouter options.

import { createRouter } from "wowter"

const logMiddleware = (req, res, next) => {
  console.log(`Incoming request: ${req.method} ${req.url}`)
  next()
}

const middleware = [logMiddleware]

const routes = {
  "/": { GET: { handler: homeHandler } },
}

const server = createRouter({ routes, middleware })

server.listen(3000, () => {
  console.log("Server running with global middleware at http://localhost:3000")
})

b. Grouped Middleware If you have a group of routes that need to share some middleware, you can use applyMiddleware to add middleware to a specific set of routes.

import { createRouter, applyMiddleware } from "wowter"

const apiRoutes = {
  "/api/users": { GET: { handler: getUsersHandler } },
  "/api/posts": { GET: { handler: getPostsHandler } },
}

const apiMiddleware = [apiAuth, apiLogging]

const groupedRoutes = applyMiddleware(apiRoutes, apiMiddleware)

const server = createRouter({ routes: groupedRoutes })

server.listen(3000)

c. Route-Specific Middleware You can also define middleware specifically for one route:

const routes = {
  "/secret": {
    GET: {
      handler: secretHandler,
      middleware: [authenticationMiddleware],
    },
  },
}

const server = createRouter({ routes })
  1. Serving Static Files To serve static files from a folder, simply provide the dir option when creating the router.
const server = createRouter({
  routes,
  dir: "./public",
})

server.listen(3000)

This will automatically serve files from the ./public folder for routes that are not defined.

  1. Custom 404 Handling Handling 404 errors can be done in a number of ways.

a. Global 404 To set up a global 404 handler, you can pass a notFound function as an option.

const notFoundHandler = (req, res) => {
  res.writeHead(404, { "Content-Type": "application/json" })
  res.end(JSON.stringify({ message: "Resource not found" }))
}

const server = createRouter({
  routes,
  notFound: notFoundHandler,
})

b. Static Folder 404

If you have a 404.html file in your static folder, it will be automatically served if a file is not found.

  1. Dynamic Routes Dynamic routes capture part of the URL as a parameter. These parameters can be accessed in the route handler.
const routes = {
  "/users/:userId": { GET: { handler: userHandler } },
}

In the userHandler, req.params.userId would hold the dynamic part of the URL.

  1. Easy Query Params Query parameters can easily be accessed through req.query. For example, for a request to /search?q=example, req.query.q would be 'example'.
const searchHandler = (req, res) => {
  const query = req.query.q
  // Do something with the query
}

const routes = {
  "/search": { GET: { handler: searchHandler } },
}

API Reference

createRouter(options)

Creates a Node.js HTTP server that handles routing.

  • Arguments:

    • options (RouterOptions): An options object passed to set up the router.
  • Returns: A Node.js Server instance.

Router(req, res, options)

Central router function that's called for every request.

  • Arguments:

    • req (ExtendedRequest): The Node.js request object with additional properties (query, params).
    • res (ServerResponse): The Node.js response object.
    • options (RouterOptions): Options for routing.
  • Returns: Promise

applyMiddleware(routes, extraMiddleware)

Adds middleware to every route in a Routes object.

  • Arguments:

    • routes (Routes): Object with routes and their configurations.
    • extraMiddleware (Array): Array of middleware functions to be applied.
  • Returns: Routes - A new routes object with the extra middleware applied.

Types

ExtendedRequest

The Node.js request object with additional properties:

  • query (Object.<string, string | string[] | undefined>): Represents the query parameters of the URL.
  • params (Object.<string, string | undefined>): Represents dynamic route parameters.

RouterOptions

Options object for setting up the router:

  • routes (Routes): An object with routes as keys and RouteConfig objects as values.
  • middleware (Array): An array of functions that will operate on every request.
  • dir (string): The directory to serve static files from.
  • notFound (Function): A custom 404 handler. If not provided, a default 404 handler will be used.

RouteConfig

Configuration for a specific route:

  • handler (Function): The main handler function for the route.
  • middleware (Array): Array of middleware functions specific to the route.

Routes

An object where the keys are paths and the values are objects mapping HTTP methods to RouteConfig.

Example:

Middleware

Functions

parseCookies(cookieString: string): Object

Parses cookies from the Cookie HTTP header.

Parameters:

  • cookieString: A string containing the raw cookies from the HTTP header.

Returns:

  • An object containing parsed cookies.

errorCheck(req: Request, res: Response, next: Function): void

Checks for the existence of a query parameter error=true and sends a 500 status code if found.

Parameters:

  • req: HTTP request object.
  • res: HTTP response object.
  • next: Callback function to proceed to the next middleware.

logger(req: Request, res: Response, next: Function): void

Logs incoming HTTP requests.

Parameters:

  • req: HTTP request object.
  • res: HTTP response object.
  • next: Callback function to proceed to the next middleware.

rateLimiter(req: Request, res: Response, next: Function): void

Limits the rate of incoming HTTP requests based on IP address.

Parameters:

  • req: HTTP request object.
  • res: HTTP response object.
  • next: Callback function to proceed to the next middleware.

urlEncodedParser(req: Request, res: Response, next: Function): void

Parses application/x-www-form-urlencoded POST data.

Parameters:

  • req: HTTP request object.
  • res: HTTP response object.
  • next: Callback function to proceed to the next middleware.

JSONParser(req: Request, res: Response, next: Function): void

Parses JSON POST data.

Parameters:

  • req: HTTP request object.
  • res: HTTP response object.
  • next: Callback function to proceed to the next middleware.

CORS(options?: CORSOptions): Function

Enables Cross-Origin Resource Sharing (CORS).

Parameters:

  • options: Optional configuration options. See CORSOptions.

Returns:

  • Middleware function for enabling CORS.

fileUpload(options?: FileUploadOptions): Function

Handles file uploads.

Parameters:

Returns:

  • Middleware function for handling file uploads.

Type Definitions

CORSOptions

  • allowedOrigins: String or Array of Strings, default "*"
  • allowedMethods: Array of Strings, default ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
  • allowedHeaders: Array of Strings, default ["Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"]
  • allowCredentials: Boolean, default true
  • preflightContinue: Boolean, default false
  • maxAge: Number, default 600
  • exposedHeaders: Array of Strings, default []

FileUploadOptions

  • MAX_SIZE: Number, default 5242880 (5MB)
  • allowedTypes: Array of Strings or null, default null
  • onFileBegin: Function or null, default null
  • onError: Function or null, default null
  • onEnd: Function or null, default null
  • tempFileDir: String or null, default null