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

swagger-docs-basic-auth-middleware

v1.1.0

Published

Reusable Express middleware to protect Swagger docs with basic auth and cookie session.

Readme

swagger-docs-basic-auth-middleware

Middleware reutilizable para proteger Swagger Docs con:

  • Login HTML para /docs

  • Cookie HttpOnly de sesion

  • Fallback Basic Auth para otras rutas protegidas

  • https://www.npmjs.com/package/swagger-docs-basic-auth-middleware?activeTab=readme

Instalacion

npm install swagger-docs-basic-auth-middleware

Uso rapido (Express)

import express from "express";
import { createSwaggerDocsAuthMiddleware } from "swagger-docs-basic-auth-middleware";

const app = express();
app.use(express.urlencoded({ extended: false }));

const swaggerAuth = createSwaggerDocsAuthMiddleware({
  credentials: {
    username: process.env.SWAGGER_USER ?? "",
    password: process.env.SWAGGER_PASSWORD ?? "",
  },
  serverPath: process.env.SERVER_PATH,
  docsPath: "/docs",
  branding: {
    appName: "Gateway Docs",
  },
});

app.use("/docs", swaggerAuth);

API

createSwaggerDocsAuthMiddleware(options: SwaggerDocsAuthOptions): RequestHandler

Opciones principales:

  • credentials.username: usuario requerido
  • credentials.password: clave requerida
  • serverPath: prefijo global (ej. /gateway)
  • docsPath: por defecto /docs
  • cookieName: por defecto swagger_docs_auth
  • logger.debug/error: adaptador de logs opcional
  • branding: textos y assets del login

Opciones de branding

Puedes personalizar completamente los textos y assets del formulario de login con branding.

branding?: {
  appName?: string;
  loginTitle?: string;
  loginSubtitle?: string;
  loginErrorMessage?: string;
  usernameLabel?: string;
  passwordLabel?: string;
  submitButtonLabel?: string;
  faviconHref?: string;
  logoHref?: string;
}

Valores por defecto:

  • appName: Docs
  • loginTitle: Acceder a Docs
  • loginSubtitle: Autenticacion requerida para la documentacion.
  • loginErrorMessage: Credenciales invalidas. Intenta nuevamente.
  • usernameLabel: Nombre de usuario
  • passwordLabel: Contrasena
  • submitButtonLabel: Entrar
  • faviconHref: sin valor por defecto (si no se define, no se renderiza favicon)
  • logoHref: sin valor por defecto (si no se define, no se renderiza logo)

Ejemplo completo de personalizacion:

const swaggerAuth = createSwaggerDocsAuthMiddleware({
  credentials: {
    username: process.env.SWAGGER_USER ?? "",
    password: process.env.SWAGGER_PASSWORD ?? "",
  },
  docsPath: "/docs",
  branding: {
    appName: "Portal Tecnico",
    loginTitle: "Ingresar a Swagger",
    loginSubtitle: "Solo personal autorizado.",
    loginErrorMessage: "Usuario o contrasena incorrectos.",
    usernameLabel: "Usuario",
    passwordLabel: "Clave",
    submitButtonLabel: "Iniciar sesion",
    faviconHref: "/assets/favicon.png",
    logoHref: "/assets/logo.svg",
  },
});

Vista rapida del resultado

Sin branding personalizado:

  • Titulo: Acceder a Docs
  • Subtitulo: Autenticacion requerida para la documentacion.
  • Labels: Nombre de usuario / Contrasena
  • Boton: Entrar

Con branding personalizado:

  • Titulo: el que definas en loginTitle
  • Subtitulo: el que definas en loginSubtitle
  • Labels: los que definas en usernameLabel y passwordLabel
  • Boton: el que definas en submitButtonLabel
  • Identidad visual: logoHref, faviconHref y appName

Preset recomendado para entorno corporativo:

branding: {
  appName: 'Portal Interno',
  loginTitle: 'Acceso a Documentacion',
  loginSubtitle: 'Requiere credenciales corporativas.',
  loginErrorMessage: 'Credenciales invalidas.',
  usernameLabel: 'Usuario corporativo',
  passwordLabel: 'Contrasena corporativa',
  submitButtonLabel: 'Ingresar',
  faviconHref: '/assets/corp-favicon.png',
  logoHref: '/assets/corp-logo.svg'
}

Troubleshooting

No carga logo o favicon

Sintoma:

  • El formulario aparece, pero el logo esta roto o no se ve el favicon.

Causa comun:

  • logoHref o faviconHref apuntan a rutas que no estan siendo servidas por tu app.

Nota:

  • Si no defines estos campos, el middleware no intenta cargar ningun asset por defecto.

Solucion:

  1. Verifica que esos archivos existan y se puedan abrir desde el navegador.
  2. Si usas NestJS, sirve assets estaticos (por ejemplo con ServeStaticModule) o apunta a una URL publica.
  3. Si tienes serverPath, valida que la ruta final no quede duplicada o incompleta.

Ejemplo:

  • Con serverPath: '/api', el default intenta usar /api/static/images/....

Muestra JSON 401 y no formulario HTML

Sintoma:

  • Respuesta: {"statusCode":401,"message":"Authentication required."}

Causa comun:

  • docsPath no coincide con la ruta protegida en app.use(...) o forRoutes(...).

Solucion:

  1. Alinea ambas rutas exactamente.
  2. Si Swagger esta en /api/docs, usa docsPath: '/api/docs' y protege /api/docs.

Login correcto pero redirecciona a ruta inesperada

Sintoma:

  • Ingresas credenciales validas y redirige a una ruta distinta a la esperada.

Causa comun:

  • El next enviado no pertenece al docsPath configurado y se sanea automaticamente.

Solucion:

  1. Asegura que el endpoint y assets de Swagger cuelguen de docsPath.
  2. Usa un docsPath unico y consistente para todo el modulo.

El cookie no persiste en HTTPS/proxy

Sintoma:

  • Te autenticas, pero al siguiente request vuelve a pedir login.

Causa comun:

  • Proxy o balanceador no propaga correctamente x-forwarded-proto: https.

Solucion:

  1. Configura tu proxy para enviar x-forwarded-proto.
  2. Verifica en network del navegador que el Set-Cookie llegue y no sea bloqueado.

Desarrollo local

npm install
npm run build
npm run test

Demo local (login en navegador)

Puedes levantar un servidor demo dentro de este repositorio para probar el formulario de login.

npm install
npm run demo:local

Abre:

  • http://localhost:3030/docs

Credenciales por defecto:

  • Usuario: admin
  • Contrasena: admin123

Opcionalmente puedes cambiarlo con variables de entorno:

SWAGGER_USER=miusuario SWAGGER_PASSWORD=miclave PORT=3030 npm run demo:local

Publicar en npm

  1. Actualiza version en package.json.
  2. Inicia sesion:
npm login
  1. Publica:
npm publish --access public

Si publicas en un registro privado, ajusta .npmrc y usa el scope correspondiente.