close
close

next.js – How should I properly use the Response object to return JSON responses in this case? Is there anything else in the code that could cause problems?

next.js – How should I properly use the Response object to return JSON responses in this case? Is there anything else in the code that could cause problems?

I’m working on a Next.js API route to handle user registration. The code is supposed to check if a username is already in use and return an appropriate response. However, I’m having 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 may be incorrect and I tried using a 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 is an error during registration.