Search code examples
javascripttypescriptmongodbnext.jsvercel

Middleware next can't connect to mongo


The next code is a middleware for Next. The idea is read the subdomain and search into the database if the subdomain exists.

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();
     })
  
});
}

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

But when I try to connect to mongo, it throws me this error on console:

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

Solution

  • I got it!.

    I just updated the mongodb version. And the error message is:

    error Error: The edge runtime does not support Node.js 'stream' module.
    

    This because Mongoose does not currently support Next.js Edge Runtime.https://mongoosejs.com/docs/nextjs.html