What are the steps to integrate a database into my Next.js application?

While I was experimenting with integrating postgresql into a nextjs project, I encountered an error 405 when trying to create an account.

Below is the error message in the browser console:

page.tsx:14 
        
        POST http://localhost:3000/api/auth/signup net::ERR_ABORTED 405 (Method Not Allowed)
handleSubmit @ page.tsx:14
callCallback @ react-dom.development.js:19462
invokeGuardedCallbackImpl @ react-dom.development.js:19511
...

And here is what appeared in my vscode terminal:

` ⨯ Detected default export in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method instead.⨯ No HTTP methods exported in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method.
This is a snippet of my API code used to POST data  

 import prisma from "@/lib/prisma";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    try {
      const { id, name, email, password } = req.body;

      // Check if the user already exists
      const existingUser = await prisma.user.findUnique({
        where: { email },
      });

      if (existingUser) {
        return res.status(400).json({ error: 'User already exists' });
      }

      // Create a new user using Prisma
      const newUser = await prisma.user.create({
        data: {
          id,
          name,
          email,
          password,
        },
      });

      return res.status(201).json(newUser);
    } catch (error) {
      console.error(error);
      return res.status(500).json({ error: 'Server error' });
    }
  } else {
    return res.status(405).json({ error: 'Method not allowed' });
  }
}

This section pertains to the frontend implementation:

"use client";

import React, { useState } from "react";

export default function SignUp() {
  const [id, setId] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();

    const user = await fetch("/api/auth/signup", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id, name, email, password }),
    });
  };

  return (
    <form onSubmit={handleSubmit} method="POST">
      <input
        type="text"
        placeholder="username"
        value={id}
        onChange={(e) => setId(e.target.value)}
      />

      <input
        type="text"
        placeholder="name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />

      <input
        type="text"
        placeholder="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />

      <input
        type="password"
        placeholder="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />

      <button type="submit">Sign Up</button>
    </form>
  );
}

I sought assistance from chatgpt regarding this issue as I am relatively new to web development frameworks and struggle with algorithmic thinking.

Answer №1

It appears that there is a confusion between the app and pages routers in Next.js 13. To utilize client/server components, the app router should be used.

The handler in your src\app\api\auth\signup\route.ts file is designed for the pages router, which is not compatible with the app router, resulting in the following error:

` ⨯ Detected default export in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method instead.⨯ No HTTP methods exported in 'C:\Users\USER\Desktop\myWorks\webdevproj\loginsys\src\app\api\auth\signup\route.ts'. Export a named export for each HTTP method.

To resolve this issue, you must adapt this handler to be compatible with the app router, such as:

export async function POST(request: Request) {
    try {
        const { id, name, email, password } = req.body;

        // Check if the user already exists (you may need to customize this logic)
        const existingUser = await prisma.user.findUnique({
            where: { email },
        });

        if (existingUser) {
            return res.status(400).json({ error: 'User already exists' });
        }

        // Create a new user using Prisma
        const newUser = await prisma.user.create({
            data: {
                id,
                name,
                email,
                password, // Note: You should hash the password before saving it to the database
           },
        });

        return res.status(201).json(newUser);
    } catch (error) {
        console.error(error);
        return res.status(500).json({ error: 'Server error' });
    }
}

For more information, refer to https://nextjs.org/docs/app/building-your-application/routing/route-handlers.

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 correct method for aligning to the right or left within the material-ui appbar using material-ui-next version?

Having trouble getting the login/logout buttons to float right using material-ui-next ("material-ui": "^1.0.0-beta.22"). It looks like they removed iconElementRight= from the api. Is the new solution to use <Grid> in the appbar? Seems a bit clunky. W ...

How can I furnish TSC with TypeScript definitions for URI imports in a comprehensive manner?

import Vue from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b3b0a085f7ebf0ebf7f4">[email protected]</a>/dist/vue.esm.js' If I submit the above code to TSC for compilat ...

Utilizing ternary operators in Angular 6 tables

