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

vite-plugin-cloudflare-router

v0.2.2

Published

A file-based router for Cloudflare Workers

Downloads

75

Readme

A file-based router for Cloudflare Workers.

Quickstart

Install

npm install -D vite-plugin-cloudflare-router

Setup

vite.config.ts

import { defineConfig } from 'vite';
import { cloudflare } from '@cloudflare/vite-plugin';
import cloudflareRouter from 'vite-plugin-cloudflare-router';

export default defineConfig({
  plugins: [
    cloudflare(),
    cloudflareRouter(),
  ],
});

tsconfig.json

{
  "extends": "./.cloudflare-router/tsconfig.json",
}

Usage

Example project structure:

.
├── src/
│   ├── routes/
│   │   └── index.ts      -> Route handler
│   └── index.ts          -> Cloudflare Workers entry point
└── package.json

Cloudflare Workers entry point

// src/index.ts
import { routes } from 'virtual:cloudflare-router';
import { createRouter } from 'vite-plugin-cloudflare-router/runtime';

const router = createRouter(routes);

export default router;

Route handler

// src/routes/index.ts
export const GET = () => {
  return new Response('ok');
};

Routing Conventions

Every route is defined as a folder with an index.ts file.

Basic

routes/
├── index.ts               -> /
└── api/
    └── index.ts           -> /api

Nested Routes

A . in a folder name becomes a / in the URL.

routes/
├── index.ts               -> /
├── api/
│   └── index.ts           -> /api
└── api.users/
    └── index.ts           -> /api/users

Dynamic Segments

Wrap a parameter name with [] to make a dynamic segment.

routes/
├── index.ts               -> /
├── api/
│   └── index.ts           -> /api
├── api.users/
│   └── index.ts           -> /api/users
└── api.users.[id]/
    └── index.ts           -> /api/users/:id

Catch-all

Use [...] in a folder name to catch the rest of the path.

routes/
├── index.ts               -> /
├── api/
│   └── index.ts           -> /api
├── api.users/
│   └── index.ts           -> /api/users
├── api.users.[id]/
│   └── index.ts           -> /api/users/:id
└── api.docs.[...slug]/
    └── index.ts           -> /api/docs/* (catch-all)

Colocated Modules

Only the index.ts file directly under the route folder (e.g. /api.users.[id]/index.ts) is a route. Any other file — including files in subfolders — is a colocated module, not a route.

routes/
├── index.ts               -> /
├── api/
│   └── index.ts           -> /api
├── api.users/
│   └── index.ts           -> /api/users
├── api.users.[id]/
│   ├── index.ts           -> /api/users/:id
│   └── shared/
│       ├── index.ts       -> colocated module
│       └── schema.ts      -> colocated module
└── api.docs.[...slug]/
    └── index.ts           -> /api/docs/* (catch-all)

Route Handlers

To handle an incoming request, export a function named after the HTTP method.

export const GET = () => {};

export const POST = () => {};

export const PATCH = () => {};

export const PUT = () => {};

export const DELETE = () => {};

A route handler receives one argument with the following properties:

  • request: The incoming HTTP request.
  • env: The bindings available to the Worker.
  • executionContext: The Worker's execution context.
  • params: Parameters for the route.
// e.g. GET /api/users/123
export const GET = (c: {
  request: Request;
  env: Env;
  executionContext: ExecutionContext;
  params: { id: string };
}) => {
  return new Response(c.params.id); // '123'
};

The example above is a bare-bones route handler, use defineHandler instead.

defineHandler

To define a route handler, use defineHandler().

defineHandler infers types for you, including dynamic params. .handle() takes the same arguments as above.

import { defineHandler } from './+types';

export const GET = defineHandler()
  .handle((c) => {
    return new Response(c.params.id);
  });

Note that the import specifier is ./+types. This plugin auto-generates types when running a Vite dev server.

Middleware

Middleware runs before and after the route handler. It allows you to prepare the request and post-process the response.

defineMiddleware

To create a middleware, use defineMiddleware(). Call next() to continue to the next middleware or route handler.

import { defineMiddleware } from './+types';

export const middleware = defineMiddleware()
  .handle((_c, next) => {
    return next();
  });

To use middleware, use .use() method.

export const GET = defineHandler()
  .use(middleware)
  .handle(() => {
    return new Response('ok');
  });

To apply multiple middlewares, chain the .use() method.

export const GET = defineHandler()
  .use(middleware1)
  .use(middleware2)
  .use(middleware3)
  .handle(() => {
    return new Response('ok');
  });

next() accepts arbitrary data as an argument. This data will be merged onto the handler's context and passed down to the route handler.

const middleware = defineMiddleware()
  .handle((_c, next) => {
    return next({ message: 'ok' });
  });

export const GET = defineHandler()
  .use(middleware)
  .handle((c) => {
    return new Response(c.message); // 'ok'
  });

A middleware must always return a response.

To continue the chain, return next(). To post-process the response, await the response from next() and then return it.

const middleware = defineMiddleware()
  .handle(async (c, next) => {
    // Simply return
    return await next();

    // or
    const response = await next();
    // post-process the response
    // e.g. response.headers.set('x-custom-header', 'hello');
    // and then return the response
    return response;
  });

Execution Order

Middleware runs in the order in which they were registered.

const middleware1 = defineMiddleware()
  .handle(async (c, next) => {
    console.log('Middleware 1 start');
    const response = await next();
    console.log('Middleware 1 end');
    return response;
  });

const middleware2 = defineMiddleware()
  .handle(async (c, next) => {
    console.log('Middleware 2 start');
    const response = await next();
    console.log('Middleware 2 end');
    return response;
  });

const middleware3 = defineMiddleware()
  .handle(async (c, next) => {
    console.log('Middleware 3 start');
    const response = await next();
    console.log('Middleware 3 end');
    return response;
  });

export const GET = defineHandler()
  .use(middleware1)
  .use(middleware2)
  .use(middleware3)
  .handle((c) => {
    console.log('Handler called');
    return new Response('ok');
  });

Output:

Middleware 1 start
  Middleware 2 start
    Middleware 3 start
      Handler called
    Middleware 3 end
  Middleware 2 end
Middleware 1 end

⬆️ Back to top