When registering a user using email, password and username and storing in mongodb, I am looking to incorporate Next Auth to store sessions at the time of registration. My goal is to redirect the user in the same way during registration as they would experience if logged in, with the session being stored. However, I am struggling to find a solution for this during the registration process. Do I need to make the user login again after registering in order to manage all authentication-related tasks using Next Auth?
Below is my registration API code:
import type { NextApiRequest, NextApiResponse } from "next";
import connectMongo from "@/lib/mongodb";
import User from "@/models/usersSchema";
import { z } from "zod";
import { hash } from "bcryptjs";
import jwt from "jsonwebtoken";
import { UserSignUpSchema } from "@/lib/UserSchema";
let secret: string = "";
if (process.env.JWT_SecR3T) {
secret = process.env.JWT_SecR3T;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "POST") {
return res.status(405).end();
}
try {
const data = req.body;
const parsedData = await UserSignUpSchema.safeParse(data);
if (parsedData.success === false) {
return res
.status(400)
.json({ error: parsedData.error.issues[0].message });
} else {
await connectMongo();
const { username, password, email } = parsedData.data;
//@ts-ignore
let existingUser = await User.findOne({ email: email });
if (existingUser) {
return res.status(409).json({ error: "Email aready exists" });
}
const hashedPassword = await hash(password, 12);
const userObj = {
username: username,
password: hashedPassword,
email: email,
};
const user = new User(userObj);
await user.save();
const token = jwt.sign({ email: email }, secret, { expiresIn: "1h" });
return res
.status(200)
.json({ message: "user successfully created", token });
}
} catch (error) {
return res.status(500).json("Internal Server Failure");
}
}