No default export function available on this page

Recently delving into Nextjs, I'm currently in the process of setting up a MongoDB connection using middleware configuration.

Let me showcase my code:

import type { NextApiRequest, NextApiResponse } from 'next'
import { connectMongoDB } from '../../middlewares/connect-db'

const handler = (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method === 'POST') {
    const { login, pwd } = req.body
    if (login === '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a4b4e4743446a4b4e47434404494547">[email protected]</a>' && pwd === 'Admin@123') {
      res.status(200).json({ message: 'Successfully logged in!' })
    }
    return res.status(400).json({ error: 'Failed to log in.' })
  }
  return res.status(405).json({ error: 'Unsupported Method' })
}
export default connectMongoDB(handler)

Let's take a look at the middleware/connect-db code:

import type { NextApiRequest, NextApiHandler, NextApiResponse } from 'next'
import mongoose from 'mongoose'

export const connectMongoDB = (handler: NextApiHandler) => {
  ;async (req: NextApiRequest, res: NextApiResponse) => {
    //check connection
    if (mongoose.connections[0].readyState) {
      return handler(req, res)
    }

    const { DB_CONNECTION_STRING } = process.env
    if (!DB_CONNECTION_STRING) {
      return res.status(500).json({ error: 'DB Connection Error' })
    }

    mongoose.connection.on('connected', () =>
      console.log('DB Connection established')
    )
    mongoose.connection.on('error', () => console.log('DB Connection Error'))
    await mongoose.connect(DB_CONNECTION_STRING)

    return handler(req, res)
  }
}

This is how my project structure looks like:

The function export was working fine before. Not sure why it's throwing errors now.

Thanks for any help in advance.

Even after renaming functions and verifying the DB_CONNECTION_STRING, the issue persists even after app restarts.

Answer №1

The issue arises from the way you defined connectMongoDB(). By creating an arrow function within connectMongoDB() without actually outputting it, the result will be void, which may not be expected by the subroutine using the export. [1]

To address this problem, one approach is to store the arrow function in a variable and then return it:

export const connectMongoDB = (handler: NextApiHandler) => {
  <b>let connect =</b> async (req: NextApiRequest, res: NextApiResponse) => {
    •••Rest of code•••
  }
  <b>return connect</b>
}

[1] One small note: there seems to be an unexpected token ;.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

Issues with Dependency Injection in Angular.js

I've been working on Dependency Injection and trying to make my code more modular in Angular.js. After researching some tutorials, I decided to try and rewrite it. Here's what I initially planned (although I may have misunderstood some concepts, ...

What could be causing the 404 error message in Backend deployment on Vercel?

Hello everyone, I'm currently in the process of deploying the backend for my MERN application on Vercel. Prior to this attempt, I successfully deployed a small todo project using MERN on Vercel. Everything worked fine then, and I followed the same st ...

Discover the flawless way to transmit client geolocation to a server. Encounter an intriguing hurdle: Unable to access undefined properties (specifically 'loc') while reading

I encountered an error that says "TypeError: Cannot read properties of undefined (reading 'loc')". This error was triggered when I attempted to pass the user's location to a server through a POST request. In my HTML file, I have included th ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Is the AngularJS Date property model sending an incorrect value to the server?

There are some puzzling things I am trying to figure out. When using datetimepicker, the Date and time selected appear correctly on the screenshot. The value in the textbox is accurate The model's value in console is correct (but hold on a second... ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

Can a json file be generated and saved using PhoneGap's file system and JavaScript?

Is it feasible to gather user data and save it as a JSON file for JavaScript to retrieve each time the user interacts with the application? ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

Node.js tutorial: Establishing a connection to MongoDB and sharing it through an include file

Initiating My First Node.js API This is my initial attempt at creating a node.js API/application for learning purposes. I am starting by creating test cases to delete all records in a table, insert three specific records, and then query for those same rec ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

Tips on utilizing recursive Promises within a loop while transferring arguments to another function

Despite searching other threads on SO, I couldn't find a satisfactory answer to my problem. Every solution seems to be missing something essential for my case, especially since none of them address Apple Music specifically. The Apple API relies heavil ...

Delete the click event listener that was previously assigned by a different script

After extensive investigation using the Chrome developer tools, I have identified a click event listener that needs to be removed: https://i.sstatic.net/dnB3Q.png I successfully removed the listener using the developer tools. Further analysis revealed th ...

Our website features a dynamic functionality where users can select from two dropdown lists with identical values. Upon selecting multiple values from the first dropdown, the corresponding values in

When selecting multiple values from the first dropdown list, the second dropdown list will automatically have the same value selected as the first dropdown. ...

Is there a way to extract osclass theme HTML from a plugin using JavaScript?

I've created a variable named btn which I'm assigning to a document.querySelector() function. The query selection seems correct as it successfully grabs the desired element when tested in the browser console. However, the assignment returns null. ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

Tips for organizing the output of a MongoDB lookup query

I am looking to merge two collections, sort the date field in the foreign table, and then group the fields to only retrieve one record from the most recent date for each device as outlined below $collection = $this->db->dv_device; $result_ ...