question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js imports browser bundle in `_middleware` file of api

See original GitHub issue

What version of Next.js are you using?

12.0.7

What version of Node.js are you using?

16.13.1

What browser are you using?

Chromse

What operating system are you using?

Windows

How are you deploying your application?

Next start

Describe the Bug

We are trying to connect to MongoDB inside the _middleware file of the api. We are using mongoose as the driver but when calling our connect funtion from inside the pages/api/_middleware.ts the browser bundle of mongoose is being imported instead of the default Node bundle. This causes our connection to fail

warn  - ./node_modules/mongoose/dist/browser.umd.js
`eval` not allowed in Middleware pages/api/_middleware
TypeError: mongoose__WEBPACK_IMPORTED_MODULE_0___default(...).connect is not a function
    at dbConnect (webpack-internal:///./src/utils/dbConnect.ts:13:77)
    at Object.handler (webpack-internal:///./pages/api/_middleware.ts:5:75)
    at adapter (webpack-internal:///./node_modules/next/dist/server/web/adapter.js:30:35)
    at Module.__WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///./node_modules/next/dist/build/webpack/loaders/next-middleware-loader.js?page=%2Fapi%2F_middleware&absolutePagePath=D%3A%5CIO-DOCK%5Cauth-api%5Cpages%5Capi%5C_middleware.ts!:17:87)
    at Object.run (D:\ ...\node_modules\next\dist\server\web\sandbox\sandbox.js:164:30)
    at DevServer.runMiddleware (D:\ ...\node_modules\next\dist\server\next-server.js:423:46)
    at async DevServer.runMiddleware (D:\ ...\node_modules\next\dist\server\dev\next-dev-server.js:383:28)
    at async Object.fn (D:\ ...\node_modules\next\dist\server\next-server.js:784:34)
    at async Router.execute (D:\ ...\node_modules\next\dist\server\router.js:210:32)
    at async DevServer.run (D:\ ...\node_modules\next\dist\server\next-server.js:1085:29)

The eval not allowed warning is probably caused because the browser bundle is used and it uses eval.

Expected Behavior

When the _middleware file is positioned inside the api folder it should not import the bundles for the browser but rather the default Node package. It probably imports the browser bundle because _middleware files are primarily used on the frontend side.

To Reproduce

This is our connection function which we want to call inside the _middleware file.

import mongoose from 'mongoose';

async function dbConnect() {
  try {
    // check if we have a connection to the database or if it's currently
    // connecting or disconnecting (readyState 1, 2 and 3)
    if (mongoose.connection?.readyState >= 1) {
      return;
    }

    const mongo = await mongoose.connect(process.env.MONGO_URL!, {
      dbName: 'core-auth',
    });
    if (!mongo) console.error('No connection to the DB established');
    return mongo;
  } catch (error) {
    console.error('Mongoose failed to connect to the DB');
    console.error(error);
  }
}

export default dbConnect;

This is our _middleware file:

import { NextFetchEvent, NextRequest } from 'next/server';
import dbConnect from '../../src/utils/dbConnect';

const handler = async (_req: NextRequest, _event: NextFetchEvent) => {
  await dbConnect();
};

export default handler;

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:13
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
IAmJakProcommented, Feb 7, 2022

I am facing exactly the same issue, have you found any solution for that?

1reaction
Klerithcommented, Feb 7, 2022

Same over here…

Read more comments on GitHub >

github_iconTop Results From Across the Web

Advanced Features: Middleware - Next.js
Middleware allows you to run code before a request is completed, then based on the incoming request, you can modify the response by...
Read more >
Advanced Features: Dynamic Import - Next.js
Dynamically import JavaScript modules and React Components and split your code into manageable chunks.
Read more >
URL Imports - next.config.js
URL imports are an experimental feature that allows you to import modules directly from external servers (instead of from the local disk).
Read more >
next.config.js: Introduction
next.config.js is a regular Node.js module, not a JSON file. It gets used by the Next.js server and build phases, and it's not...
Read more >
Advanced Features: Next.js Compiler
js Compiler, written in Rust using SWC, allows Next.js to transform and minify your JavaScript code for production. This replaces Babel for individual...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found