0

hi i want to connect my nextjs app with mongoose to mongodb database but when i type await dbconnect() it return an error saying i should set topLevelAwait=true but in nextjs.config file there is not such thing even when i type it myself it return the same error

i tried googling it and i found a stackoverflow question but it was for earlier version of next-js and it dosnt work for next 13

file dbConect

import mongoose from "mongoose";

const dbConnect = async () => {
  try {
    const { connection } = mongoose.connect(
      "mongodb+srv://<username>:<password>@cluster0.slqa5pz.mongodb.net/?retryWrites=true&w=majority"
    );
    if (connection.readyState == 1) {
      console.log("database connected");
    }
  } catch (error) {
    console.log(error);
  }
};

export default dbConnect;

file api

import dbConnect from "@/database/dbConnect"
export async function GET(request) {
    await dbConnect()
    return new Response('Hello, Next.js!')
}

papar
  • 21
  • 3
  • Does this answer your question? [how can I use top level "await" in typescript next.js](https://stackoverflow.com/questions/68339243/how-can-i-use-top-level-await-in-typescript-next-js) – Yilmaz Mar 24 '23 at 21:40

1 Answers1

2

To activate top level await, you have to configure tour next.config.js file this way:

/** @type {import("next").NextConfig} */
module.exports = {
    experimental: { appDir: true, serverComponentsExternalPackages: ["mongoose"] },
    webpack(config) {
        config.experiments = { ...config.experiments, topLevelAwait: true };
        return config;
    }
};

Since you are using mongoose, I recommend to add serverComponentsExternalPackages option as put above. It might be not necessary in future nextjs updates, but so far I had to add it in order to make my project work.

Mathieu Guyot
  • 689
  • 5
  • 14