I need to dynamically display certain amounts based on the comparison of two interest values. Here is the logic: <td *ngIf="subTable.flexitaxMaxPaymentDate"> subTable.flexitaxMaxInterest > subTable.IRDInterest ? {{subTable.maxAmou ...

Why does React redirect me to the main page after refreshing the page, even though the user is authenticated in a private route?

In the process of developing a private route component that restricts unauthenticated users and redirects them to the homepage, we encountered an issue upon page refresh. The problem arises when the current user variable momentarily becomes null after a ...

Struggling to upload image to Canvas with React and Next.js

I have been attempting to display an image in my canvas element within a react component. I've tried loading it from various sources - URLs, local repositories, using different syntax forms, but all my efforts have been unsuccessful. The only "progre ...

Automate the compilation of Typescript project references by creating a solution that allows for passing unique options to each

When compiling or building a project with references programmatically, I make use of the ts.createSolutionBuilder API. The challenge I face is that in my specific scenario, I do not have individual tsconfig.json files stored on the filesystem for each pac ...

Enhancing the efficiency of Angular applications

My angular application is currently coded in a single app.module.ts file, containing all the components. However, I am facing issues with slow loading times. Is there a way to improve the load time of the application while keeping all the components within ...

Currently in the process of modernizing an outdated method to a more up-to-date version in Jasmine, encountering issues related to

Currently working to update the method throwOnExpectationFailure to the newer one oneFailurePerSpec. According to the Jasmine documentation, this can be achieved by: Use the `oneFailurePerSpec` option with Env#configure After conducting research, I came ...

The layout in Next.js production builds appears to be distinct from the layout in the

Currently, I am working on a website where I have implemented a dark theme by adding a class to the body element. Everything is functioning perfectly in the development environment, but I am encountering issues in the production build. Here is the root l ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

Strategies for resolving the "Objects are invalid React children" issue in Next.js 13 and Next Auth

I am currently developing an application using Next JS 13 with Firebase and Next Auth. After integrating Firebase with Next Auth and utilizing the session, I encountered an error. Error: Objects are not valid as a React child (found: [object Promise]). If ...

Using Next.js to Retrieve JSON Data and Render it in Components

I want to refactor the MainMenu function and getStaticProps from index.js into separate components. Here is my current index.js page that is functioning correctly. #index.js import Link from 'next/link'; function MainMenu({ menuLists }) { re ...

The Prisma schema and the database schema do not align

I have a Person table structured like this in the schema: model Person { id String @id @default(uuid()) firstName String? lastName String? roles Role[] middleNames String? gender String? dob ...

Issue encountered at 'site construction' phase: failure in build script with exit code 2

I am a novice and struggling to solve this error. I have attempted to fix it by adjusting the deploy settings, but I can't seem to resolve this compilation error. The syntax errors are overwhelming, and I'm not sure if there is something crucial ...

the value of properrty becomes undefined upon loading

In my code, there exists an abstract class named DynamicGridClass, containing an optional property called showGlobalActions?: boolean?. This class serves as the blueprint for another component called MatDynamicGridComponent, which is a child component. Ins ...

The process of exporting a singleton instance

I have created a new class called AppViewModel with a setting property set to 1: class AppViewModel { setting: number = 1; } export = AppViewModel; Afterward, I imported the class and instantiated it within another class named OrderEntry: import AppV ...

Unable to retrieve a property from a variable with various data types

In my implementation, I have created a versatile type that can be either of another type or an interface, allowing me to utilize it in functions. type Value = string | number interface IUser { name: string, id: string } export type IGlobalUser = Value | IU ...

End the pipeline execution in a chain of RxJS observables

Here is a scenario where a series of Observables are chained together. Is it possible to prevent the subsequent chain from executing if an error is thrown by 'parentObs1'? import { throwError } from "rxjs"; import { mergeMap, catchError ...

Experiencing difficulties with the mat-card component in my Angular project

My goal is to implement a login page within my Angular application. Here's the code I've written: <mat-card class="login"> <mat-card-content> <div class="example-small-box mat-elevation-z4"> ...

What are the top methods for managing states within ReactJs components?

When dealing with multiple states in a component that all impact the rendered JSX, it's important to consider best practices for managing these states and minimizing the use of if-else conditions. class AddressBody extends Component { render() { ...