{"id":16823,"library":"fastify-openid-auth","title":"Fastify OpenID Connect Authentication","description":"fastify-openid-auth is a specialized Fastify plugin designed to streamline OpenID Connect (OIDC) authentication within a Fastify application. Leveraging the robust openid-client library, it offers comprehensive support for both bearer token and cookie-based authentication flows, providing flexibility in how authentication state and tokens are managed. The plugin currently operates at version 12.0.0 as of its latest significant update in late 2025, demonstrating a consistent and active development cadence with several minor and major releases throughout 2024 and 2025. Key differentiators include its deep integration into the Fastify ecosystem by decorating the Fastify instance with dedicated `login`, `verify`, `refresh`, and `logout` handlers, full TypeScript type definitions, and adaptable token reading/writing strategies via headers, cookies, or session storage, making it suitable for a wide range of web application and API authentication scenarios.","status":"active","version":"12.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/mikaelkaron/fastify-openid-auth","tags":["javascript","fastify","openid","typescript"],"install":[{"cmd":"npm install fastify-openid-auth","lang":"bash","label":"npm"},{"cmd":"yarn add fastify-openid-auth","lang":"bash","label":"yarn"},{"cmd":"pnpm add fastify-openid-auth","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core library for OpenID Connect protocol handling.","package":"openid-client","optional":false},{"reason":"Peer dependency as this is a Fastify plugin, requiring Fastify 5.x+ since v10.0.0.","package":"fastify","optional":false},{"reason":"Peer dependency for proper Fastify plugin registration and encapsulation.","package":"fastify-plugin","optional":false}],"imports":[{"note":"This is the default export used for registering the plugin with `fastify.register()`.","wrong":"const openIDAuthPlugin = require('fastify-openid-auth')","symbol":"openIDAuthPlugin","correct":"import openIDAuthPlugin from 'fastify-openid-auth'"},{"note":"A named export for directly creating OpenID authentication handlers without using the Fastify plugin wrapper, useful for custom integrations or testing.","wrong":"import openIDHandlersFactory from 'fastify-openid-auth'","symbol":"openIDHandlersFactory","correct":"import { openIDHandlersFactory } from 'fastify-openid-auth'"},{"note":"This is a TypeScript type definition, crucial for type-safe configuration of the login handler. Always use `import type` to avoid runtime issues or bundle size increases.","wrong":"import { OpenIDLoginHandlerOptions } from 'fastify-openid-auth'","symbol":"OpenIDLoginHandlerOptions","correct":"import type { OpenIDLoginHandlerOptions } from 'fastify-openid-auth'"}],"quickstart":{"code":"import Fastify from 'fastify';\nimport openIDAuthPlugin from 'fastify-openid-auth';\nimport { generators } from 'openid-client'; // Often used with openid-client\n// For session management, typically you'd also install and register @fastify/cookie and @fastify/session\n// import fastifyCookie from '@fastify/cookie';\n// import fastifySession from '@fastify/session';\n\nconst fastify = Fastify({ logger: true });\n\n// Dummy OpenID Provider configuration (replace with actual values)\nconst openidConfig = {\n  issuer: 'https://accounts.google.com', // Example, replace with your OIDC provider\n  client_id: process.env.OIDC_CLIENT_ID ?? 'your-client-id-from-provider',\n  client_secret: process.env.OIDC_CLIENT_SECRET ?? 'your-client-secret-from-provider',\n  redirect_uris: ['http://localhost:3000/auth/callback'],\n  response_types: ['code']\n};\n\nconst AUTH_HANDLERS_SYMBOL = Symbol.for('auth-handlers');\n\n// Register cookie and session plugins FIRST if using cookie-based authentication\n// fastify.register(fastifyCookie);\n// fastify.register(fastifySession, { \n//   secret: process.env.SESSION_SECRET ?? 'a-very-long-and-secure-secret-key-for-session-encryption',\n//   cookie: { secure: process.env.NODE_ENV === 'production' }\n// });\n\nfastify.register(openIDAuthPlugin, {\n  decorator: AUTH_HANDLERS_SYMBOL,\n  config: openidConfig,\n  login: {\n    // Required since v12.0.0 for all handlers that manage OIDC state/tokens via session\n    session: {\n      get: async (request) => (request as any).session, // Placeholder: assumes @fastify/session is set up\n      set: async (request, value) => { (request as any).session = value; }, // Placeholder\n      destroy: async (request) => { delete (request as any).session; } // Placeholder\n    },\n    client_redirect_uri: 'http://localhost:3000/auth/callback',\n    parameters: {\n      scope: 'openid email profile',\n      prompt: 'login'\n    },\n    code_verifier_generator: generators.codeVerifier, // Recommended for PKCE\n    state_generator: generators.random // Recommended for state parameter\n  },\n  verify: {\n    session: {\n      get: async (request) => (request as any).session,\n      set: async (request, value) => { (request as any).session = value; },\n      destroy: async (request) => { delete (request as any).session; }\n    }\n  }\n});\n\nfastify.get('/login', async (request, reply) => {\n  const { login } = (fastify as any)[AUTH_HANDLERS_SYMBOL];\n  await login(request, reply);\n});\n\nfastify.get('/auth/callback', async (request, reply) => {\n  const { verify } = (fastify as any)[AUTH_HANDLERS_SYMBOL];\n  try {\n    const tokens = await verify(request, reply);\n    reply.send({ message: 'Login successful!', tokens });\n  } catch (error: any) {\n    fastify.log.error(error);\n    reply.status(401).send({ error: 'Authentication failed', details: error.message });\n  }\n});\n\nfastify.get('/protected', async (request, reply) => {\n  // In a real application, you would add authentication middleware here\n  // to check for a valid session or bearer token after 'verify' has run.\n  reply.send({ message: 'This is a protected route. Requires prior authentication.' });\n});\n\nconst start = async () => {\n  try {\n    await fastify.listen({ port: 3000 });\n    fastify.log.info(`Server listening on port ${3000}`);\n  } catch (err) {\n    fastify.log.error(err);\n    process.exit(1);\n  }\n};\n\nstart();","lang":"typescript","description":"This quickstart initializes a Fastify server, registers `fastify-openid-auth`, and demonstrates a basic OpenID Connect login and callback flow. It includes placeholder configuration for an OIDC provider and the session management required for cookie-based authentication, showing how to leverage the decorated authentication handlers."},"warnings":[{"fix":"Ensure your `login`, `verify`, `refresh`, and `logout` handler options explicitly define the `session` property with `get`, `set`, and `destroy` functions, typically integrating with a Fastify session plugin like `@fastify/session`.","message":"In `v12.0.0`, the internal `session` configuration for handlers like `OpenIDLoginHandler` was externalized. This means `session` configuration options must now be explicitly passed within `OpenIDLoginHandlerOptions` (and similar handler options) and are no longer automatically inferred or handled internally by the plugin. This makes `options` explicitly required for `OpenIDLoginHandler`.","severity":"breaking","affected_versions":">=12.0.0"},{"fix":"Review the changelogs for `openid-client@v6` and `jose@v6` for specific breaking changes. Adjust your OpenID client configuration, token parsing logic, and any direct `jose` interactions accordingly.","message":"`v11.0.0` upgraded the underlying `openid-client` to `v6` and `jose` to `v6`. These are significant upgrades to core dependencies and introduce breaking changes that may affect how you configure your OpenID client, handle tokens, or interact with OIDC provider metadata.","severity":"breaking","affected_versions":">=11.0.0"},{"fix":"Upgrade your Fastify application to `fastify@5.x` or newer to ensure compatibility. If you need to stay on Fastify 4.x, you must use an older version of `fastify-openid-auth` (e.g., `<10.0.0`).","message":"`fastify-openid-auth@10.0.0` introduced a breaking change requiring `fastify` version `5.x` or higher. Using older versions of Fastify with this plugin will lead to compatibility issues and errors.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"Always register and properly configure a robust session management plugin (like `@fastify/session`) *before* registering `fastify-openid-auth`. Ensure session secrets are strong, rotated, and managed securely, especially in production environments.","message":"For cookie-based authentication, `fastify-openid-auth` relies on a Fastify session plugin (e.g., `@fastify/session`) to manage user sessions and store OIDC state/tokens. Incorrectly configured or missing session management can lead to security vulnerabilities, lost state, and failed authentication flows.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `fastify.register(openIDAuthPlugin, ...)` is called only once per Fastify instance, or use a unique `decorator` symbol/string if you intend to register it multiple times for different configurations (though this is rare).","cause":"Attempting to register `fastify-openid-auth` multiple times with the same decorator symbol, or another plugin using the same symbol.","error":"FST_ERR_DEC_ALREADY_PRESENT: The decorator 'AUTH_HANDLERS_SYMBOL' is already present!"},{"fix":"Ensure a Fastify session plugin (e.g., `@fastify/session`) is registered *before* `fastify-openid-auth`. Then, explicitly provide the `session` object with `get`, `set`, and `destroy` methods in your `login`, `verify`, `refresh`, and `logout` options, mapping them to your session plugin's interface (e.g., `request.session`).","cause":"The `session` object within the handler options (`login`, `verify`, etc.) is either missing or its `get`, `set`, `destroy` functions are not properly defined. This is especially relevant after v12.0.0 and typically indicates a problem with session plugin integration.","error":"TypeError: Cannot read properties of undefined (reading 'get') at OpenIDLoginHandler (file:///path/to/fastify-openid-auth/dist/index.js:XXX:YY)"},{"fix":"Upgrade your project's `fastify` dependency to `5.x` (or newer) if using `fastify-openid-auth@10.0.0+`. Alternatively, if you must use Fastify 4.x, downgrade `fastify-openid-auth` to a compatible version (e.g., `<10.0.0`).","cause":"Version mismatch between `fastify-openid-auth` and the installed `fastify` package, specifically related to the breaking change in v10.0.0 that requires Fastify 5.x.","error":"Plugin 'fastify-openid-auth' was registered against Fastify version '4.x.x' but is being used with Fastify version '5.x.x.'"}],"ecosystem":"npm","meta_description":null}