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

@express-worker/app

v1.4.0

Published

Express-style routing for Service Workers

Downloads

74

Readme

Express.js ported to a Service Worker context

What is ExpressWorker?

ExpressWorker provides a simple Express.js-like API for handling requests inside a Service Worker.

Installation

Create an ExpressWorker app instance at the top level of a service worker file:

import { ExpressWorker } from '@express-worker/app';

const app = new ExpressWorker();

app.get('/', (req, res) => {
  res.send('Hello world!');
});

After registering the service worker, ExpressWorker will handle all requests.

Serving Dynamic Pages

You can use Express-style path params and a server-side templating engine such as react-dom/server to produce dynamic HTML output.

For example:

import { renderToString } from 'react-dom/server';

app.get('/cats/:id', (req, res) => {
  const renderResult = renderToString(<CatPage id={req.params.id} />);
  res.send(`<!DOCTYPE html>${renderResult}`);
});

Serving Static Resources

By default, non-matching requests are forwarded to the network, which can be slow. To improve performance, you can cache static resources in the install event handler and create GET handlers to serve them from the cache.

Here's a simplified example, but you will likely need a more robust solution that handles cache invalidation and versioning:

const URLS_TO_CACHE = ['client.js', 'manifest.json', 'style.css'];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => cache.addAll(URLS_TO_CACHE)),
  );
});

const handleStaticFile = (req, res) => {
  const cache = await caches.open('v1');
  const cachedResponse = await cache.match(new URL(req.url).pathname);

  if (cachedResponse) {
    res.status = cachedResponse.status;

    for (const [key, value] of cachedResponse.headers.entries()) {
      res.set(key, value);
    }

    const body = await cachedResponse.text();

    res.send(body);
  } else {
    res.status = 404;
    res.send('Not found in cache.');
  }

  res.end();
};

for (const url of URLS_TO_CACHE) {
  app.get(url, handleStaticFile);
}

Serving a 404 Page

Register a catch-all handler to serve a 404 page for all unhandled requests.

app.get('*', (req, res) => {
  res.status = 404;
  res.send('Not found!');
});

Applying Middleware

Middleware handlers are called before other request handlers, so they can be used to add properties to req that will be present downstream.

Here's a simple middleware handler to normalize FormData as req.data:

app.use(function FormDataMiddleware(req) {
  if (req.headers.get('Content-Type') === 'multipart/form-data') {
    req.data = Object.fromEntries(Array.from(req.formData.entries())).map(
      ([key, value]) => [key, value.toString()],
    );
  }
});

Here's a simple middleware handler to normalize the query string as req.query:

app.use(function QueryStringMiddleware(req) {
  const url = new URL(req.url);
  req.query = Object.fromEntries(Array.from(url.searchParams.entries()));
});

If you add additional properties to req, then you can wrap handlers with the static applyAdditionalRequestProperties method to make TypeScript aware of them:

import { ExpressWorker } from '@express-worker/app';

app.get(
  '/cats/:id',
  ExpressWorker.applyAdditionalRequestProperties<{
    data: Record<string, string>;
    query: Record<string, string>;
  }>((req, res) => {
    // TypeScript now knows these are defined.
    console.log(req.query);
    console.log(req.data);

    // TypeScript is still aware of `req.params`.
    console.log(req.params.id);
  }),
);

Differences from Express

  • req works like native Request with appended params property.
  • res has the following Express-like methods:
    • send()
    • text()
    • html()
    • json()
    • blob()
    • redirect()
    • status()
    • end()
  • No support for next() function.
  • No need for listen() method.
  • No support for rendering engines or other advanced features.

Examples

  • https://github.com/michaelcpuckett/listleap

See Also

  • https://github.com/jcubic/wayne/