Webpack with Next.js bundles file it is not supposed to in client bundle

I have a Next.js app with mongoose to connect to my mongodb. The models import db.ts to make sure that there is an active connection to the database like so:

import { model, models, Schema } from "mongoose";
import "../../db";

This is the code that connects to my database:

import mongoose from "mongoose";
mongoose.connect("mongodb://admin:admin@localhost:27022/admin");

I have gone ahead and made some serverless functions in next.js and added some database fetching from the models in my getServerSideProps. All of which worked perfectly fine. I can interact with the models, create new Documents, delete them and update them. there are no issues.

The Problem

I recently added a new component: it is at /pages/flashcards/[id].tsx. Just like my other components, this one imports one of my mongoose models. However, for some reason, Webpack feels like it should bundle the model and its import of ../../db and send it and send it over to the client, which results in this error:

TypeError: mongoose__WEBPACK_IMPORTED_MODULE_0___default(...).connect is not a function

Again: This does not happen with any of my other components which use the exact same models as the component which is having these problems.


The issue occurs because you have the following unused import in the /pages/flashcards/[id] page.

import question from "../../db/models/question";

Any code inside getServerSideProps or getStaticProps, and imports used exclusively by these methods, is removed by Next.js when building the client bundle.

However, since question is not explicitly being used in getServerSideProps, Next.js can't figure out the import is only meant to be used on the server. This means it will be included in both the server and client bundles.

You can use the Next.js Code Elimination tool to verify what Next.js eliminates from the client-side bundle. You'll see that if you run your page's code through it, the import is not removed. However, as soon as you reference and use it inside getServerSideProps, Next.js automatically eliminates it from the imports.

Make sure to always comment out/remove unused imports (there are linting rules to help you do that).