Next.js Discord

Discord Forum

Middleware function in NEXT JS does not allow to use async/await

Answered
Pigeon tremex posted this in #help-forum
Open in Discord
Pigeon tremexOP
This is my NEXT js middleware to connect to a certain database as per the API route
import { NextRequestWithAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
import { connectEventsDB } from "../API/connector/connector";

const connectDB = async (url: string) => {
  if(url === "events"){
    console.log("here")
    await connectEventsDB();
    console.log("here 2");
  }
}

export function middleware(request: NextRequestWithAuth) {
  const isAdminRoute = request.nextUrl.pathname.startsWith("/admin/")
  if (isAdminRoute) {
    if (!request.nextauth.token?.role) return NextResponse.rewrite(new URL("/login", request.url));
  }
  else {
    const urlName = request.nextUrl.pathname.split("/api/V1/")[1]; // Split the pathname by "/api/V1/" and get the second part
    connectDB(urlName)
      .then(() => {
        return NextResponse.next();
      })
      .catch((error) => {
        console.log("error is " + error);
      });

  }
}


export const config = {
  matcher: ["/admin/:path*", "/api/V1/:path*"]
}

Now here I get an error saying
A Node.js API is used (process.cwd) which is not supported in the Edge Runtime.

The issue is the presence of async await function above. When I remove it it works. What is the issue?
Answered by ᴉuɐpɹɐɐ
Middleware is run in the edge runtime. And not all of Node.js API is present in the edge runtime.
Thats why it throws an error.

Async/await can still be used in the middleware however keep in mind that middleware is supopsed to be lightweight. Ideally you shouldnt fetch or make db calls in your middleware. Keep middleware only for front-line auth check and modifying headers
View full answer

2 Replies

@Pigeon tremex This is my NEXT js middleware to connect to a certain database as per the API route js import { NextRequestWithAuth } from "next-auth/middleware"; import { NextResponse } from "next/server"; import { connectEventsDB } from "../API/connector/connector"; const connectDB = async (url: string) => { if(url === "events"){ console.log("here") await connectEventsDB(); console.log("here 2"); } } export function middleware(request: NextRequestWithAuth) { const isAdminRoute = request.nextUrl.pathname.startsWith("/admin/") if (isAdminRoute) { if (!request.nextauth.token?.role) return NextResponse.rewrite(new URL("/login", request.url)); } else { const urlName = request.nextUrl.pathname.split("/api/V1/")[1]; // Split the pathname by "/api/V1/" and get the second part connectDB(urlName) .then(() => { return NextResponse.next(); }) .catch((error) => { console.log("error is " + error); }); } } export const config = { matcher: ["/admin/:path*", "/api/V1/:path*"] } Now here I get an error saying A Node.js API is used (process.cwd) which is not supported in the Edge Runtime. The issue is the presence of async await function above. When I remove it it works. What is the issue?
Middleware is run in the edge runtime. And not all of Node.js API is present in the edge runtime.
Thats why it throws an error.

Async/await can still be used in the middleware however keep in mind that middleware is supopsed to be lightweight. Ideally you shouldnt fetch or make db calls in your middleware. Keep middleware only for front-line auth check and modifying headers
Answer