skip to Main Content

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


  1. 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 :

    import type { NextApiRequest, NextApiResponse } from "next"
    import NextAuth from "next-auth"
    
    export default async function auth(req: NextApiRequest, res: NextApiResponse) {
    
      // Do whatever you want here, before the request is passed down to `NextAuth`
    
      return await NextAuth(req, res, {
    
        // NEXT AUTH OPTIONS HERE
    
      })
    }
    

    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

    Login or Signup to reply.
  2. 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 file

    Now in your SignUp Route Page or SignIn Route Page

    import SignIn fuction from "next-auth/react" and send all the user credentials to nextAuth by calling

    signIn(
    'credentials', //very important, its lets  nextAuth knows you want to use your credentials and not a provider like "Google"
     {
       ... Add user crendtials like email and password
       callbackUrl: "/on-boarding" // callbackUrl you want the user to be redirected to after they finish auth
       })
    

    Now in your /app/api/auth/[...nextauth]/route.ts, you need to have include a CredentialProvider that will handle server fetching.

      CredentialsProvider({
                async authorize(credentialPayload: any) {
                     // credentialPayload will be the user credentials you passed into the SignIn Fucn
                  
                   ...Now run all your mongodb logic here for getting the user token
                    
                    //Now make sure you return the data gotten from your mongodb Database, this should be what you want to store in the userSession
                    return data;
    
                },
            }),
    

    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.

     callbacks: {
            async signIn({ account, user }) {
            //Note that "user" will be the data value you returned from "CredentialsProvider", you are only passing the value down to jwt callback here
                if (account) {
                    account.userData = user; // pass value down to jwt callback func   
                }
                // make sure to return true;
                return true;
    
            },
    
            async jwt({ token, account, trigger, session }) {
                // Persist the OAuth access_token to the token right after signin
                if (account) {
                      if (account.provider === "credentials") { // make sure its credentialsProvider as you can have other Providers e.g "Google"
                        
                        /* 
                        Credential Auth is mainly handled in credential "Authorize" 
                        func.
                        you are only passing the value to session Token here
                         */
                        if (account.userData) {
                            token = account.userData;
    
                        } else {
                            token = {
                                accessToken: null,
                                isAuthError: true,
                            }
                        }
                    }
                }
    
    
    
                return token
            },
            async session({ session, token, }) {
                // Send properties to the client
    
                session = {
                    ...token,
                };
                return session
            }
        }
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search