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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@cortec/polka

v2.6.4

Published

<description>

Readme

@cortec/polka

Module Overview

@cortec/polka provides a robust HTTP server framework built on Polka, designed for modular, scalable APIs. It integrates seamlessly with other Cortec modules for logging, error handling, authentication, rate limiting, and more. The package supports middleware such as CORS, Helmet, compression, and body parsing, and is designed to work with a configuration-driven approach.

Configuration Options

Where to put config: Place your Polka config in config/default.yml (or your environment-specific config file).

Schema/Structure:

polka:
  cors: # CORS middleware options
    origin: '*' # Allowed origins (string or array)
    methods: ['GET', 'POST'] # Allowed HTTP methods
    credentials: false # Allow credentials (optional)
  helmet: # Helmet security middleware options
    contentSecurityPolicy: false
    # ...other helmet options
  compression: # Compression middleware options
    threshold: 1024 # Minimum response size to compress (bytes)
  bodyParser: # Body parser options for different content types
    json:
      limit: '1mb' # Max JSON body size
    raw: {} # Options for raw body parsing
    text: {} # Options for text body parsing
    urlencoded:
      extended: true # Use extended query string parsing

Field-by-field explanation:

  • polka: Root key for Polka config.
  • cors: CORS options.
    • origin: Allowed origins (string, array, or boolean).
    • methods: Allowed HTTP methods (array of strings).
    • credentials: Allow credentials (boolean, optional).
    • Other options as per CORS middleware.
  • helmet: Helmet options for HTTP header security.
    • contentSecurityPolicy: Enable/disable CSP (boolean).
    • Other options as per Helmet middleware.
  • compression: Compression options.
    • threshold: Minimum response size to compress (bytes).
    • Other options as per compression middleware.
  • bodyParser: Options for parsing request bodies.
    • json: Options for JSON bodies (e.g., limit for max size).
    • raw: Options for raw bodies.
    • text: Options for text bodies.
    • urlencoded: Options for URL-encoded bodies (e.g., extended).

Example YAML configuration:

polka:
  cors:
    origin: '*'
    methods: ['GET', 'POST']
    credentials: false
  helmet:
    contentSecurityPolicy: false
  compression:
    threshold: 1024
  bodyParser:
    json:
      limit: '1mb'
    raw: {}
    text: {}
    urlencoded:
      extended: true

How config is loaded: The config is loaded automatically by the @cortec/config module and validated at runtime. Access it in code via:

const config = ctx.provide<IConfig>('config');
const polkaConfig = config?.get<any>('polka');

If config is missing or invalid, an error is thrown at startup.

Example Usage

Below is a minimal example of how to use the Polka module in a Cortec context:

import Polka from '@cortec/polka';
import { route } from '@cortec/polka/types';

// Define your router
const router = (app, ctx) => {
  app.get(
    '/hello',
    route({
      onRequest: async (req, ctx) => ({
        status: 200,
        body: { message: 'Hello, world!' },
      }),
    })
  );
};

// Create the Polka module
const polkaModule = new Polka(router);

// Register with Cortec context
context.use(polkaModule);

// After context.load(), you can get the HTTP handler:
const handler = polkaModule.handler();

Features

  • Error Handling: Integrated with NewRelic, Sentry, and custom error classes.
  • Rate Limiting: Supports Redis-backed rate limiting per route.
  • Body Parsing: Configurable for JSON, raw, text, and URL-encoded bodies.
  • Security: Helmet middleware for HTTP header protection.
  • CORS: Configurable cross-origin resource sharing.
  • Static Files: Easily serve static assets via app.static(path, dir, options).

Advanced Example: Route with Rate Limiting and Validation

app.post(
  '/api/data',
  route({
    schema: {
      body: z.object({ foo: z.string() }),
    },
    rateLimit: {
      cache: 'main', // Redis cache name
      duration: 60, // seconds
      limit: 100, // requests per duration
      count: (ctx, req, reqCtx) => reqCtx.session?.userId ?? 'anonymous',
    },
    onRequest: async (req, ctx) => ({
      status: 201,
      body: { received: req.body.foo },
    }),
  })
);

Notes

  • The Polka module expects to be loaded in a Cortec context with required dependencies (logger, sentry, newrelic, redis, etc.).
  • Error responses are standardized and traceable via trace IDs.
  • For full type definitions and advanced usage, see the source code and exported types in src/types.ts.