Next.js Discord

Discord Forum

Getting instrumentation hook error when adding middleware.ts

Answered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Answered by Cape lion
Middleware will run on the edge runtime, as far as I'm aware, mongoose will not work on that.

There's a discussion going about allowing the Node.js runtime for middleware: https://github.com/vercel/next.js/discussions/46722
View full answer

4 Replies

Cape lionOP
// middleware.ts
import { NextResponse, type NextRequest } from "next/server";

export const middleware = async (request: NextRequest) => {
  return NextResponse.redirect(new URL('/', request.url))
};

export const config = {};
// instrumentation.ts
import { connect } from "mongoose";

export const register = async () => {
  await connect(process.env.MONGO_URI!, {
    dbName: process.env.NODE_ENV === "development" ? "dev" : "prod",
  }).then(() => console.log("Connected to MongoDB"));
};
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    esmExternals: "loose",
    serverComponentsExternalPackages: ["mongoose"],
    instrumentationHook: true,
  },
};

export default nextConfig;
Cape lion
Middleware will run on the edge runtime, as far as I'm aware, mongoose will not work on that.

There's a discussion going about allowing the Node.js runtime for middleware: https://github.com/vercel/next.js/discussions/46722
Answer