Fastify Auth Prisma Plugin

1.2.444 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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();

view raw JSON →