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

remix-middleware

v0.1.1

Published

middleware for your remix loaders and actions

Downloads

108

Readme

remix-middleware

Add an express-like middleware stack to your remix loaders and actions!

yarn add remix-middleware
// ./app/middleware.ts
export const mdw = createMiddleware();

mdw.use(async (ctx, next) => {
  console.log("middleware activated for", ctx.request.url);
  await next();
  console.log("middleware completed for", ctx.request.url);
});

mdw.use(mdw.routes());
// ./app/routes/posts/index.tsx
import { ActionFunction, LoaderFunction, Form, useLoaderData } from "remix";

import { mdw } from "~/middleware";

interface Post {
  id: string;
  title: string;
}

export const loader: LoaderFunction = (props) =>
  mdw.run(props, (ctx) => {
    // ctx.response is where the response object goes
    ctx.response = [
      {
        id: "1",
        title: "My First Post",
      },
      {
        id: "2",
        title: "A Mixtape I Made Just For You",
      },
    ];
  });

export const action: ActionFunction = (props) =>
  mdw.run(props, async (ctx) => {
    const body = await ctx.request.formData();
    const post = { id: "3", title: body.get("title") };
    ctx.response = post;
  });

export default function Posts() {
  const posts = useLoaderData<Post[]>();
  return (
    <div>
      <h1>Posts</h1>
      <div>
        {posts.map((post) => (
          <div key={post.id}>{post.title}</div>
        ))}
      </div>
      <div>
        <Form method="post">
          <p>
            <label>
              Title: <input name="title" type="text" />
            </label>
          </p>
          <p>
            <button type="submit">Create</button>
          </p>
        </Form>
      </div>
    </div>
  );
}

Just have simple JSON that you are returning in a loader like in the example above?

export const loader: LoaderFunction = (props) =>
  mdw.run(
    props,
    mdw.response([
      {
        id: "1",
        title: "My First Post",
      },
      {
        id: "2",
        title: "A Mixtape I Made Just For You",
      },
    ])
  );

remix-auth

We built a couple middleware that will help interacting with remix-auth more streamlined.

  • isAuthenticated - activates authenticator.isAuthenticated
  • userData - automatically assigns the user object to the remix response object

Setting up remix-auth

// ./app/user.ts
export interface User {
  id: string;
  email: string;
}
// ./app/authenticator.ts
import { Authenticator } from 'remix-auth';
import { sessionStorage } from "./session";
import type { User } from './user';

export const authenticator = new Authenticator<User>(sessionStorage);

Create middleware for your needs

// ./app/middleware.ts
import { createMiddleware, AuthCtx, isAuthenticated } from 'remix-middleware';
import { authenticator } from './authenticator';
import type { User } from './user';

// use this middleware for routes that do *not* require authentication
// but you want the user to automatically redirect somewhere
export const unauthed = createMiddleware();
unauthed.use(isAuthenticated(authenticator, { successRedirect: '/dashboard' }));
unauthed.use(unauthed.routes());

// use this middleware for routes that *require* authentication
export const authed = createMiddleware<AuthCtx<User>>();
authed.use(isAuthenticated(authenticator, { failureRedirect: '/login' }));
authed.use(authed.routes());

// use this middleware if the route allows both authenticated and
// non-authenticated users
export const mdw = createMiddleware<AuthCtx<User | null>>();
mdw.use(isAuthenticated(authenticator));
mdw.use(async (ctx, next) => {
  if (ctx.user) {
    // ... do something with the user
  } else {
    // ... do something with a non-user
  }
  await next();
});

Now in your routes that require authentication

// in a route that requires auth
import { authed } from '~/middleware.ts

export const loader: LoaderFunction = (props) =>
  authed.run(props, (ctx) => {
    // no user can make it to this point without being authenticated
    // and as a result we now have access to ctx.user which is `User`
    // in this example
    console.log(ctx.user); // { id: '123', email: '[email protected]' }

    ctx.response = { text: `Hi ${ctx.user.email}!` };
  });

Now in your routes that do not require authentication

// in a route that does *not* require auth
import { authed, unauthed } from '~/middleware.ts';

// `.run()` doesn't need any middleware, it'll run without it
export const loader = (props) => unauthed.run(props);

userData middleware

import { userData } from 'remux-auth';
import { authed } from '~/middleware.ts';

// if you just want user data in the loader response
export const loader = (props) => authed.run(props, userData)
// this will automatically add `user` to the response object
// ctx.response.user = { ... }