lucia-auth / lucia

Authentication, simple and clean
https://lucia-auth.com
MIT License
9.25k stars 471 forks source link

[Bug]: Middleware with Prisma Adapter (PrismaClient) is not working #1443

Closed MusabDev closed 7 months ago

MusabDev commented 7 months ago

Package

lucia

Describe the bug

Hello,

First of all, I am using Prisma (with Lucia adapter) and Next.js 14.

So, when I try to call the following function in middleware.ts, it returns the error: Error: PrismaClient is unable to run in Vercel Edge Functions or Edge Middleware. As an alternative, try Accelerate: https://pris.ly/d/accelerate. (screenshot provided below).

I think this is because you shouldn't use the PrismaClient in middleware, rather to use PrismaClient from @prisma/client/edge. Check this issue for more details: https://github.com/prisma/prisma/issues/21310

export const validateRequest = cache(
  async (): Promise<
    { user: User; session: Session } | { user: null; session: null }
  > => {
    const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null;
    if (!sessionId) {
      return {
        user: null,
        session: null,
      };
    }

    const result = await lucia.validateSession(sessionId);
    try {
      if (result.session && result.session.fresh) {
        const sessionCookie = lucia.createSessionCookie(result.session.id);
        cookies().set(
          sessionCookie.name,
          sessionCookie.value,
          sessionCookie.attributes,
        );
      }
      if (!result.session) {
        const sessionCookie = lucia.createBlankSessionCookie();
        cookies().set(
          sessionCookie.name,
          sessionCookie.value,
          sessionCookie.attributes,
        );
      }
    } catch {}
    return result;
  },
);

image

pilcrowOnPaper commented 7 months ago

This isn't a bug, nor is it related to Lucia (?)