How to handle properly error which is thrown in api route Next JS 14?

I want to display nice UI message when some user try to register with already registered email.
This is my route.tsx (/api/auth/register/route.tsx)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { NextResponse } from "next/server";
import prisma from "@/app/libs/prismadb";
import { hash } from "bcrypt";
export async function POST(request: Request){
try {
const {firstName, lastName, email, password} = await request.json();
console.log({firstName, lastName, email, password});
const userExist = await prisma.user.findFirst({
where: {
email: email
}
})
if(userExist){
//throw new Error("User with this email already exist");
return NextResponse.json({ message: "User with this email already exist" }, { status: 400 })
}
const hasPass = await hash(password, 12);
const user = await prisma.user.create({
data: {
firstName: firstName,
lastName: lastName,
email: email,
username: email,
hashedPassword: hasPass
}
})
return NextResponse.json({message: "success"});
} catch (error) {
console.log({error});
}
}
</code>
<code>import { NextResponse } from "next/server"; import prisma from "@/app/libs/prismadb"; import { hash } from "bcrypt"; export async function POST(request: Request){ try { const {firstName, lastName, email, password} = await request.json(); console.log({firstName, lastName, email, password}); const userExist = await prisma.user.findFirst({ where: { email: email } }) if(userExist){ //throw new Error("User with this email already exist"); return NextResponse.json({ message: "User with this email already exist" }, { status: 400 }) } const hasPass = await hash(password, 12); const user = await prisma.user.create({ data: { firstName: firstName, lastName: lastName, email: email, username: email, hashedPassword: hasPass } }) return NextResponse.json({message: "success"}); } catch (error) { console.log({error}); } } </code>
import { NextResponse } from "next/server";

import prisma from "@/app/libs/prismadb";
import { hash } from "bcrypt";

export async function POST(request: Request){

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

        console.log({firstName, lastName, email, password});

        const userExist = await prisma.user.findFirst({
            where: {
                email: email
            }
        })

        if(userExist){
            //throw new Error("User with this email already exist");
            return NextResponse.json({ message: "User with this email already exist" }, { status: 400 })
        }

        const hasPass = await hash(password, 12);

        const user = await prisma.user.create({
            data: {
                firstName: firstName,
                lastName: lastName,
                email: email,
                username: email,
                hashedPassword: hasPass
            }
        })

        return NextResponse.json({message: "success"});
        
        
    } catch (error) {

        console.log({error});

        
        
    }

    
}

This is my Form component form.tsx (app/register/form.tsx)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"use client"
import React, { FormEvent } from 'react'
const Form = () => {
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
try {
const response = await fetch("api/auth/register", {
method: "POST",
body: JSON.stringify({
firstName: formData.get('firstName'),
lastName: formData.get('lastName'),
email: formData.get('email'),
password: formData.get('password'),
})
})
if (!response.ok) {
throw new Error("OOOOOOOPSS");
}
} catch (error) {
console.log(error);
}
}
return (
<form onSubmit={handleSubmit} className='w-full flex flex-col gap-5'>
<input className=' border-black bg-slate-300' type="text" name="firstName" id="firstName" placeholder='John' />
<input className=' border-black bg-slate-300' type="text" name="lastName" id="lastName" placeholder='Wick' />
<input className=' border-black bg-slate-300' type="email" name="email" id="email" placeholder='Email' />
<input className='border-black bg-slate-300' type="password" name="password" id="password" placeholder='Password' />
<button className=' bg-red-300' type="submit">Register</button>
</form>
)
}
export default Form
</code>
<code>"use client" import React, { FormEvent } from 'react' const Form = () => { async function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const formData = new FormData(e.currentTarget); try { const response = await fetch("api/auth/register", { method: "POST", body: JSON.stringify({ firstName: formData.get('firstName'), lastName: formData.get('lastName'), email: formData.get('email'), password: formData.get('password'), }) }) if (!response.ok) { throw new Error("OOOOOOOPSS"); } } catch (error) { console.log(error); } } return ( <form onSubmit={handleSubmit} className='w-full flex flex-col gap-5'> <input className=' border-black bg-slate-300' type="text" name="firstName" id="firstName" placeholder='John' /> <input className=' border-black bg-slate-300' type="text" name="lastName" id="lastName" placeholder='Wick' /> <input className=' border-black bg-slate-300' type="email" name="email" id="email" placeholder='Email' /> <input className='border-black bg-slate-300' type="password" name="password" id="password" placeholder='Password' /> <button className=' bg-red-300' type="submit">Register</button> </form> ) } export default Form </code>
"use client"
import React, { FormEvent } from 'react'

const Form = () => {

    async function handleSubmit(e: FormEvent<HTMLFormElement>) {

        e.preventDefault();

        const formData = new FormData(e.currentTarget);


        try {
            const response = await fetch("api/auth/register", {
                method: "POST",
                body: JSON.stringify({
                    firstName: formData.get('firstName'),
                    lastName: formData.get('lastName'),
                    email: formData.get('email'),
                    password: formData.get('password'),
                })
            })

            if (!response.ok) {
                throw new Error("OOOOOOOPSS");
                
            }
        } catch (error) {
            console.log(error);
        }
    }

    return (
        <form onSubmit={handleSubmit} className='w-full flex flex-col gap-5'>
            <input className=' border-black bg-slate-300' type="text" name="firstName" id="firstName" placeholder='John' />
            <input className=' border-black bg-slate-300' type="text" name="lastName" id="lastName" placeholder='Wick' />
            <input className=' border-black bg-slate-300' type="email" name="email" id="email" placeholder='Email' />
            <input className='border-black bg-slate-300' type="password" name="password" id="password" placeholder='Password' />
            <button className=' bg-red-300' type="submit">Register</button>
        </form>
    )
}

export default Form

And this is my page.tsx (app/register/page.tsx)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import Form from './form'
const page = () => {
return (
<div className='w-[300px] min-h-[400px] mx-auto mt-10'>
<Form />
</div>
)
}
export default page
</code>
<code>import Form from './form' const page = () => { return ( <div className='w-[300px] min-h-[400px] mx-auto mt-10'> <Form /> </div> ) } export default page </code>
import Form from './form'

const page = () => {

    

    return (
        <div className='w-[300px] min-h-[400px] mx-auto mt-10'>
            <Form />
        </div>
    )
}

export default page

Initially I was throwing an error in api route file. After that I decided just to return response with message but i could’t get the message from the response in my component form file. I just want to know what is the proper way to show for example a simple alert message to the user with a message that this email is already registered

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật