Skip to content

Commit

Permalink
improve error handling in user registration process
Browse files Browse the repository at this point in the history
  • Loading branch information
pvk05 committed Feb 1, 2025
1 parent a08ea2c commit d8d7d76
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 16 deletions.
4 changes: 3 additions & 1 deletion app/(pages)/auth/register/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,13 @@ async function createUser(firstName, lastName, email, debug) {
email: normalizedEmail,
}),
});

const responseBody = await response.json();

if (debug) console.log("createUser response:", response);

if (!response.ok) {
return { ok: false, error: response.error };
return { ok: false, error: responseBody.error };
}

const data = await response.json();
Expand Down
52 changes: 37 additions & 15 deletions app/api/v2/users/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,24 @@ import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/utils/authOptions";


const errors = {
missingFields: NextResponse.json(
{ error: "Missing required fields" }
, { status: 400 }
),
userExists: NextResponse.json(
{ error: "User already exists" },
{ status: 400 }
),
userCreateError: NextResponse.json(
{ error: "Could not create user" },
{ status: 400 }
),
emailError: NextResponse.json(
{ error: "Could not send verification email" },
{ status: 400 }
),
};


const NEXTAUTH_URL = process.env.NEXTAUTH_URL || "";
Expand Down Expand Up @@ -63,26 +81,30 @@ async function createUser(email, firstName, lastName) {

async function registerUser(email, firstName, lastName) {
if (!email || !firstName || !lastName) {
return NextResponse.json(
{ error: "Missing required fields" },
{ status: 400 }
);
return errors.missingFields;
}

const userRes = await createUser(email, firstName, lastName)
if (!userRes)
return NextResponse.json({ ok: false, error: "Could not create user" }, {status: 400});
const user = await prisma.user.findUnique({
where: {
email: email,
},
});
if (user) {
return errors.userExists;
};

const {newUser, activateToken} = userRes
const userRes = await createUser(email, firstName, lastName);
if (!userRes)
return errors.userCreateError;

const res = await sendVerificationEmail(newUser, activateToken)
if (res.success) {
return NextResponse.json({ok: true}, {status: 200})
}
const { newUser, activateToken } = userRes;

return NextResponse.json({ ok: false, error: "Could not send verification email" }, {status: 400});


const res = await sendVerificationEmail(newUser, activateToken);
if (res.success) {
return NextResponse.json({ ok: true }, { status: 200 });
}

return errors.emailError;
}

export async function POST(req) {
Expand Down

0 comments on commit d8d7d76

Please sign in to comment.