Exporting a named export for every HTTP method is the way to go with NextJs

I'm currently working on a project to create an Airbnb clone using NextJs. The tutorial I'm following is using an experimental version, while I've opted for the latest version of NextJs. One aspect that's been causing confusion for me is understanding how routing works in NextJs, especially when it comes to API calls. Despite my efforts to research and make changes to the routing path, I continue to encounter errors.

Everything functions as expected during the registration process. However, upon attempting to log in, I encountered the following error:

Error Detected default export in 'E:\Program\airbnb\app\api\auth[...nextauth]\route.ts'. Export a named export for each HTTP method instead.

This is the routing path I have set up:

https://i.stack.imgur.com/9zJ1z.png

located inside my app/api/auth/[...nextauth]/route.js

export const authOptions: AuthOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID as string,
            clientSecret: process.env.GITHUB_SECRET as string
        }),
        GoogleProvider({
            clientId: process.env.GOOGLE_ClIENT_ID as string,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string
        }),
        CredentialsProvider({
            name: 'credentials',
            credentials: {
                email: {label: 'email', type: 'text'},
                password: {label: 'password', type: 'password'},
            },
            async authorize(credentials){
                // Authorize logic here
            }
        })
    ],
    pages: {
        signIn: '/',
    },
    debug: process.env.NODE_ENV === 'development',
    session: {
        strategy: 'jwt'
    },
    secret: process.env.NEXTAUTH_SECRET
}

export default NextAuth

register/route.js

export async function POST(request: Request) {
  // POST request logic here
}

Here is the code snippet from my LoginModal.ts file:

const onSubmit: SubmitHandler<FieldValues> = (data) => {
    setIsLoading(true)
   
    signIn('credentials',{
      ...data,
      redirect: false,
    })
    .then((callback) => {
      setIsLoading(false)

      if(callback?.ok){
        toast.success('Logged In')
        router.refresh()
        loginModal.onClose()
      }

      if(callback?.error){
        toast.error(callback.error)
      }

    })
  }

Answer №1

To utilize Route Handlers in NextJS 13, a handler is required. In the file api/auth/[...nextauth], simply switch export default NextAuth to:

const handler = NextAuth(authOptions)
export { handler as GET, handler as POST}

This demonstrates how exports are used in route handlers with next-auth. For further information, refer to their documentation here.

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

What is the best way to enhance an error object in Express with additional information beyond just a simple message?

I need to enhance the error handling process in my express application by passing two pieces of information to the error handler, which will then send both pieces of information in a JSON format to the client. Currently, I am only able to include an error ...

Using Mongoose to Perform Lookup with an Array as a Foreign Key

In my database, I have a collection called questions which contains fields like _id, name, and more. Additionally, there is another collection named tests with fields such as _id, name, and an array of questions. My goal is to retrieve all the questions a ...

Having difficulty transferring data from a JSON file on a different domain to a variable using Ajax

As a beginner in Ajax, I am currently exploring the use of Ajax Cross domain functionality to fetch data. The Ajax function is triggered from test.php, which then calls stats.php to request the desired data. The content of Stats.php: <?php $data = ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

Encountered an issue while building Next.js in a Docker container, although it runs smoothly when

I am facing an issue with building my nextjs app in docker, although it runs without any errors locally. I have added output: 'standalone' to my nextjs config and the project is using yarn. The Dockerfile I am using is identical to the one found ...

Is there a way to prevent the DOM from loading images until Angular has successfully injected the correct variables?

Having some trouble with this block of code I have: <div class="image" ng-repeat="image in images"> <img src="{{image.url}}"></img> </div> It seems that the image sources are being set correctly, but I keep getting an error wh ...

IconButton function in ReactJS malfunctioning specifically in Firefox browser

There seems to be an issue with the click function of IconButton from Material UI not working in any version of FireFox. Below is the code snippet in question: <div className='floating-button visible-xs'> <IconButton touch={true} tool ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Is utilizing React's useEffect hook along with creating your own asynchronous function to fetch data the best approach

After attempting to craft a function for retrieving data from the server, I successfully made it work. However, I am uncertain if this is the correct approach. I utilized a function component to fetch data, incorporating useState, useEffect, and Async/Awa ...

To show the image along with the .titleclass, .subtitleclass, and .description when clicking on it, what steps do I

<?php while($galleryrec = mysqli_fetch_array($getresultgallery)){ ?> <div class="col-lg-2 col-md-2 mb-4 mb-lg-0" id="imageidback"> <img data-id ="<?php echo $galleryrec['publishid& ...

While attempting an AJAX request with jQuery, I encountered the following error message: "Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN"

I encountered an issue that says: ` throw err; // Rethrow non-MySQL errors ^ Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN ` while attempting a jQuery AJAX get request, and I'm unsure of the cause. My backend is built using node.js a ...

Deactivate a function when the dropdown input is selected

I'm currently using a function to attach scroll events to a slider element for navigating through slides. However, I want to temporarily disable this function in specific situations - such as when a dropdown is in focus - to allow smooth scrolling thr ...

What makes the creation of Javascript objects so flexible and dynamic?

Recently, I've been exploring the concept of creating new objects in JavaScript. It's interesting to note that in JS, every object creation is dynamic. This allows you to create an object and then add properties later on. Even fields created in t ...

Guidelines for populating data with an array

I have the following array: const dataArr = [[15, 14, 5], [16, 10, 2], [17, 6, 13], [18, 4, 8], [19, 7, 4]]; Now, I am populating another array using the above data as shown below: for (let i=0; i<dataArr.length; i++){ newData.push(dataArr[i]); ...

An improved method for fetching data from the server at regular intervals of x minutes

Is setInterval the best way to periodically check for updates in a database and update the UI accordingly, or are there better approaches that I should consider? I've read conflicting opinions on using setInterval for this purpose, with some sources ...

Having trouble aligning image and expanding video to fit the screen in a NextJS application

I need help with: centering the image above the waitlist sign up scaling the background video in a relative way to fill the screen regardless of browser size This is the relevant part of index.js: import Head from 'next/head' import Image from ...

What is the reason this straightforward regex functions perfectly in all cases, except for when applied to the html5

This particular HTML input turns red to signify that the pattern has not matched when the value in the input field is "1". var newInput = document.createElement ('input'); newInput.pattern = '^\d+\.?\d*$'; document.getEl ...