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')