Replies: 9 comments 9 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.
-
Summary
May 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
the file at @/lib/auth/auth
this is the file at app/api/auth/[...nextauth]/route.ts
This is the error logged in the terminal.
Additional information
No response
Example
https://github.com/haocloo/issue
Beta Was this translation helpful? Give feedback.
All reactions