Registry / web-framework / fastify-auth-prisma

fastify-auth-prisma

JSON →
library1.2.444jsnpmunverified

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.

npm install fastify-auth-prisma
INSTALL
IMPORT
SIG · FASTIFY-AUTH-PRISM
F
fastify-auth-prisma
web-frameworkjavascriptv1.2.444
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

fastifyAuthPrismaPlugin
import { fastifyAuthPrismaPlugin } from 'fastify-auth-prisma';
const fastifyAuthPrismaPlugin = require('fastify-auth-prisma').fastifyAuthPrismaPlugin;
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.
createUserToken
import { createUserToken } from 'fastify-auth-prisma';
This function is provided as a utility to generate user tokens outside of the main plugin registration.
User
import { User } from '@prisma/client';
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.

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.

import fastify from 'fastify'; import { PrismaClient, User } from '@prisma/client'; import unifyFastifyPlugin from 'unify-fastify'; import { fastifyAuthPrismaPlugin } from 'fastify-auth-prisma'; const prisma = new PrismaClient(); const server = fastify({ logger: true }); declare module 'fastify' { interface FastifyRequest { connectedUser?: User; } } async function startServer() { await server.register(unifyFastifyPlugin); await server.register(fastifyAuthPrismaPlugin, { config: [{ url: '/public/*', method: 'GET' }], prisma, secret: process.env.JWT_ACCESS_SECRET ?? 'supersecretjwtkey', userValidation: async (user: User) => { if (!user.id) { throw new Error('User not found or invalid.'); } // Add custom validation logic here, e.g., check if user is banned } }); server.get('/public/hello', async (request, reply) => { return { message: 'Hello, public world!' }; }); server.get('/protected/hello', async (request, reply) => { if (!request.connectedUser) { reply.code(401).send({ message: 'Unauthorized' }); return; } return { message: `Hello, ${request.connectedUser.id}! You are connected.` }; }); try { await server.listen({ port: 3000 }); server.log.info(`Server listening on http://localhost:3000`); } catch (err) { server.log.error(err); process.exit(1); } } startServer();
Debug
Known issues
breakingThe `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.
fix
Ensure you add the `declare module 'fastify'` snippet as shown in the quickstart or documentation to extend the `FastifyRequest` interface with `connectedUser`.
affects: >=1.0.0
gotchaThe `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.
fix
Always store `process.env.JWT_ACCESS_SECRET` in production environments. Consider using environment variable managers or secret management services for deployment.
affects: >=1.0.0
gotchaProper 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.
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`.
affects: >=1.0.0
gotchaThe `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.
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.
affects: >=1.0.0
Errors
Common errors & fixes
Property 'connectedUser' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, RawRequestDefaultExpression, RouteShorthandOptions<RawServerDefault>, ContextConfigDefault>'
Missing TypeScript declaration merging for the `FastifyRequest` interface.
fix
Add `declare module 'fastify' { interface FastifyRequest { connectedUser?: User; } }` to your project's global declaration file or a relevant TypeScript file.
TypeError: Cannot read properties of undefined (reading 'register')
Attempting to register the plugin before the Fastify instance is fully initialized or when `server` is not a valid Fastify instance.
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.
FastifyError: FST_ERR_MISSING_SECRET: Missing secret
The `secret` option was not provided or was an empty string during plugin registration.
fix
Provide a non-empty string for the `secret` option when registering `fastifyAuthPrismaPlugin`, ideally from `process.env`.
Upgrade
Version history
1.2.444latest on npm
Audit
Dependencies
prismarequiredRequired for database schema definition and migration, used with @prisma/client.
@prisma/clientrequiredPrisma ORM client for database interactions (e.g., querying User and Token models).
unify-fastifyrequiredA peer dependency or commonly used plugin that fastify-auth-prisma expects to be registered, enabling unified Fastify functionality.
Agent activity
25 hits · last 30 days
node
22
Bingbot
1
OpenAI (training)
1
Resources
fastify-auth-prisma — npm install fastify-auth-prisma · libregistry