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

@shajib729/auth-kit

v1.0.0

Published

A unified, strategy-based authentication middleware system for Express. Supporting Google OAuth, Credentials, and custom authentication strategies with a single onAuthenticate callback interface.

Readme

auth-kit

A unified, strategy-based auth system for Express. Google OAuth, credentials, GitHub, anything else — every strategy resolves to the same result shape, and you decide what happens next in one place.

npm install @shajib729/auth-kit

The core idea

Authenticating with Google and authenticating with email/password are fundamentally different processes — but what your server does after either succeeds is usually identical: look up or create a user, issue a session, redirect or respond. Most auth libraries blur this line and you end up with provider-specific glue code scattered across routes.

auth-kit splits it cleanly into two layers:

| Layer | Responsibility | Where it lives | |---|---|---| | Strategy | Talk to the provider, return a normalized user | strategies/*.js | | AuthKit | Wire strategies to routes, call your hook | core/AuthKit.js | | Your hook | Decide what "logged in" means for your app | your code |

Every strategy, no matter how different internally, resolves to exactly this:

{
  provider: "google",        // or "credentials", "github", ...
  user: {
    id, email, name, picture, emailVerified
  },
  raw: { /* untouched provider payload, for anything custom */ }
}

Your onAuthenticate hook receives this shape every time, regardless of which strategy ran. Add a GitHub strategy next month — your hook doesn't change at all.


Quick start

import express from "express"
import jwt from "jsonwebtoken"
import { AuthKit, GoogleStrategy, CredentialsStrategy } from "auth-kit"

const google = new GoogleStrategy({
  clientID:     process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  redirectURI:  "http://localhost:8000/auth/google/callback",
})

const credentials = new CredentialsStrategy({
  // YOU control persistence — Postgres, Mongo, anything
  verify: async ({ email, password }) => {
    const row = await db.users.findByEmail(email)
    if (!row) return null
    const valid = await CredentialsStrategy.compare(password, row.passwordHash)
    return valid ? row : null
  },
})

const authKit = new AuthKit({
  strategies: { google, credentials },

  // Called after ANY strategy succeeds — same shape every time
  onAuthenticate: async (result, req, res) => {
    const { provider, user } = result
    const token = jwt.sign({ id: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: "1d" })

    if (provider === "google") {
      return res.redirect(`http://localhost:3000/auth/callback?token=${token}`)
    }
    res.json({ token, user })
  },

  onError: (err, req, res) => {
    res.status(err.status ?? 500).json({ error: err.message, code: err.code })
  },
})

const app = express()
app.use(express.json())

app.get("/auth/google",          authKit.initiate("google"))
app.get("/auth/google/callback", authKit.complete("google"))
app.post("/auth/login",          authKit.complete("credentials"))

Notice: initiate() and complete() are the same two calls for every strategy. The only thing that changes per-provider is which string you pass.


Strategies included

GoogleStrategy

new GoogleStrategy({
  clientID,       // required
  clientSecret,   // required
  redirectURI,    // required
  scopes,         // default: ["email", "profile"]
  accessType,     // "offline" | "online", default "offline"
  prompt,         // default "consent"
})

result.raw contains { profile, tokens } — the full Google profile and token response, in case you need fields beyond the normalized set (e.g. locale, or the Google refresh_token to call Google APIs later).

CredentialsStrategy

new CredentialsStrategy({
  verify: async ({ email, password }, req) => {
    // Return a user object, or null/undefined if invalid.
    // Throwing here is treated as a 500 (DB error), not a 401 (bad password) —
    // keeps your error codes honest.
  },
  emailField:    "email",     // body field name, if you ever need to change it
  passwordField: "password",
})

This strategy deliberately does not touch your database — you provide verify. That's what makes "production grade, your choice of persistence" actually true: swap Postgres for Mongo for an in-memory Map without touching anything in this package.

Password helpers (shared so signup and login use identical hashing):

const hash  = await CredentialsStrategy.hash("plaintext")       // for signup
const valid = await CredentialsStrategy.compare("plaintext", hash) // used internally by verify()

Signup itself is intentionally not abstracted — creating a user is a write to your specific schema, so write that route yourself (see server.example.js) using CredentialsStrategy.hash() for consistency.


Adding your own strategy (e.g. GitHub)

Implement two methods. That's the entire contract:

import { BaseStrategy, AuthError } from "auth-kit"

export class GitHubStrategy extends BaseStrategy {
  name = "github"

  constructor({ clientID, clientSecret, redirectURI }) {
    super()
    this.clientID = clientID
    this.clientSecret = clientSecret
    this.redirectURI = redirectURI
  }

  async initiate(_req, res) {
    res.redirect(`https://github.com/login/oauth/authorize?client_id=${this.clientID}&redirect_uri=${this.redirectURI}`)
  }

  async authenticate(req) {
    const code = req.query.code
    if (!code) throw new AuthError("Missing code", { status: 400 })

    // ... exchange code, fetch profile via GitHub's API ...

    return {
      provider: this.name,
      user: { id, email, name, picture, emailVerified },
      raw: { profile, tokens },
    }
  }
}

Register it and it slots into the exact same onAuthenticate hook:

authKit.use("github", new GitHubStrategy({ ... }))
app.get("/auth/github",          authKit.initiate("github"))
app.get("/auth/github/callback", authKit.complete("github"))

Nothing else in your app needs to know GitHub exists.


Error handling

Every strategy should throw AuthError (not a plain Error) for known failure cases:

throw new AuthError("Invalid email or password", { status: 401, code: "INVALID_CREDENTIALS" })

Unexpected errors (network failures, bugs) get auto-wrapped by AuthKit into an AuthError with status: 500, code: "STRATEGY_ERROR", so onError always receives a consistent shape:

err.message   // human-readable
err.status    // HTTP status to respond with
err.code      // machine-readable, e.g. "INVALID_CREDENTIALS"
err.cause     // original error, if any (useful for logging)

What this package intentionally does NOT do

  • No database. CredentialsStrategy.verify and your onAuthenticate hook are where persistence happens — bring your own ORM/driver.
  • No JWT signing. onAuthenticate gets a normalized user; signing tokens, setting cookies, and session management are yours to control.
  • No signup flow. Creating a user is schema-specific — write that route directly, using CredentialsStrategy.hash() for consistency.

This is by design: the moment a library starts making decisions about your schema or session strategy, it stops being reusable across projects. This package's only job is "run a strategy, hand back the same shape every time."


File structure

auth-kit/
├── core/
│   ├── AuthKit.js        ← orchestrator: initiate(), complete(), use()
│   ├── BaseStrategy.js   ← interface every strategy follows
│   └── errors.js         ← AuthError class
├── strategies/
│   ├── google.js
│   └── credentials.js
├── index.js              ← public exports
└── server.example.js     ← full working example (Google + credentials)

License

MIT