Connection to mongo is currently unavailable for Middleware next

This code snippet shows a middleware for Next, which is designed to read the subdomain and check if it exists in the database.

import { getValidSubdomain } from '@/lib/getValidSubdomain';
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import * as mongoDB from 'mongodb';
let cachedDb: mongoDB.Db = null;

export function middleware(req: NextRequest) {
  const host = req.headers.get('host');
  const subdomain = getValidSubdomain(host);
  console.log({subdomain})

  if(!subdomain) return NextResponse.next()
  console.log({MONGOURL: process.env.MONGO_URL})

   mongoDB.MongoClient.connect(process.env.MONGO_URL, {
     useNewUrlParser: true,
     useUnifiedTopology: true,
   })
     .then((client) => {
       const db = client.db();
     })
  
});
}

// Learn more about "Matching Paths" below
export const config = {
  matcher: '/(.*)',
}

However, when attempting to connect to MongoDB, an error is thrown on the console:

- error node_modules/bson/lib/bson/symbol.js (2:0) @ <unknown>
- error Cannot read properties of undefined (reading 'custom')

Answer №1

Ah-ha! Success!

After updating the version of MongoDB, I encountered the following error message:

Error: The Node.js 'stream' module is not supported by the edge runtime.

This issue arose because Mongoose does not currently work with Next.js Edge Runtime. Learn more at https://mongoosejs.com/docs/nextjs.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the content within table cells by utilizing JavaScript functions linked to specific IDs

I am currently working on a project that involves a dropdown list: <select id="itemsList" onchange="gettingList()"> <option>Please choose an option</option> <option value="50">Shampoo</option ...

Guidelines for implementing a seamless transition effect on elements with Tailwind CSS

I successfully created a responsive nav bar using Tailwind CSS in Next.js, and it is functioning perfectly. https://i.stack.imgur.com/yTCbs.png https://i.stack.imgur.com/rdXhL.png https://i.stack.imgur.com/J8fM6.png Everything works well, except when I ...

The State Hook error "state variable is not defined" arises due to an issue with the state declaration in

function Header() { const [keys, setKeys] = useState([]); //custom addition const first = (e) => { var result = new Map() axios.post('http://localhost:8000/' + query) .then(function(response){ var content ...

The TypeORM connection named "default" could not be located during the creation of the connection in a Jest globalSetup environment

I've encountered a similar issue as the one discussed in #5164 and also in this thread. Here is a sample of working test code: // AccountResolver.test.ts describe('Account entity', () => { it('add account', async () => { ...

Obtaining the host and port information from a mongoose Connection

Currently, I am utilizing mongoose v5.7.1 to connect to MongoDb in NodeJS and I need to retrieve the host and port of the Connection. However, TypeScript is throwing an error stating "Property 'host' does not exist on type 'Connection'. ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Ensure that the Promise is resolved upon the event firing, without the need for multiple event

I'm currently working on a solution where I need to handle promise resolution when an EventEmitter event occurs. In the function containing this logic, an argument is passed and added to a stack. Later, items are processed from the stack with differe ...

Why is the Routes module failing to acknowledge the component?

I am in the process of developing my own Portfolio and decided to use Angular 12. Despite following all of the instructions on angular.io, I am facing challenges with Routing. To demonstrate my work more effectively, I have created a Stack Blitz: My Portf ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error messa ...

Remove the initial DIV element from the HTML code

I have created a unique chat interface by combining JScript, php, and jquery. The chat messages are saved in an HTML document that gets displayed in the text area. Each user input message is contained within its individual div tag: <div>Message</ ...

During operational hours, an Ajax request may cause interruptions to the website's functionality

Having an issue with a large ajax request: I am querying a PHP file that makes some cURL requests, taking 15-20 seconds to complete and then returning JSON on my webpage. It's a standard ajax request, but I found a strange bug. While the ajax query i ...

What is the correct method for typing sagas?

After diligently following the official redux documentation for integrating with TypeScript, which can be found at https://redux.js.org/recipes/usage-with-typescript, I successfully typed actions, reducers, react components, and more. However, my progress ...

Executing a JavaScript function by utilizing the # symbol in the URL: Tips and Tricks

It all began with a function called loadround that changed the innerHTML of an iframe. The links within the iframe would then change the page when clicked, but hitting the back button made the loadround page vanish. I pondered over this issue multiple time ...

What is the best way to save session data in MongoDB with NodeJS?

Utilizing the connect-mongo module, I am able to store sessions from express in mongodb. Here is how you can implement it: app.use(express.session({ 'secret': config.APP_SECRET, 'store': new MongoStore({ 'db': ...

Error 404: Page not found in Node.js

I attempted to troubleshoot this issue, but when I visited localhost:5000, an error message appeared: Cannot GET / //*****************app.js************ const express = require('express'); const mongoose = require('mongoose'); co ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

Using for loop in AJAX Done() function

I'm currently working on a for loop that loops through an array consisting of 3 different report numbers. For each value in the array, an AJAX request is sent out. What I want to achieve is having a unique behavior for the .done() function based on th ...

Is there a way to ensure a Javascript alert appears just one time and never again?

I struggle with Javascript, but I have a specific task that needs to be completed. I am participating in a school competition and need an alert to appear only once throughout the entire project, not just once per browsing session. The alert will inform ...