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

flow-middleware

v0.2.3

Published

Run Express middlewares on any Node.js server framework without hacking/polluting native `req`/`res` objects with Proxy.

Downloads

17

Readme

flow-middleware Node CI npm version

Run Express middlewares on any Node.js server framework without hacking/polluting native req/res objects with Proxy.

Checkout the Next.js example with Passport.js integration.

Why

As people start using a new Node server library other than Express, they encounter a lack of middlewares that Express already has, which have been well tested and production-ready many years ago. Some of them try to shape a brand new ecosystem on the new island and some just go back to Express.

Let's start from admitting Express is one of the most successful, beautifully designed and battle-tested software in the Node ecosystem. Don't forget its hundreds of outstanding middlewares have been born on it. Then why you can't use them? The answers will be summarized:

  • It breaks since they depend on req.param() and res.redirect() that Express decorates native objects with. I don't want to hack to make them work in my ${Your favorite server comes here}.
  • Pollution. Express officially recommends middlewares to extend object properties such as req.session and req.flash, just where my ${Your favorite server} leaves them tidy. Plus, dynamic extensions don't fit today of the TypeScript era.

Yeah. Let's move on.

How

JavaScript Proxy.

Wrapping req and res by Proxy to split using native methods and Express methods. Express exports clean prototypes that we can intercept internal calls with. It lets middlewares to call native methods like res.writeHead() and res.end() so native objects properly embed HTTP info and send the response.

In the end, flow-middleware returns the extended properties like req.session and req.user so you can use them after the middlewares go through.

flow-middleware architecture

Getting started

Install it with Express.

yarn add flow-middleware express

flow(...middlewares)

A function flow creates an http handler from some Express middlewares, processed from left to right of arguments.

import flow from 'flow-middleware';
import { ok } from "assert";
import { createServer } from 'http';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import flash from 'express-flash';

// Creates an async function that handles req and res.
const handle = flow(
    cookieParser(),
    session({ secret: 'x' }),
    flash(),
    (reqProxy, _resProxy, next) => {
    
        // Our wrapped objects provide accessors
        // that Express middlewares extended💪
        ok(reqProxy.cookies);
        ok(reqProxy.session);
        ok(reqProxy.flash);
        next();
    }
);

createServer(async (req, res) => {
  
    // Let's run the Express middlewares🚀
    const [ reqProxy, resProxy ] = await handle(req, res);

    // Native objects are clean thanks to our proxy✨
    ok(req.cookies === undefined);
    ok(req.session === undefined);
    ok(req.flash === undefined);

    // You still can access to Express properties here🚚
    ok(reqProxy.cookies);
    ok(reqProxy.session);
    ok(reqProxy.flash);
    ok(resProxy.cookie);
    ok(resProxy.redirect);

    res.end('Hello!');
}).listen(3000);

compose(...middlewares)(...middlewares)()

compose lets you hold a set of middlewares and share it on other routes. This is useful when you want the same initializing middlewares to come first while the different middlewares come at the end. Calling it with zero arguments returns a handler function.

This is a Passport example where a login handler for POST /api/auth/github and an OAuth callback handler for GET /api/auth/callback/github share their initializing middlewares.

import cookieSession from 'cookie-session';
import { compose } from 'flow-middleware';
import passport from './passport';

const composed = compose(
    cookieSession(),
    passport.initialize(),
    passport.session()
);

const handleToLogIn = composed(passport.authenticate('github'))();

const handleForCallback = composed(passport.authenticate('github', {
    failureRedirect: '/auth',
    successRedirect: '/',
}))();

Don't forget to call it with zero arguments at last to get a handler.

Wrapper function style

Or, you can simply write a wrapper function to share middlewares.

import { Handler } from 'express';

function withPassport(...middlewares: Handler[]) {
    return flow(
        cookieSession(),
        passport.initialize(),
        passport.session(),
        ...middlewares
    );
}

License

MIT

Author

Soichi Takamura <[email protected]>