"use server";
import { customFetch } from "./customFetch";
import { revalidatePath } from "next/cache";
import { BadRequestError } from "./ErrorHandler";
import uploadFileToS3 from "./uploadFileToS3";
import { redirect } from "next/navigation";
export const registerNewUser = async (prevState: any, formData: FormData) => {
const image = formData.get("image") as File;
if (!image) return;
if (!["image/jpeg", "image/png"].includes(image.type.toLowerCase())) {
throw new BadRequestError("Image type should be JPEG or PNG Only.");
}
if (image.size > 1024 * 1024 * 5) {
throw new BadRequestError("Image size should not exceed 5MB.");
}
const buffer = Buffer.from(await image.arrayBuffer());
const uploadedImage = await uploadFileToS3(buffer, image.name, image.type);
const user = {
firstName: formData.get("firstName") as string,
lastName: formData.get("lastName") as string,
password: formData.get("password") as string,
confirmPassword: formData.get("confirmPassword") as string,
email: formData.get("email") as string,
image: uploadedImage,
};
try {
const { data } = await customFetch.post("/api/auth/sign-up", user);
revalidatePath("/");
// redirect("/");
return data;
} catch (error: any) {
console.log(error.response.data.error);
return { message: error.response.data.error };
}
};
import { connectDB } from "../../../../lib/mongoose";
import { User, userValidation, loginValidation } from "../../../../models/User";
import { BadRequestError } from "../../../../lib/ErrorHandler";
import asyncHandler from "../../../../lib/asyncHandler";
import { NextRequest, NextResponse } from "next/server";
import { S3 } from "@aws-sdk/client-s3";
import { redirect } from "next/navigation";
const s3 = new S3({
region: process.env.AWS_REGION,
});
export const POST = asyncHandler(async (req: NextRequest) => {
await connectDB(process.env.MONGODB_URI);
const data = await req.json();
const { error, value } = userValidation.validate(data);
if (error) throw new BadRequestError(error.details[0].message);
const isEmailExist = await User.findOne({ email: value.email });
if (isEmailExist) {
throw new BadRequestError("email is already exist");
}
const user = new User(value);
await user.save();
return NextResponse.json(
{
message: `Success Signing Up!`,
success: true,
user,
},
{ status: 201 }
);
});
I think this is one of the most easy solutions out there, but yet im stuck on it for a long time hehe.
I want to be able to redirect to the home page after signin up, I cant figure out how can i redirect to the home page and return data or nextreponse, cause when i redirect, the return statement is not accessible.
I shared 2 files cause im not sure even where to write the redirect logic.
thanks in advance.