How to set up session management in next-auth v5 using nextjs app router using credentails as provider

107 views Asked by At

i keep getting empty user object in my session object.

i keep getting an empty user obj in the session, this is my auth.ts

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import Credentials from 'next-auth/providers/credentials';
import { getUser } from './app/lib/data';
import { z } from 'zod';


// zod schema
const UserSchema = z.object({
    username: z.string().max(10).min(2),
    password: z.string().min(8),
});



export const { auth, signIn, signOut } = NextAuth({
    ...authConfig,
    providers: [
        Credentials({
            async authorize(credentials) {

                const parsedCredentials = UserSchema.safeParse(credentials);
                console.log(parsedCredentials);


                if (parsedCredentials.success) {

                    const { username, password } = parsedCredentials.data;
                    const user = await getUser(username);

                    if (!user) return null;
                    
                    if (user.password === password) {
                        return user;
                    } // TODO: use bcrypt
                }


                console.log('invalid cred');
                return null;

            },
        }),
    ],
    callbacks: {
        authorized(params) {
          return !!params.auth?.user;
        },
      },
});

the session object

{ user: {}, expires: "2024-03-20T06:33:01.264Z" }

the userSchema when creating the user and saving to db

username: string
password: string
is_admin: boolean
expert: boolean
created_at: date

the signUp action for the form in auth-actions.ts

export async function signUp(prevState: State, formData: FormData) {

    const validatedFields = CreateUser.safeParse({
        username: formData.get('username'),
        password: formData.get('password'),
    });

    if (!validatedFields.success) {
        return {
            errors: validatedFields.error.flatten().fieldErrors,
            message: 'Missing Fields. Failed to sign up.',
        };
    }

    const useroObj = validatedFields.data;
    const usernameTaken = await usernameIsUnique(useroObj.username);
    if (usernameTaken) {
        return {
            errors: { username: ['someone beat you to it, choose somethiing else'] }
        };
    }


    // create the user before sign in
    try {
        const user = await createUser(useroObj);
    } catch (error) {
        // database error
        return {
            message: 'something went wrong please try again later',
        };
    }

    // sign in user to session
    const authUser = await signIn('credentials', formData);
    

    revalidatePath('/', 'layout');

    return {
        message: 'signed up successfully'
    };

}

its obvious that this is my first time using next-auth, and i tried reading the docs, but could only get so much from it--- please help me out thanks

0

There are 0 answers