I was writing the backend of my Next.js application and I tried to use the _middleware files functionality to connect to my MongoDB database. But it throws the following error:
./node_modules/mongodb/lib/connection_string.js:5:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/mongodb/lib/mongo_client.js
./node_modules/mongodb/lib/index.js
./pages/api/_middleware.ts
https://nextjs.org/docs/messages/module-not-found
Now, I know that via the file next.config.js I could fix this but:
- There are a bunch of them, it's not just fs,
- I guess I'm doing something wrong because this behaviour is pretty weird
First middleware:
import { NextApiRequest } from "next";
import { MongoClient, Db } from 'mongodb'
import { NextResponse } from "next/server";
export type NextRequestDB = NextApiRequest & {
db: Db
}
export default (req: NextRequestDB) => {
const client = new MongoClient(process.env.DATABASE_URL!)
client.connect()
req.db = client.db('hey-there')
return NextResponse.next()
}
Second middleware:
import { NextRequestDB } from "../_middleware"
import {Collection} from 'mongodb'
import { NextResponse } from "next/server"
export type NextRequestCollection = NextRequestDB & {
collection: Collection
}
export default (req: NextRequestCollection) => {
req.collection = req.db.collection('Users')
return NextResponse.next()
}