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

@json-express/middleware-auth

v2.0.0

Published

JWT Authentication Middleware plugin for JSON Express

Readme

@json-express/middleware-auth

JWT authentication middleware for JSONExpress v2. Verifies Bearer tokens on incoming requests, rejects unauthenticated traffic, and publishes the decoded JWT payload so downstream generators (REST, GraphQL) can authorize.


What It Does

This plugin implements the IMiddleware interface under the name 'auth'. When a route includes 'auth' in its middlewares[], every request to that route must carry a valid JWT Authorization: Bearer <token> header. Otherwise the middleware short-circuits with 401 Unauthorized (missing/malformed header) or 403 Forbidden (invalid/expired token).

On success, the decoded payload is serialized and attached to the request as:

req.headers['x-user-payload'] = JSON.stringify(decoded)

The api-rest and api-graphql generators read this header to evaluate per-collection access rules (see Schema-Driven Access Control below).


Configuration

All options are set via .env using the jex or JEX namespace (double underscore creates nested blocks). Pick exactly one of auth.secret or auth.jwksUri — the middleware throws at boot if both are set.

Symmetric (HMAC, e.g. tokens you mint yourself)

# HMAC secret used by jsonwebtoken to verify every token.
jex__auth__secret=your-hmac-secret

# Optional — comma-separated or array of path prefixes the middleware should skip.
# Useful for health checks, docs, login endpoints, or making /graphql public.
jex_auth_exclude=/docs,/health,/login

Asymmetric (JWKS, e.g. Auth0 / Firebase / Supabase / any OIDC provider)

# Public JWKS endpoint of your identity provider. The middleware fetches and
# caches the signing keys, then verifies RS256 tokens against them — no secret
# is shared with your app.
jex__auth__jwks_uri=https://dev-xxx.us.auth0.com/.well-known/jwks.json

# Optional — strictly validated by jsonwebtoken when set.
jex__auth__audience=my-json-express-api
jex__auth__issuer=https://dev-xxx.us.auth0.com/

Full key reference

| Key | Type | Default | Description | |---|---|---|---| | auth.secret | string | — | Shared HMAC secret. Mutually exclusive with auth.jwksUri. | | auth.jwksUri | string | — | Public JWKS endpoint URL for asymmetric verification. Mutually exclusive with auth.secret. | | auth.audience | string \| string[] | — | Optional. When set, every token's aud claim must match. | | auth.issuer | string | — | Optional. When set, every token's iss claim must match. | | auth.algorithms | string[] | ['HS256'] for secret, ['RS256'] for jwksUri | Pinned allow-list of accepted algorithms. Prevents the alg: none attack and guards against JWKS providers that mix algorithms. | | auth.exclude | string \| string[] | [] | Path prefixes that bypass the Bearer-token check. Matched via path.startsWith(prefix). |

If neither auth.secret nor auth.jwksUri is set, the middleware logs a warning and calls next() without authentication. The REST API generator attaches the 'auth' middleware automatically to every route it produces when either key is set — except for routes whose collection declares access.{op}: 'public' (see below).


Expected Token Shape

This middleware is transport-neutral about claims — any valid JWT verifies. For RBAC integration, downstream generators look at payload.role (string or string[]). A typical payload:

{
  "sub": "user-123",
  "role": "admin",
  "iat": 1700000000,
  "exp": 1700003600
}

Mint tokens with any standard library, e.g.:

import jwt from 'jsonwebtoken';
const token = jwt.sign(
    { sub: 'user-1', role: 'admin' },
    process.env.JEX__AUTH__SECRET!,
    { expiresIn: '1h' }
);

Then send it as Authorization: Bearer <token>.


Schema-Driven Access Control

middleware-auth handles authentication only ("who are you?"). Authorization ("can you perform this operation?") is declared on each ModelSchema and enforced by the API generators:

// models/posts.ts
import { defineModel, types } from '@json-express/core';

export default defineModel({
    fields: {
        id: types.id(),
        title: types.string({ required: true }),
        body: types.string(),
    },
    access: {
        read: 'public',                  // anonymous allowed; auth middleware is stripped from this route
        create: 'admin',                 // requires a valid JWT with role === 'admin'
        update: ['admin', 'editor'],     // any listed role is sufficient
        delete: 'admin',
    },
});

| Rule value | Behavior | |---|---| | undefined | No authorization check. Auth middleware still runs if auth.secret is set. | | 'public' | Anonymous traffic allowed. REST routes have the 'auth' middleware stripped entirely. | | string / string[] | Requires a verified JWT whose role claim matches (intersection for arrays). | | 'owner' | Row-level security. Caller must own the record — owner field defaults to ownerId (override via access.ownerField). Mismatches return 404 (not 403) to prevent existence leaks. |

On denial, generators return:

  • REST — 401 (missing/invalid payload) or 403 (role mismatch).
  • GraphQL — GraphQLError with extensions.code = 'UNAUTHENTICATED' | 'FORBIDDEN'.

GraphQL Caveat

/graphql is a single endpoint, so middleware-auth cannot selectively protect individual operations. In practice:

  • If any of your GraphQL collections are truly public, add /graphql to JEX__AUTH__EXCLUDE. Resolver-level rules still enforce role checks on protected operations.
  • Otherwise, the middleware gates the endpoint as today; resolvers layer role checks on top.

Installation

This plugin is auto-discovered by the JSONExpress CLI when listed in your package.json dependencies:

npm install @json-express/middleware-auth

Set jex__auth__secret and it is applied to every route generated by api-rest / api-graphql unless explicitly excluded.


Architecture Note

Request → [auth middleware] → 401 / 403 (short-circuit)
                        ↓ on success
       sets req.headers['x-user-payload']
                        ↓
            [validation middleware]
                        ↓
          [api-rest / api-graphql handler]
              └─ evaluateAccess(schema.access[op], x-user-payload)
                    ├─ allowed → db call
                    └─ denied  → 401 / 403 (or GraphQLError)

The middleware is deliberately narrow — it only authenticates. All authorization logic lives in @json-express/core's evaluateAccess helper and is invoked by the API generators, keeping this package free of business rules.