{"id":16725,"library":"fastify-auth-prisma","title":"Fastify Auth Prisma Plugin","description":"Fastify Auth Prisma is a Fastify plugin that integrates with Prisma to provide a simple and secure authentication middleware solution. It handles token-based authentication, allowing developers to protect routes and manage user sessions by leveraging Prisma for database interactions. The current stable version is 1.2.444, indicating active development within the 1.x release line. While a specific release cadence isn't stated, the version numbering suggests frequent updates. Key differentiators include its direct integration with Prisma, simplifying the data layer for authentication, and its focus on being a Fastify-native solution for performance and developer experience within the Fastify ecosystem. It provides mechanisms for defining public routes and validating connected users using a Prisma client and JWT secrets.","status":"active","version":"1.2.444","language":"javascript","source_language":"en","source_url":"https://github.com/qlaffont/fastify-auth-prisma","tags":["javascript","typescript"],"install":[{"cmd":"npm install fastify-auth-prisma","lang":"bash","label":"npm"},{"cmd":"yarn add fastify-auth-prisma","lang":"bash","label":"yarn"},{"cmd":"pnpm add fastify-auth-prisma","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for database schema definition and migration, used with @prisma/client.","package":"prisma"},{"reason":"Prisma ORM client for database interactions (e.g., querying User and Token models).","package":"@prisma/client"},{"reason":"A peer dependency or commonly used plugin that fastify-auth-prisma expects to be registered, enabling unified Fastify functionality.","package":"unify-fastify"}],"imports":[{"note":"The library primarily uses named exports and is designed for ESM contexts within Fastify. CommonJS require() usage needs to specifically target the named export or use a transpiler.","wrong":"const fastifyAuthPrismaPlugin = require('fastify-auth-prisma').fastifyAuthPrismaPlugin;","symbol":"fastifyAuthPrismaPlugin","correct":"import { fastifyAuthPrismaPlugin } from 'fastify-auth-prisma';"},{"note":"This function is provided as a utility to generate user tokens outside of the main plugin registration.","symbol":"createUserToken","correct":"import { createUserToken } from 'fastify-auth-prisma';"},{"note":"While not directly from `fastify-auth-prisma`, the `User` type is crucial for extending FastifyRequest and is sourced from `@prisma/client`, which is a core dependency.","symbol":"User","correct":"import { User } from '@prisma/client';"}],"quickstart":{"code":"import fastify from 'fastify';\nimport { PrismaClient, User } from '@prisma/client';\nimport unifyFastifyPlugin from 'unify-fastify';\nimport { fastifyAuthPrismaPlugin } from 'fastify-auth-prisma';\n\nconst prisma = new PrismaClient();\nconst server = fastify({\n  logger: true\n});\n\ndeclare module 'fastify' {\n  interface FastifyRequest {\n    connectedUser?: User;\n  }\n}\n\nasync function startServer() {\n  await server.register(unifyFastifyPlugin);\n\n  await server.register(fastifyAuthPrismaPlugin, {\n    config: [{ url: '/public/*', method: 'GET' }],\n    prisma,\n    secret: process.env.JWT_ACCESS_SECRET ?? 'supersecretjwtkey',\n    userValidation: async (user: User) => {\n      if (!user.id) {\n        throw new Error('User not found or invalid.');\n      }\n      // Add custom validation logic here, e.g., check if user is banned\n    }\n  });\n\n  server.get('/public/hello', async (request, reply) => {\n    return { message: 'Hello, public world!' };\n  });\n\n  server.get('/protected/hello', async (request, reply) => {\n    if (!request.connectedUser) {\n      reply.code(401).send({ message: 'Unauthorized' });\n      return;\n    }\n    return { message: `Hello, ${request.connectedUser.id}! You are connected.` };\n  });\n\n  try {\n    await server.listen({ port: 3000 });\n    server.log.info(`Server listening on http://localhost:3000`);\n  } catch (err) {\n    server.log.error(err);\n    process.exit(1);\n  }\n}\n\nstartServer();","lang":"typescript","description":"This quickstart demonstrates how to set up `fastify-auth-prisma` with a basic Fastify server, including Prisma client integration, custom user validation, and defining public/protected routes. It shows how `connectedUser` is made available on the request object for authenticated users."},"warnings":[{"fix":"Ensure you add the `declare module 'fastify'` snippet as shown in the quickstart or documentation to extend the `FastifyRequest` interface with `connectedUser`.","message":"The `declare module 'fastify'` block for `connectedUser` is essential. Failing to include it will result in TypeScript errors when attempting to access `request.connectedUser` within route handlers.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always store `process.env.JWT_ACCESS_SECRET` in production environments. Consider using environment variable managers or secret management services for deployment.","message":"The `secret` option for `fastifyAuthPrismaPlugin` is critical for JWT security. Using a hardcoded or easily guessable secret in production can lead to severe security vulnerabilities. It is strongly recommended to use a robust, externally managed secret.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the `prisma.schema` example provided in the documentation to ensure your Prisma models for `User` and `Token` include the necessary fields like `id`, `refreshToken`, `accessToken`, and the relation `owner`/`ownerId`.","message":"Proper Prisma schema setup is crucial for this plugin. The `Token` and `User` models, along with their relations, must match the structure expected by the plugin for correct authentication flow.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Either register `unify-fastify` if it's a required dependency, or check if `fastify-auth-prisma` can function correctly without it based on its internal implementation details or future documentation updates.","message":"The `unify-fastify` plugin is registered in the example setup. If your application does not use or register `unify-fastify`, you might encounter unexpected behavior or errors if `fastify-auth-prisma` has a hard dependency or expects its functionalities.","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":"Add `declare module 'fastify' { interface FastifyRequest { connectedUser?: User; } }` to your project's global declaration file or a relevant TypeScript file.","cause":"Missing TypeScript declaration merging for the `FastifyRequest` interface.","error":"Property 'connectedUser' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, RawRequestDefaultExpression, RouteShorthandOptions<RawServerDefault>, ContextConfigDefault>'"},{"fix":"Ensure `fastify()` is called correctly and `server.register` is invoked within an `async` function with `await` if using top-level await or inside a setup function.","cause":"Attempting to register the plugin before the Fastify instance is fully initialized or when `server` is not a valid Fastify instance.","error":"TypeError: Cannot read properties of undefined (reading 'register')"},{"fix":"Provide a non-empty string for the `secret` option when registering `fastifyAuthPrismaPlugin`, ideally from `process.env`.","cause":"The `secret` option was not provided or was an empty string during plugin registration.","error":"FastifyError: FST_ERR_MISSING_SECRET: Missing secret"}],"ecosystem":"npm"}