Next.js Discord

Discord Forum

⨯ Error: API route returned a Response object in the Node.js runtime, this is not supported. Please

Unanswered
Kromfohrländer posted this in #help-forum
Open in Discord
KromfohrländerOP
I am not able to solve this error, My request is not returning the response
here is the code:
import { hash } from "bcrypt";
import { NextResponse } from "next/server";
import * as z from "zod";

import prismadb from "@/lib/prismadb";

// Define a schema for input validation
const userSchema = z.object({
  username: z.string().min(1, "Username is required").max(100),
  email: z.string().min(1, "Email is required").email("Invalid email"),
  password: z
    .string()
    .min(1, "Password is required")
    .min(8, "Password must have than 8 characters"),
});

export default async function POST(req: Request) {
  try {
    const body = await req.json();
    const { email, username, password } = userSchema.parse(body);

    // check if email already exists
    const existingUserByEmail = await prismadb.user.findUnique({
      where: { email },
    });

    if (existingUserByEmail) {
      return NextResponse.json(
        {
          user: null,
          message: "Email with this email already exists",
        },
        { status: 409 }
      );
    }

    // check if username already exists
    const existingUserByUsername = await prismadb.user.findUnique({
      where: { username },
    });

    if (existingUserByUsername) {
      return NextResponse.json(
        {
          user: null,
          message: "User with this username already exists",
        },
        { status: 409 }
      );
    }

    const hashedPassword = await hash(password, 10);
    const newUser = await prismadb.user.create({
      data: {
        username,
        email,
        password: hashedPassword,
      },
    });

    const { password: newUserPassword, ...rest } = newUser;

    return NextResponse.json(
      {
        user: rest,
        message: "User created successfully",
      },
      { status: 201 }
    );
  } catch (error) {
    console.log("[SIGNUP_POST]", error);
    return new NextResponse("Internal error", { status: 500 });
  }
}

Someone, please help!

4 Replies

Im not 100% sure but you seem to be confusing Api routes and Route handlers. You are using a route handler inside pages directory
Thats not how you handle api routes in pages and thats definitely not how you send response in api routes.
Follow this page for more info