1

I saw this article about connecting MongoDB when the project started.

After I implemented it. The project works without any issues.

Start console message

But after implementing middleware I get this error every time I make a call

Error

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

1 Answer 1

1
import { connectToMongoDB } from "@/lib/mongoose";

export async function register() {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return;
  await connectToMongoDB();
}
Sign up to request clarification or add additional context in comments.

Comments

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.