'How to use next() function in Next JS API like Express JS?

While making an API in Next JS, where I pass three parameter to my API function (req, res, next) here is the code :

import catchAsyncErrors from "../../../middleware/catchAsyncErrors.js";
import connectToMongo from "../../../middleware/db.js";
import isAuthenticatedUser from "../../../middleware/isAuthenticated";
import ErrorHandler from "../../../utils/errorHandler";

const handler = catchAsyncErrors(async (req, res, next) => {
  try {
    console.log(next); // Undefined
    if (req.method === "POST") {
      return next(new ErrorHandler("Not Allowed", 405));
      //     ^ Error
    } else {
      return res.status(500).send("INVALID REQUEST");
    }
  } catch (error) {
    console.log(error);
  }
});

export default connectToMongo(isAuthenticatedUser(handler));

I assure that ErrorHandler is working fine, but when I call this API it gives me the following Error:

TypeError: next is not a function
at eval (webpack-internal:///(api)/./pages/api/auth/test.js:19:20)
at eval (webpack-internal:///(api)/./middleware/catchAsyncErrors.js:3:25)
at eval (webpack-internal:///(api)/./middleware/isAuthenticated.js:22:16)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

In Express JS we pass next parameter to call next function or error handler but it seems like it doesn't work with Next JS. I am new in this framework so I need your help in this.



Solution 1:[1]

So I found that we cannot use next() function in next JS like we used to do in express JS. Next JS API function accept only two parameters (req, res).

To use next() function to call other middleware, check out the bellow example :

import middleware1 from './middleware/func1';
import middleware2 from './middleware/func2';

const handler = async(req, res)=>{
//Your Code here
}

export default middleware1(middleware2(handler));

In the middleware functions:

middleware 1 :

const middleware1 = (handler) => {
return (req, res) =>{
//middleware function here
     return handler(req, res)
  }
}

export default middleware1;

middleware 2 :

const middleware2 = (handler) => {
return (req, res) =>{
//middleware function here
     return handler(req, res)
  }
}

export default middleware2;

As you can see both middleware take handler in parameter and return handler at end of code. Make sure to return handler(req, res) at the end of the function as given in code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raghav Patel