#Next-Auth Error?

13 messages · Page 1 of 1 (latest)

hoary pond
#
./node_modules/bcryptjs/dist/bcrypt.js
A Node.js API is used (process.nextTick at line: 351) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/bcryptjs/dist/bcrypt.js
./lib/auth.config.ts
./lib/auth.ts

./node_modules/bcryptjs/dist/bcrypt.js
A Node.js API is used (setImmediate at line: 352) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/bcryptjs/dist/bcrypt.js
./lib/auth.config.ts
./lib/auth.ts

./node_modules/bcryptjs/dist/bcrypt.js
A Node.js API is used (setImmediate at line: 352) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/bcryptjs/dist/bcrypt.js
./lib/auth.config.ts
./lib/auth.ts

./node_modules/bcryptjs/dist/bcrypt.js
A Node.js API is used (process.nextTick at line: 352) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/bcryptjs/dist/bcrypt.js
./lib/auth.config.ts
./lib/auth.ts

what is the solution?

analog flareBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

hoary pond
#

auth.config.ts

import type { NextAuthConfig } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcryptjs";
import prisma from "prismadb";

export default {
  providers: [
    CredentialsProvider({
      id: "credentials",
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password) {
          throw new Error("Something went wrong.");
        }

        try {
          const user = await prisma.user.findUnique({
            where: {
              email: credentials.email as string,
            },
          });
          const isPasswordCorrect = await compare(
            credentials?.password as string,
            user?.password as string
          );
          if (user) {
            if (isPasswordCorrect) {
              return Promise.resolve(user);
            } else {
              throw new Error("Incorrect Credentials!");
            }
          } else {
            throw new Error("No such user found!");
          }
        } catch (err) {
          throw new Error(err as string);
        }
      },
    }),
  ],
  session: {
    strategy: "jwt",
    maxAge: 24 * 60 * 60, // 1 day
    updateAge: 60 * 60, // 1 hour
  },
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.uid as string;
      }
      return session;
    },
    async jwt({ token, user }: any) {
      if (user) {
        let { password, ...userInfo } = user;
        token.role = userInfo.role;
        token.user = userInfo;
      }
      return token;
    },
  },
} satisfies NextAuthConfig;

#

auth.ts

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

export const { handlers, auth, signIn, signOut } = NextAuth({
  secret: process.env.NEXTAUTH_SECRET,
  debug: process.env.NODE_ENV !== "production",
  adapter: PrismaAdapter(prisma),
  ...authConfig,
});
dreamy hamlet
#

From what I understood, bcrypt can't run on Edge Runtime. If you're using middleware.js for example, you can't use that.

If I'm not mistaken, the solution is adding all the providers only in the auth.ts and in your middleware.ts you will then import only the auth.config.ts

hoary pond
#
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import createIntlMiddleware from "next-intl/middleware";
import { auth } from "auth";

const locales = ["en", "de", "ru", "fr"];
const authPages = ["/login", "/register"];
const publicPages = [
  "/",
  "/login",
  "/register",
  "/create-reservation",
  "/services",
  "/contact",
  "/about-us",
  "/mission-vision",
  "/our-privacy-policy",
  "/query",
];

const intlMiddleware = createIntlMiddleware({
  locales,
  defaultLocale: "en",
  localePrefix: "always",
});
const testPathnameRegex = (pages: string[], pathName: string): boolean => {
  return RegExp(
    `^(/(${locales.join("|")}))?(${pages
      .flatMap((p) => (p === "/" ? ["", "/"] : p))
      .join("|")})/?$`,
    "i"
  ).test(pathName);
};

const authMiddleware = auth((req) => {
  const isAuthPage = testPathnameRegex(authPages, req.nextUrl.pathname);
  const session = req.auth;

  // Redirect to sign-in page if not authenticated
  if (!session && !isAuthPage) {
    return NextResponse.redirect(new URL("/login", req.nextUrl));
  }

  // Redirect to home page if authenticated and trying to access auth pages
  if (session && isAuthPage) {
    return NextResponse.redirect(new URL("/", req.nextUrl));
  }

  return intlMiddleware(req);
});

const middleware = (req: NextRequest) => {
  const isPublicPage = testPathnameRegex(publicPages, req.nextUrl.pathname);
  const isAuthPage = testPathnameRegex(authPages, req.nextUrl.pathname);

  if (isAuthPage) {
    return (authMiddleware as any)(req);
  }

  if (isPublicPage) {
    return intlMiddleware(req);
  } else {
    return (authMiddleware as any)(req);
  }
};

export const config = {
  matcher: ["/((?!api|_next|.*\\..*).*)"],
};

export default middleware;
#

import { auth } from "auth"; => auth.ts

dreamy hamlet
#

You should be importing the auth.conf.ts and creating a new NextAuth client in there. Also, move all the providers that require bcrypt out of there, that code will run on edge runtime and break

hoary pond
hoary pond
#

@dreamy hamlet Currently, I have completely removed "bcryptjs" from everywhere to try it, but while there is no problem with "npm run build", I am currently getting an error when running "docker build".
npm updated 10.6.0

> [deps 4/4] RUN npm install:
107.3 npm notice 
107.3 npm notice New minor version of npm available! 10.5.0 -> 10.6.0
107.3 npm notice Changelog: <https://github.com/npm/cli/releases/tag/v10.6.0>
107.3 npm notice Run `npm install -g [email protected]` to update!
107.3 npm notice 
107.3 npm ERR! code ERESOLVE
107.3 npm ERR! ERESOLVE could not resolve
107.3 npm ERR!
107.3 npm ERR! While resolving: [email protected]
107.3 npm ERR! Found: [email protected]
107.3 npm ERR! node_modules/react
107.3 npm ERR!   react@"^18" from the root project
107.3 npm ERR!   peer react@"^16.8 || ^17.0 || ^18.0" from @radix-ui/[email protected]
107.3 npm ERR!   node_modules/@radix-ui/react-dialog
107.3 npm ERR!     @radix-ui/react-dialog@"^1.0.5" from the root project
107.3 npm ERR!   7 more (react-dom, @radix-ui/react-dropdown-menu, ...)
107.3 npm ERR!
107.3 npm ERR! Could not resolve dependency:
107.3 npm ERR! @reduxjs/toolkit@"^2.2.1" from the root project
107.3 npm ERR!
107.3 npm ERR! Conflicting peer dependency: [email protected]
107.3 npm ERR! node_modules/react
107.3 npm ERR!   peer react@"18.2.0" from [email protected]
107.3 npm ERR!   node_modules/react-native
107.3 npm ERR!     peerOptional react-native@">=0.69" from [email protected]
107.3 npm ERR!     node_modules/react-redux
107.3 npm ERR!       react-redux@"^9.1.0" from the root project
107.3 npm ERR!       1 more (@reduxjs/toolkit)
107.3 npm ERR!
107.3 npm ERR! Fix the upstream dependency conflict, or retry
107.3 npm ERR! this command with --force or --legacy-peer-deps
107.3 npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
jade jolt