I saw this article about connecting MongoDB when the project started.
After I implemented it. The project works without any issues.
But after implementing middleware I get this error every time I make a call
Below are the codes
instrumentation.ts
import { connectToMongoDB } from "@/lib/mongoose";
export async function register() {
await connectToMongoDB();
}
mongoose.ts
import mongoose, { Connection } from "mongoose";
let cachedConnection: Connection | null = null;
export async function connectToMongoDB() {
if (cachedConnection) {
console.log("Using cached db connection");
return cachedConnection;
}
try {
const cnx = await mongoose.connect(process.env.MONGODB_URI!);
cachedConnection = cnx.connection;
console.log("New mongodb connection established");
return cachedConnection;
} catch (error) {
console.log(error);
throw error;
}
}
middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
console.log("test middleware");
return NextResponse.redirect(new URL("/home", request.url));
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ["/api/onboarding/:path*"],
};
MAY I KNOW WHAT THE REAL ISSUE IS. HOW TO FIX THAT
tried to move both files to app, also removed await
from instrumentations.ts
import { connectToMongoDB } from "@/lib/mongoose";
export async function register() {
if (process.env.NEXT_RUNTIME !== 'nodejs') return;
await connectToMongoDB();
}