Using Next.js 14 app router with mongoose, I encounter this error as soon as I import a server action into my middleware:
⨯ src\models\nachricht.ts (38:0) @ <unknown>
⨯ Cannot read properties of undefined (reading 'Message')
36 | );
37 |
> 38 | export default mongoose.models.Message || mongoose.model('Message', messageSchema)
The root of the issue seems to be that [middleware in Next.js is an edge runtime and DB connections aren't recommended in there](#1142075909856305162 message).
Why isn't it possible to connect to a DB in Next.js middleware? And what's the alternative?
(Temporary) solution
I've solved the problem temporarily by moving saveMessage() to a seperate file for server actions which establish database connection and use models.
But this is indeed only a temporary fix, because sooner or later the getUniqueCityNamesAndSlugs() action will also work with a database connection (instead of a JSON file).
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.