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

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe. Here is an example of how one of these objects is structured: ...

Error in Node.js: [Error: Query parameter should not be empty]

I've been recently focusing on a project that involves sending the required name to my profile.js file using a POST request. However, whenever I try to access console.log(req.body.bookName) (as the data being sent is named bookName), it shows an error ...

Shifting attention from the main point to the surrounding details (including siblings)

In my search bar layout, the main parent component consists of three child components - location dropdown, date picker (calendar), and duration dropdown. By default, the user's location is pre-selected in the location dropdown. I want the focus to shi ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Understanding Json data using Jquery

I am currently learning about Jquery, Ajax, and JSON but I am having difficulty with parsing Json data. Despite researching extensively on stackoverflow Parsing JSON objects for HTML table Access / process (nested) objects, arrays or JSON Parse JSON in ...

Revolutionize Your App with React Native's Interactive Bottom Sheet Option

Hello there! I am trying to create a FlatList with multiple items, each of which should trigger a bottom-sheet when clicked. I want to make this dynamic but I'm encountering an error. TypeError: undefined is not an object (evaluating `_this[_reactNat ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

What is the best practice for accessing specific components of JSON values that are delimited by colons?

When working with an API that returns a JSON containing strings separated by colons, such as: { "id": "test:something:69874354", "whatever": "maybe" } It may be necessary to extract specific values from these strings. For example, in the given JSON s ...

What distinguishes res.send from app.post?

I'm just starting to learn about express and HTTP. I've heard that the express library has app.get, app.post, and res.send methods. From what I gather, app.get is used for GET requests and app.post is used for POST requests. How does res.send fit ...

Executing the callback function passed as a prop

I'm a bit confused about how to call a callback function in an element's prop. Let's say I have a button here: <Button onPress={() => { loadMore()}} title="Load More" backgroundColor='#0A55C4' /> I am wondering wh ...

Searching with Sequelize for an indirect relationship: How can it be done?

Within my database, there exists a relationship between Users and Roles. A User can have multiple Roles assigned to them. These Roles are connected to Activities in such a way that they can be associated with many different activities. This association all ...

Retrieving HTML Content with Ajax

Currently using this script for an assignment in my class. Still learning! The script checks whether a site is down or not. I want to expand this script to display statuses for each website in the table without duplicating the script. Any suggestions on ...

"Enhance Your Website with Stylish Bootstrap Pop

Hello, I am trying to display a "Loading..." text or spinner image while waiting for the dynamic ajax content to load. Due to the large amount of data that needs to be fetched, it takes approximately 2-3 seconds for the content to fully load. Below is my ...

React Login Redirect

I am struggling to implement a redirect in my React project login. Despite researching online and finding solutions using routers, I have been unsuccessful in adding it to my code correctly. Here is my code - how can I effectively implement the router? Ap ...

Adding a div with a canvas element is malfunctioning

I've been experimenting with using canvg to convert an SVG within a div into a canvas. So far, the conversion is working fine but when I try to copy the innerHTML of the div to another div, it's not functioning properly. The canvas is being gener ...

Is there a way to display a toast notification when redirecting because of an expired session with Next-Auth in a Next.js application?

Let's say I have a page named internal.tsx with the following code: export const getServerSideProps: GetServerSideProps = async (ctx) => { const session = await getSession(ctx); if (!session) { // TODO: Add a toast notification explaining t ...

Click the edit button to access the options in the material table

https://i.stack.imgur.com/Inyow.png Currently, I am utilizing Material Table within Reactjs to display the table Data. However, I have encountered a hurdle where I need to alter state upon clicking on the edit option/icon. My objective is not to modify th ...

What is causing the ERR_HTTP_HEADERS_SENT('set') error when running on Windows Server, but not on my development machine?

Currently, I am in the process of developing a Node/Express application that will integrate with ActiveDirectory. The login form is designed to post the username and password to a specific /auth route, where the AD authentication takes place, along with se ...