{"id":16744,"library":"smart-auth-middleware","title":"Express Smart Authentication Middleware","description":"This package, `smart-auth-middleware`, is an Express.js middleware designed for authenticating incoming requests by validating JSON Web Tokens (JWTs) against an external Identity Service (IDS). It integrates with `jwks-rsa` for fetching JSON Web Key Sets and `express-jwt` for the core JWT verification process. Currently at version 0.21.0, it is in active development, implying that breaking changes might occur more frequently between minor versions as it approaches a stable 1.0 release. The middleware provides a lifecycle with `authPreCheck` for initial validation, `jwtVerify` for token verification and setting user information on `req.user`, and `authPostCheck` to ensure verification success. Its key differentiators include built-in support for JWKS endpoints and configurable options for issuer, audience, and ignored paths, streamlining JWT-based authentication in Express applications.","status":"active","version":"0.21.0","language":"javascript","source_language":"en","source_url":null,"tags":["javascript"],"install":[{"cmd":"npm install smart-auth-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add smart-auth-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add smart-auth-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used internally to retrieve RSA public keys from a JWKS endpoint for token verification.","package":"jwks-rsa"},{"reason":"Provides the core JWT authentication logic, including token parsing and signature verification.","package":"express-jwt"}],"imports":[{"note":"The library primarily exports a default function. While the README shows CommonJS, this is the correct ESM import assuming dual package support.","wrong":"import { authentication } from 'smart-auth-middleware';","symbol":"authentication","correct":"import authentication from 'smart-auth-middleware';"},{"note":"As per documentation, this is the correct CommonJS `require` statement for the default exported function.","wrong":"const { authentication } = require('smart-auth-middleware');","symbol":"authentication","correct":"const authentication = require('smart-auth-middleware');"},{"note":"Configuration options are passed as an object directly to the `authentication` middleware function, not imported separately.","wrong":"import { options } from 'smart-auth-middleware';","symbol":"Auth Options","correct":"// No direct import for options object, it's passed directly to the middleware function"}],"quickstart":{"code":"import express from 'express';\nimport authentication from 'smart-auth-middleware';\n\nconst app = express();\nconst router = express.Router();\n\n// Ensure environment variables are set or provide fallbacks\nconst options = {\n    IDENTITY_SERVICE_URL: process.env.IDENTITY_SERVICE_URL ?? 'http://localhost:3000/identity',\n    ISSUER: process.env.JWT_ISSUER ?? 'your-issuer-url',\n    AUDIENCE: process.env.JWT_AUDIENCE ?? 'your-audience',\n    ignorePaths: [ '/healthcheck', '/ping' ]\n};\n\n// Apply the authentication middleware to all routes under '/'\n// All routes after this middleware will require a valid JWT, except ignoredPaths\napp.use('/', authentication(options), router);\n\nrouter.get('/secure-data', (req, res) => {\n  // req.user will be populated by the middleware if token is valid\n  if (req.user) {\n    res.status(200).json({ message: 'Access granted to secure data', user: req.user });\n  } else {\n    res.status(401).json({ message: 'Unauthorized: req.user not found' });\n  }\n});\n\nrouter.get('/healthcheck', (req, res) => {\n  res.status(200).send('Service is healthy');\n});\n\n// Basic error handling middleware for express-jwt errors\napp.use((err, req, res, next) => {\n  if (err.name === 'UnauthorizedError') {\n    res.status(401).json({ message: 'Invalid token: ' + err.message });\n  } else {\n    next(err);\n  }\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on port ${PORT}`);\n  console.log('Test with: curl -H \"Authorization: Bearer <YOUR_JWT>\" http://localhost:3000/secure-data');\n  console.log('Or: curl http://localhost:3000/healthcheck');\n});","lang":"typescript","description":"Demonstrates how to integrate `smart-auth-middleware` into an Express application, configure essential options, protect routes, and handle common authentication errors."},"warnings":[{"fix":"Thoroughly review the package's `CHANGELOG.md` or release notes before updating minor versions, especially in production environments.","message":"As a package in the `0.x.x` version series, `smart-auth-middleware` may introduce breaking changes in minor versions (e.g., from 0.20.x to 0.21.x) without adhering to semantic versioning for major changes. Always review changelogs when updating.","severity":"breaking","affected_versions":">=0.1.0"},{"fix":"Ensure `IDENTITY_SERVICE_URL` is always present and correctly points to your Identity Service. Use environment variables for sensitive or deployment-specific configurations.","message":"The `IDENTITY_SERVICE_URL` option is mandatory. If it's not provided or is misconfigured, the middleware's `authPreCheck` method will throw an error, preventing the application from starting or processing requests.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Add a dedicated Express error handling middleware to catch `UnauthorizedError` and other potential errors thrown by the authentication process, providing a user-friendly response.","message":"Error handling for `UnauthorizedError` from the underlying `express-jwt` library must be explicitly implemented as an Express error handling middleware (`app.use((err, req, res, next) => { ... })`). Failing to do so will result in unhandled exceptions.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Clients should send JWTs in the standard `Authorization: Bearer <token>` format. Verify client-side implementation matches this expectation.","message":"The middleware expects a JWT in the `Authorization` header with a `Bearer` prefix (e.g., `Authorization: Bearer <token>`). Using incorrect header names or token formats will result in authentication failure.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `IDENTITY_SERVICE_URL` is set to a valid URL in the options object passed to `authentication()`.","cause":"The `IDENTITY_SERVICE_URL` option was not provided or was an empty string when initializing the middleware.","error":"Error: IDENTITY_SERVICE_URL is mandatory configuration."},{"fix":"The client must provide an `Authorization` header with a valid JWT, prefixed by `Bearer` (e.g., `Authorization: Bearer YOUR_JWT_TOKEN`).","cause":"The `Authorization` header was missing or empty in the incoming HTTP request.","error":"UnauthorizedError: No authorization token was found"},{"fix":"Verify that the JWT is correctly formed, has not expired, is signed by a trusted issuer, and matches the expected audience configured in the middleware options.","cause":"The provided JWT was malformed, expired, had an incorrect signature, or did not pass other validation checks (e.g., issuer, audience).","error":"UnauthorizedError: Invalid token"}],"ecosystem":"npm"}