Next.js Discord

Discord Forum

Why cant i connect to mongoose in my middleware.ts?

Unanswered
Banana posted this in #help-forum
Open in Discord
Middleware.ts:
import { NextRequest, NextResponse } from 'next/server';
import connectDB from '@/utils/db';
import { Mongoose } from 'mongoose';

export async function middleware(req: NextRequest) {
  await connectDB();

  const Analytics = (await import('@/Models/Analytics')).default;

  const ip = req.headers.get('x-forwarded-for') || req.ip || '0.0.0.0';
  const userAgent = req.headers.get('user-agent') || 'unknown';
  const path = req.nextUrl.pathname;

  const analytics = new Analytics({
    ip,
    userAgent,
    path,
  });

  await analytics.save();

  return NextResponse.next();
}

export const config = {
  matcher: '/:path*',
};

Db.ts:
import mongoose, { Mongoose } from 'mongoose';

const MONGO_URL = process.env.MONGO_URL as string;

if (!MONGO_URL) {
  throw new Error('Please define the MONGO_URL environment variable inside .env.local');
}

declare global {
  var mongoose: {
    conn: Mongoose | null;
    promise: Promise<Mongoose> | null;
  };
}

const globalWithMongoose = global as typeof globalThis & {
  mongoose: {
    conn: Mongoose | null;
    promise: Promise<Mongoose> | null;
  };
};

let cached = globalWithMongoose.mongoose;

if (!cached) {
  cached = globalWithMongoose.mongoose = { conn: null, promise: null };
}

async function connectDB(): Promise<Mongoose> {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    cached.promise = mongoose.connect(MONGO_URL).then((mongoose) => {
      return mongoose;
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

export default connectDB;

2 Replies

.
Transvaal lion
Hi, mongoose doesn’t support the nextjs edge runtime, you can import it but it won’t be able to create a connection. This is because the edge runtime doesn’t support the net api from node which is used by the MongoDB node driver to connect to a db. Hope this helps!