Next.js Discord

Discord Forum

Can't run PrismaClient inside middleware (App Dir)

Unanswered
Shiba Inu posted this in #help-forum
Open in Discord
Shiba InuOP
I am having problems implementing a call to my prisma database within my middleware.ts in my next project. I want to verify that a user has permission to configure a guild on my discord dashboard so I am trying to get the auth key stored in the accounts table so I can make a call to get the permissions of that guild from discord.

I am getting an error though Error: PrismaClient is unable to be run in the browser.
I thought the middleware was server side?

this is whats causing the in middleware.ts

const account = await db.account.findFirst({
          where: {
            userId: userId,
          },
        })



Heres the code for the middleware.ts
import { getToken } from "next-auth/jwt"
import { withAuth } from "next-auth/middleware"
import { NextResponse } from "next/server"
import { db } from "./lib/db"

export default withAuth(
  async function middleware(req) {
    const token = await getToken({ req })
    const isAuth = !!token
    const isAuthPage = req.nextUrl.pathname.startsWith("/login")

    if (isAuthPage) {
      if (isAuth) {
        return NextResponse.redirect(new URL("/dashboard", req.url))
      }

      return null
    }

    const isServerPage = req.nextUrl.pathname.startsWith("/dashboard/s/")
    console.log(req.nextUrl.pathname, isServerPage)

    // TODO: The feature I am working on is to check if the user is an admin of the server in question and if the bot manages it (if the guild has an entry in the database)
    // If the user is not an admin of the server in question, they should be redirected to the dashboard home page
    // If the user is an admin of the server in question, they should be allowed to access the page

    if (isServerPage) {
      if (isAuth) {
        const serverUrl = req.nextUrl.pathname.split("/")[3]

        // get the user's auth key from the accounts database
        const userId = token.id
        const account = await db.account.findFirst({
          where: {
            userId: userId,
          },
        })

        console.log(account)
      }
      return null
    }

    if (!isAuth) {
      let from = req.nextUrl.pathname
      if (req.nextUrl.search) {
        from += req.nextUrl.search
      }

      return NextResponse.redirect(
        new URL(`/login?from=${encodeURIComponent(from)}`, req.url)
      )
    }
  },
  {
    callbacks: {
      async authorized() {
        // This is a work-around for handling redirect on auth pages.
        // We return true here so that the middleware function above
        // is always called.
        return true
      },
    },
  }
)

export const config = { matcher: ["/dashboard/:path*", "/login"] }



and here is my db.ts file

import { PrismaClient } from "@prisma/client"

declare global {
  // eslint-disable-next-line no-var
  var cachedPrisma: PrismaClient
}

let prisma: PrismaClient
if (process.env.NODE_ENV === "production") {
  prisma = new PrismaClient()
} else {
  if (!global.cachedPrisma) {
    global.cachedPrisma = new PrismaClient()
  }
  prisma = global.cachedPrisma
}

export const db = prisma

2 Replies

Shiba InuOP
After doing some more research I was thinking of 2 solutions:

1. make a server side only api endpoint (how do i actually do this, any links would be appreciated)

EDIT: I wanna do this but how on earth do u make an api endpoint that only the server can access???

2. is there any way to get the user's auth token in their next auth session without reaching out to my prisma database?