skip to Main Content

I’m working on a Next.js API route to handle user registration. The code is supposed to check if a username is already taken and return an appropriate response. However, I’m encountering an issue with the Response.json method.

import dbConnect from "@/lib/dbconnect";
import UserModel from "@/model/User";
import bcrypt from "bcryptjs";
import { sendVerificationEmail } from "@/helpers/sendVerificationEmail";

export async function POST(request: Request){
    await dbConnect();

    try {
        const { username, email, password } = await request.json();

        const existingUserVerifiedByUsername = await UserModel.findOne({
            username,
            isVerfied: true
        });

        if(existingUserVerifiedByUsername){
            return Response.json({
                success: false,
                message: "Username is already taken"
            }, { status: 400 });
        }

    } catch (error) {
        console.error('Error registering user', error);
        return Response.json({
            success: false,
            message: "Error registering user"
        }, { status: 500 });
    }
}

I understand that Response.json might be incorrect and tried using new Response(…), but I’m still not sure if this is the right approach.

The code should return a 400 response if the username is taken and a 500 response if there’s an error during registration.

2

Answers


  1. There is a typo isVerfied (should be isVerified I assume, or was this intentional?)

    Also try NextResponse.

    Note, you are not handling the case where if(existingUserVerifiedByUsername){} condition does not match. Make sure you always send back a response.

    Login or Signup to reply.
  2. All paths should return a response, in your case there’s no response if userName is not taken, this should do the work:

    
    export async function POST(request: Request){
        await dbConnect();
    
        try {
            ...
    
            if(existingUserVerifiedByUsername){
                return Response.json({
                    success: false,
                    message: "Username is already taken"
                }, { status: 400 });
            }
            // No user verified by username exists
            // Proceed to create user with mongoose
            const user = await User.create({...});
            return Response.json({
                success: true;
                message: "User created successfully"
            }, {status: 201})
    
        } catch (error) {
            console.error('Error registering user', error);
            return Response.json({
                success: false,
                message: "Error registering user"
            }, { status: 500 });
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search