Summary:
Opt for a dynamic import instead of the traditional method:
import mongoose from 'mongoose';
export const connectDb = async () => {
try {
await mongoose.connect('your-connection-string', { });
} catch (error) {
// exit process with failure
process.exit(1);
}
};
Consider this approach:
import dynamic from 'next/dynamic';
// import mongoose from 'mongoose';
export const connectDb = async () => {
try {
// Dynamically load mongoose
const mongoose = (await import('mongoose')).default;
await mongoose.connect('your-connection-string', { });
} catch (error) {
// exit process with failure
process.exit(1);
}
};
Check out the documentation here: Dynamic Imports
What makes this method effective?
Luca's explanation is on point:
If you encounter an error in the browser, it indicates that you are attempting to use Mongoose in your client-side code.
Mongoose internally validates the node installation version within its code.
In essence, node.js
is not accessible on the client side of a next.js project, but it operates smoothly within server-side contexts like getServerSideProps
or /pages/api
. It is best utilized within the /pages/api
directory for optimal performance.