I am using email, password and username to register user and storing in mongodb. I want to use next Auth to store sessions at time of registration also. I want to redirect user in same way at registration in same way as user would logged in and session get stored. I cant seem to find a way to this a time of registration. Do I need to make user login again after registering to handle all auth related things using next Auth.
I am adding 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");
}
}
2
Answers
Since you use NextJS, you should probably be using the next/auth handler in your api.
create the file
/app/api/auth/[...nextauth]/route.ts
and use this inside :
Generally, follow the steps described in the docs to get started in a fresh working way
https://next-auth.js.org/getting-started/example#existing-project
Okay @zanea answer is correct but i will be more specific on how to go about it.
After creating the
/app/api/auth/[...nextauth]/route.ts
fileNow in your
SignUp Route Page
orSignIn Route Page
import
SignIn
fuction from"next-auth/react"
and send all the user credentials to nextAuth by callingNow in your
/app/api/auth/[...nextauth]/route.ts
, you need to have include a CredentialProvider that will handle server fetching.Next in your same
/app/api/auth/[...nextauth]/route.ts
, you need to have add various callbacks that will help you in persisiting the session and also storing it.Now for better understanding of the flow i would advice you also go through the docs https://next-auth.js.org/getting-started/introduction and look at what each API does do you can tailor it to your needs