Skip to content

Instantly share code, notes, and snippets.

@klarstrup
Last active September 7, 2025 15:24
Show Gist options
  • Select an option

  • Save klarstrup/5b63772d9fddb5a24fa05b99c8ed63e8 to your computer and use it in GitHub Desktop.

Select an option

Save klarstrup/5b63772d9fddb5a24fa05b99c8ed63e8 to your computer and use it in GitHub Desktop.
import { Router } from "express";
export function LazyRouter(
loader: () => Promise<{ default: Router }>,
{ preload }: { preload?: boolean } = {}
) {
const loadRouter = () => (router ||= loader().then((m) => m.default));
let router: Promise<Router> | null = preload ? loadRouter() : null;
return Router().use((req, res, next) =>
loadRouter()
.then((r) => r(req, res, next))
.catch(next)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment