2

I am developing an application to learn NextJS and getting deeper to its concepts.

Im following a course that teaches most needed things to build a full-stack application using NextJS.

The stack I'm using : NextJS, Prisma, Postgresql, AuthJS

I'm consistently getting this error when I bring up my development server with : npm run dev

TypeError: Cannot read properties of undefined (reading 'modules')

This error only appears when I use middleware to protect some routes in my app.

These are files and information you may need to help me:

package.json

{
  "name": "next-match",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@auth/prisma-adapter": "^2.10.0",
    "@heroui/react": "^2.7.11",
    "@hookform/resolvers": "^5.1.1",
    "@prisma/client": "^6.11.1",
    "bcrypt": "^6.0.0",
    "framer-motion": "^12.19.1",
    "next": "15.3.4",
    "next-auth": "^5.0.0-beta.29",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-hook-form": "^7.58.1",
    "react-icons": "^5.5.0",
    "react-toastify": "^11.0.5",
    "zod": "^3.25.67"
  },
  "devDependencies": {
    "@eslint/eslintrc": "^3",
    "@types/bcrypt": "^5.0.2",
    "@types/node": "^20",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "autoprefixer": "^10.4.21",
    "eslint": "^9",
    "eslint-config-next": "15.3.4",
    "postcss": "^8.5.6",
    "prisma": "^6.10.1",
    "tailwindcss": "3.4.17",
    "typescript": "^5"
  }
}

auth.ts

import NextAuth from "next-auth";
import authConfig from "@/auth.config";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "./lib/prisma";

export const { handlers, auth, signIn, signOut } = NextAuth({
  callbacks: {
    session: async ({ token, session }) => {
      if (token.sub && session.user) {
        session.user.id = token.sub;
      }
      return session;
    },
  },
  adapter: PrismaAdapter(prisma),
  session: { strategy: "jwt" },
  ...authConfig,
});

auth.config.ts

import Credentials from "next-auth/providers/credentials";
import type { NextAuthConfig } from "next-auth";
import { loginSchema } from "./lib/schemas/login-form-schema";
import { getUserByEmail } from "./app/actions/auth-actions";
import { compare } from "bcrypt";

export default {
  providers: [
    Credentials({
      name: "credentials",
      authorize: async (creds) => {
        const validated = loginSchema.safeParse(creds);

        if (validated.success) {
          const { email, password } = validated.data;
          const user = await getUserByEmail(email);

          if (!user || !(await compare(password, user.password))) return null;

          return user;
        }

        return null;
      },
    }),
  ],
} satisfies NextAuthConfig;

middleware.ts

import { NextResponse } from "next/server";
import { AUTH_ROUTES, PUBLIC_ROUTES } from "./routes";
import { auth } from "./auth";

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;

  const isPublic = PUBLIC_ROUTES.includes(nextUrl.pathname);
  const isAuthRoute = AUTH_ROUTES.includes(nextUrl.pathname);

  if (isPublic) {
    return NextResponse.next();
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return NextResponse.redirect(new URL("/members", nextUrl));
    }
    return NextResponse.next();
  }

  if (!isPublic && !isLoggedIn) {
    return NextResponse.redirect(new URL("/login", nextUrl));
  }

  return NextResponse.next();
});

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.5.0: Tue Apr 22 19:48:46 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T8103
  Available memory (MB): 8192
  Available CPU cores: 8
Binaries:
  Node: 22.17.0
  npm: 10.9.2
  Yarn: N/A
  pnpm: 10.12.4
Relevant Packages:
  next: 15.3.4 // There is a newer version (15.3.5) available, upgrade recommended! 
  eslint-config-next: 15.3.4
  react: 19.1.0
  react-dom: 19.1.0
  typescript: 5.8.3
Next.js Config:
  output: N/A

Course repo: https://github.com/TryCatchLearn/next-match

What I tired:

  • At first I was using pnpm, I changed to npm to match the course instructions
  • I split configuration as you see in the code
  • I changed prisma-adapter and next-auth to match course version

Nothing worked.

Thanks <3

2 Answers 2

0

In your auth.ts file you're exporting auth from:
export const { handlers, auth, signIn, signOut } = NextAuth({});

But this auth is not compatible with next.js middleware. I think it's meant for API routes.
To use NextAuth inside middleware.ts, you have to use withAuth() from next-auth/middleware .

https://next-auth.js.org/tutorials/securing-pages-and-api-routes

Maybe the code below might help
middleware.ts

import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
import { AUTH_ROUTES, PUBLIC_ROUTES } from "./routes";

export default withAuth(
  function middleware(req) {
    const { nextUrl } = req;
    const isLoggedIn = !!req.nextauth?.token;

    const isPublic = PUBLIC_ROUTES.includes(nextUrl.pathname);
    const isAuthRoute = AUTH_ROUTES.includes(nextUrl.pathname);

    if (isPublic) {
      return NextResponse.next();
    }

    if (isAuthRoute && isLoggedIn) {
      return NextResponse.redirect(new URL("/members", nextUrl));
    }

    if (!isLoggedIn) {
      return NextResponse.redirect(new URL("/login", nextUrl));
    }

    return NextResponse.next();
  },
  {
    
    callbacks: {
      authorized: ({ token }) => !!token,
    },
  }
);

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response. Next auth doesn't export such a member as the error says: ``` Module '"next-auth/middleware"' has no exported member 'withAuth'.ts(2305) ``` I guess this version of next-auth doesn't support the way you mentioned
I have a similar problem, the withAuth has been depricated and removed from authjs (v5) as per authjs.dev/reference/nextjs/middleware and this authjs.dev/getting-started/migrating-to-v5 refer to the latest v5 docs
0

The problem was with using the bcrypt library; it's not compatible with the edge runtime, which is why I ran into the issue. I switched to bcryptjs, and the problem was resolved.

Edge runtime in Next.js refers to running your application code closer to the user, at the "edge" of the network, using platforms like Vercel Edge Functions. This runtime allows for faster responses and reduced latency by executing code closer to where users are located. However, certain libraries or features that rely on Node.js-specific APIs may not work in this environment.

For example:

  • Libraries like bcrypt, which depend on native Node.js modules, are not compatible with the edge runtime.

  • On the other hand, libraries like bcryptjs (a pure JavaScript implementation) work well in the edge runtime.

In Next.js, you can use middleware to run code at the edge before it reaches your API or pages. For example, Next.js middleware can be used to handle authentication, redirects, or logging right at the edge, improving the speed of requests.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.