0

I am using next.js: 13.4.12 (app router) with next-auth: 4.22.3, prisma: 5.0.0, @next-auth/prisma-adapter: 1.0.7 in typescript.

I have also followed all the required boiler plate from the official documentation.

this is my middleware.ts file


import withAdminsAuthentication from "./middleware/admin";
import withUserAuthentication from "./middleware/auth";
import { stackMiddlewares } from "./middleware/stackMiddlewares";

const middlewares = [withUserAuthentication, withAdminsAuthentication];
// stackMiddleware function chains the given list of middlewares
export default stackMiddlewares(middlewares);

this is my middleware/auth.ts file


import type { MiddlewareFactory } from "./types";
import { options } from "@/lib/auth";
import { NextResponse } from "next/server";
import { getUserByEmail } from "@/database/users";
import { getServerSession } from "next-auth";

const authenticatedUsersOnlyRoutes: string[] = [
  // regex for routes that require authentication
];

const withUserAuthentication: MiddlewareFactory =
  (next) => async (request, event) => {
    const path = new URL(request.url).pathname;
    for (const route of authenticatedUsersOnlyRoutes) {
      const regex = new RegExp(route);
      console.log(regex, path);

      if (regex.test(path)) {
        // this line causes error. If I remove the getServerSession call there is no error
        const session = await getServerSession(options);

        if (session == null) {
          return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }
        const email = session.user?.email;
        if (email == null) {
          return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const user = await getUserByEmail(email);

        if (user instanceof Error) {
          return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        request.user = user;
        return await next(request, event);
      }
    }
    return await next(request, event);
  };

export default withUserAuthentication;

this is my @lib/auth.ts file where I export the next-auth options


import client from "@/database/client";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import type { AuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";

const clientId = process.env.GOOGLE_OAUTH_CLIENT_ID;
const clientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;

if (clientId == null || clientSecret == null) {
  throw new Error("Missing `Google Oauth` Credentials");
}

export const options: AuthOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    GoogleProvider({
      name: "Sign in with Google",
      clientId,
      clientSecret,
      httpOptions: {
        timeout: 20000,
      },
    }),
  ],
  adapter: PrismaAdapter(client),
};

error stacktrace


Server Error
TypeError: Xt1.deprecate is not a function

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
webpack-internal:///(middleware)/./node_modules/@prisma/client/runtime/library.js (376)
deprecate
node_modules\@prisma\client\runtime\library.js (1:8533)
e
node_modules\@prisma\client\runtime\library.js (1:221)
Ri
node_modules\@prisma\client\runtime\library.js (5:258)
e
node_modules\@prisma\client\runtime\library.js (1:221)
Fi
node_modules\@prisma\client\runtime\library.js (7:9720)
Object.(middleware)/./node_modules/@prisma/client/runtime/library.js
file:///D:/Jk/Work/Recomm-new-prototype/.next/server/src/middleware.js (238:1)
__webpack_require__
file:///D:/Jk/Work/Recomm-new-prototype/.next/server/edge-runtime-webpack.js (37:33)
fn
file:///D:/Jk/Work/Recomm-new-prototype/.next/server/edge-runtime-webpack.js (268:21)
eval
webpack-internal:///(middleware)/./src/database/client.ts (9:88)
Module.(middleware)/./src/database/client.ts
file:///D:/Jk/Work/Recomm-new-prototype/.next/server/src/middleware.js (1818:1)

This was updated

now I commented all the code in the middleware/auth.ts but I still get the same error but now in middleware/admin.ts page

here is the content in the middleware/admin.ts file


import type { MiddlewareFactory } from "./types";
import { getAdminByUserId } from "@/database/admin";
import { NextResponse } from "next/server";
const adminsOnlyRoutes: string[] = [
  // regex for routes that require admin authentication
];

const withAdminsAuthentication: MiddlewareFactory =
  (next) => async (request, event) => {
    const path = new URL(request.url).pathname;
    for (const route of adminsOnlyRoutes) {
      const regex = new RegExp(route);
      if (regex.test(path)) {
        // the route is in the list of routes that require authentication
        // validate if the user is authenticated
        if (request.user == null) {
          return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }
        const admin = getAdminByUserId(request.user.id);
        if (admin instanceof Error) {
          return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }
        return await next(request, event);
      }
    }
    // the route is not in the list of routes that require authentication
    return await next(request, event);
  };

export default withAdminsAuthentication;

by debugging line by line I found that the error was caused by getAdminByUserId which uses prisma. it is confusing for me that I am getting the error even though the adminsOnlyRoutes array is empty

it seems like I cannot use prisma in the middleware.

can anyone explain me why and suggest any solution

1 Answer 1

0

we cannot use prisma in the edge runtime yet.

using prisma in edge run time leads to unexpected behaviors like this.

follow this Github issue for more informations

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.