1

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()
}
  • Does this answer your question: [Next.js middleware Module not found: Can't resolve 'fs'](https://stackoverflow.com/questions/71106759/next-js-middleware-module-not-found-cant-resolve-fs)? You can't use Node.js native APIs (or packages that use them) in Next.js middleware. – juliomalves Apr 21 '22 at 08:15
  • 1
    @juliomalves Thank you, very helpful. Kind of a shame tho, it takes away a ton of its application. – Alessandro Tornesi Apr 21 '22 at 18:52

0 Answers0