-
SummaryMay I know how to solve this issue of Error: The edge runtime does not support Node.js 'crypto' module? This error happened after I added the middleware.ts file. this my .env.local POSTGRES_URL=
APP_ENV=local
# Must follow naming convention for NextAuth v5 to work
AUTH_SECRET=
AUTH_GITHUB_ID=
AUTH_GITHUB_SECRET=
AUTH_GOOGLE_ID=
AUTH_GOOGLE_SECRET= middleware.ts import { auth } from "@/lib/auth/auth"
export default auth((req) => {
// req.auth
console.log("Route Middleware", req.nextUrl.pathname)
})
// Optionally, don't invoke Middleware on some paths
// Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = {
// if you dont match anything, the website will work.
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
// matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
} the file at @/lib/auth/auth // auth.ts
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
import Google from "next-auth/providers/google"
import CredentialsProvider from "next-auth/providers/credentials";
import { db } from "@/lib/db/index"
import { eq } from "drizzle-orm";
import { getUserByEmail } from "@/data/user";
import { users } from "../db/schema";
let userInfo = {
id: "",
email: "",
name: "",
}
// sign in with email and password
async function authorize(credentials: any) {
if (!credentials?.email || !credentials.password) {
return null;
}
let user = await getUserByEmail(credentials.email as string);
if (!user?.length) {
return null;
}
userInfo = {...user as any};
return user;
}
// sign in with google or github
async function signIn({ user, account, credentials }: { user: any; account: any; credentials: any }) {
// prevent signInUser from running if authorizeUser has already run
if(credentials?.email){
return true;
}
if (account?.provider === "google" || account?.provider === "github") {
try {
if(user?.email){
let result = await getUserByEmail(user.email);
if (result?.length === 0) {
await db.insert(users).values({ name: user.name as string ,email: user.email as string, password: account.provider as string });
result = await getUserByEmail(user.email);
}
userInfo = {...result as any};
return true;
}
} catch (err) {
console.log(err);
return false;
}
}
return false;
}
async function jwt({ token, user, account }: { token: any; user: any; account: any }) {
// cant use the user object to get the id cus the data is not updated when using oauth but only in credentials login
// user object contains info from credentials or from oauth default user object, it will then disappaer aftre this function runs
if (user || account?.provider === "google" || account?.provider === "github") {
return userInfo;
}
return token;
}
async function session({ session, token }: { session: any; token: any }) {
if (token) {
session.user = token;
}
return session.user;
}
export const {
handlers: { GET, POST },
auth,
// signIn,
signOut,
} = NextAuth({
secret: process.env.AUTH_SECRET,
providers: [GitHub,Google,
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
placeholder: "[email protected]",
},
password: { label: "Password", type: "password" },
},
authorize
}),
],
pages : {
signIn: '/login',
},
callbacks: {
signIn,
jwt,
session
}
}) this is the file at app/api/auth/[...nextauth]/route.ts export { GET, POST } from "@/lib/auth/auth"; This is the error logged in the terminal. ⚠ ./node_modules/.pnpm/[email protected]/node_modules/pg/lib/native/client.js
Module not found: Can't resolve 'pg-native' in 'C:\Users\User\Desktop\webwebweb\food-order\node_modules\.pnpm\p[email protected]\node_modules\pg\lib\native'
Import trace for requested module:
./node_modules/.pnpm/[email protected]/node_modules/pg/lib/native/client.js
./node_modules/.pnpm/[email protected]/node_modules/pg/lib/native/index.js
./node_modules/.pnpm/[email protected]/node_modules/pg/lib/index.js
./lib/db/index.ts
./lib/auth/auth.ts
⨯ Error: The edge runtime does not support Node.js 'crypto' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
at <unknown> (webpack-internal:///(middleware)/./node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/next/dist/esm/server/web/globals.js:33)
at Object.get (webpack-internal:///(middleware)/./node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/next/dist/esm/server/web/globals.js:33:19)
at eval (webpack-internal:///(middleware)/./node_modules/.pnpm/[email protected]/node_modules/pg/lib/crypto/utils-webcrypto.js:22:32)
at (middleware)/./node_modules/.pnpm/[email protected]/node_modules/pg/lib/crypto/utils-webcrypto.js (file://C:\Users\User\Desktop\webwebweb\food-order\.next\server\middleware.js:1251:1)
at __webpack_require__ (file://C:\Users\User\Desktop\webwebweb\food-order\.next\server\edge-runtime-webpack.js:37:33)
at fn (file://C:\Users\User\Desktop\webwebweb\food-order\.next\server\edge-runtime-webpack.js:285:21)
at eval (webpack-internal:///(middleware)/./node_modules/.pnpm/[email protected]/node_modules/pg/lib/crypto/utils.js:8:20)
at (middleware)/./node_modules/.pnpm/[email protected]/node_modules/pg/lib/crypto/utils.js (file://C:\Users\User\Desktop\webwebweb\food-order\.next\server\middleware.js:1262:1)
at __webpack_require__ (file://C:\Users\User\Desktop\webwebweb\food-order\.next\server\edge-runtime-webpack.js:37:33)
at fn (file://C:\Users\User\Desktop\webwebweb\food-order\.next\server\edge-runtime-webpack.js:285:21)
at eval (webpack-internal:///(middleware)/./node_modules/.pnpm/[email protected]/node_modules/pg/lib/crypto/sasl.js:3:16) {
middleware: true
} Additional informationNo response Example |
Beta Was this translation helpful? Give feedback.
Replies: 11 comments 16 replies
-
same issue here =/ |
Beta Was this translation helpful? Give feedback.
-
You have to use the |
Beta Was this translation helpful? Give feedback.
-
because the runtime you are using is edge runtime which is not a node js server so crypto module is not available im also having this issue right now but i don't know to solve this |
Beta Was this translation helpful? Give feedback.
-
i encountered this issue and the solution come from this file middleware first thing import NextAuth from "next-auth"; import authConfig from "./auth.config"; this file in my case contains the following : import type { NextAuthConfig } from "next-auth" export default { then make that : const { auth } = NextAuth(authConfig); it should works now i hope you find this useful |
Beta Was this translation helpful? Give feedback.
-
I had the same issue when updating from v4 but actually while this error is showing up, the actual cause was related with something different: My I think that since the Removing the import and refactoring a little did the trick.
|
Beta Was this translation helpful? Give feedback.
-
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export function middleware(req: NextRequest) {
console.log("Route Middleware", req.nextUrl.pathname);
// You can add additional middleware logic here
return NextResponse.next();
}
// Optionally, don't invoke Middleware on some paths
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
// pages/api/auth/[...nextauth].ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import { db } from "@/lib/db/index";
import { getUserByEmail } from "@/data/user";
import { users } from "@/lib/db/schema";
let userInfo = {
id: "",
email: "",
name: "",
};
async function authorize(credentials: any) {
if (!credentials?.email || !credentials.password) {
return null;
}
let user = await getUserByEmail(credentials.email as string);
if (!user?.length) {
return null;
}
userInfo = { ...user as any };
return user;
}
async function signIn({ user, account, credentials }: { user: any; account: any; credentials: any }) {
if (credentials?.email) {
return true;
}
if (account?.provider === "google" || account?.provider === "github") {
try {
if (user?.email) {
let result = await getUserByEmail(user.email);
if (result?.length === 0) {
await db.insert(users).values({ name: user.name as string, email: user.email as string, password: account.provider as string });
result = await getUserByEmail(user.email);
}
userInfo = { ...result as any };
return true;
}
} catch (err) {
console.log(err);
return false;
}
}
return false;
}
async function jwt({ token, user, account }: { token: any; user: any; account: any }) {
if (user || account?.provider === "google" || account?.provider === "github") {
return userInfo;
}
return token;
}
async function session({ session, token }: { session: any; token: any }) {
if (token) {
session.user = token;
}
return session.user;
}
export const {
handlers: { GET, POST },
auth,
signOut,
} = NextAuth({
secret: process.env.AUTH_SECRET,
providers: [GitHub, Google,
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
placeholder: "[email protected]",
},
password: { label: "Password", type: "password" },
},
authorize
}),
],
pages: {
signIn: '/login',
},
callbacks: {
signIn,
jwt,
session
}
}); What did I fix from your code ?
|
Beta Was this translation helpful? Give feedback.
-
If you are able to use the This should work fine for cases where you don't need a |
Beta Was this translation helpful? Give feedback.
-
I solved this issue by not attempting to use MongoDB directly from the Next-Auth callback functions. It seems only Edge runtime is supported within this scope, meaning you can't use many internal node packages (including Instead I make an internal API route and invoke using
// Edge runtime. Limited support of built-in node module. E.g `crypto` is not supported and will fail at runtime.
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
// Docs:
// https://next-auth.js.org/configuration/providers/oauth
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
allowDangerousEmailAccountLinking: true,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
}),
],
// Docs
// https://next-auth.js.org/configuration/callbacks
callbacks: {
async jwt({ trigger, token, account, profile, user }) {
if (trigger === 'signUp') {
try {
const response = await fetch(`${process.env.NEXTAUTH_URL}/api/user`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({token, account, profile, user}),
});
if (!response.ok) {
console.error("Failed to create user:", await response.json());
}
} catch (error) {
console.error("Error calling API:", error);
}
}
return token;
},
},
}); Then in the route handler, I can safely do my DB instantiation and a variety of operations using the node.js runtime rather than Edge.
// Nodejs runtime. Full support of node.js runtime. Do what you want.
import { connectMongoDB } from '@/lib/common/mongodb/connect';
import { UserQuery } from '@/lib/services/mongodb/user-query';
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
try {
await connectMongoDB(); // Singleton style connector
const body = await req.json();
const user: any = await UserQuery.getInstance().create(body);
return NextResponse.json({ status: 'success', data: { id: user.id} });
} catch (error) {
console.error(error);
return NextResponse.json(
{ status: 'error', message: 'Failed to create user' },
{ status: 500 }
);
}
} |
Beta Was this translation helpful? Give feedback.
-
I solved it this way // middleware.ts
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const protectedPaths = [
"/dashboard",
];
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const isProtectedPath = protectedPaths.some((prefix) =>
path.startsWith(prefix)
);
if (isProtectedPath) {
const token = (await cookies()).get('authjs.session-token');
if (!token) {
const url = new URL("/", request.url);
return NextResponse.redirect(url);
}
}
return NextResponse.next();
}
// Configure matcher to specify which paths middleware will run on
export const config = {
matcher: [
"/((?!api|_next|static|favicon.ico|sitemap.xml).*)",
],
}; |
Beta Was this translation helpful? Give feedback.
-
The same error occurs when I'm trying to validate my JSON Web Token. The alternative is the jose library, but I don't want to use it because I prefer not to install too many libraries in my project. I'm trying hard to fix the issue, so if anyone knows a solution, please help. |
Beta Was this translation helpful? Give feedback.
-
Good news everyone, Node.js Middleware support landed in Next.js 15.2 (experimental). This is now ready for testing. For any issues you run into, please open new issues so we can track and address before marking it as stable. Thank you! https://nextjs.org/blog/next-15-2#nodejs-middleware-experimental |
Beta Was this translation helpful? Give feedback.
Good news everyone, Node.js Middleware support landed in Next.js 15.2 (experimental). This is now ready for testing. For any issues you run into, please open new issues so we can track and address before marking it as stable. Thank you!
https://nextjs.org/blog/next-15-2#nodejs-middleware-experimental