Why User is redirect in signin after signup and how can i fix it?

Hi there! I am doing a next.js application and i have a issue, when i use /signup and create a user, it’s supossed to redirect in /usuario, but instead is going to /signin after being a moment in /usuario, idk why it’s making that
To clarify, i using nextAuth for the login
Here is the signup page:

"use client"
import Link from "next/link"
import Image from 'next/image';
import CustomButton from '../../components/CustomButton';
import {signIn, useSession} from 'next-auth/react'
import { Navbar2 } from "@/components";
import { useRouter } from "next/navigation";
import React, {useState} from "react";
import CustomAlert from '@/components/CustomAlert';

export default function Form(){
    const router = useRouter();
    const { data: session, status: sessionStatus } = useSession();
    
    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const res = await fetch("/api/usuarios",{
            method: "POST",
            body: JSON.stringify(formData),
            headers:{
                "Content-Type": "application/json"
            }
            
        })
        
        if(res.ok){
            router.replace("/usuario");
        } else {
            throw new Error("Error al crear el usuario")
        }
        
    }
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) =>{
        const value = e.target.value;
        const name = e.target.name;
        setFormData((prevState) => ({
            ...prevState,
            [name]: value,
        }));
    }
    const startingUsuariosData={
        nombre: "",
        apellido: "",
        correo: "",
        contrasena: "",
        role: "usuario",
    };
   
    const [formData, setFormData] = useState(startingUsuariosData);
   

    export default function Form(){
        
        return(
            <>

The signin page

"use client"
import Link from "next/link"
import Image from 'next/image';
import CustomButton from '@/components/CustomButton';
import {signIn, useSession} from 'next-auth/react'
import { Navbar2 } from "@/components";
import { useRouter } from "next/navigation";
import React, {useEffect, useState} from "react";
import CustomAlert from '@/components/CustomAlert';

export default function Form(){
    // const session = useSession();
    const router = useRouter();
    const { data: session, status: sessionStatus } = useSession();
    const [alertMessage, setAlertMessage] = useState(""); // Mensaje de alerta
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        if (sessionStatus === "authenticated") {
        //router.replace("/usuario");
            if(session?.user?.role === "usuario"){
                router.replace("/usuario");
        }else{
            router.replace("/terapeuta");
        }}
    }, [sessionStatus, router]);

    const handleSubmit = async (e: any) => {
        e.preventDefault();
        const email = e.target[0].value;
        const password = e.target[1].value;

        const res = await signIn('credentials', {
            email,
            password,
            redirect: false,
        });

        if (res?.error) {
            setAlertMessage("Contraseña y/o correo eléctronico incorrecto");
            setIsVisible(true);
        }
    };

    if (sessionStatus === "loading") {
        return <h1>Loading...</h1>;
    }

    return(
        <>

The route.ts (who is in charge of the signin process and signup in case of using google)

import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import CredentialsProvider from "next-auth/providers/credentials";
import { connectDB } from "@/libs/mongodb";
import User from "@/models/usuarios";
import { GoogleProfile } from 'next-auth/providers/google';
import getServersession from 'next-auth';



const authOptions = {   //const handler = NextAuth({ -> lo que estaba antes
    providers: [ 
        GoogleProvider ({
        profile(profile:GoogleProfile){
            return{
                ...profile,
                role: "usuario",
                id: profile.sub,
            }
        },
        clientId: process.env.GOOGLE_CLIENT_ID as string,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
        }),
        CredentialsProvider({
            id: 'credentials',
            name: "Credentials",
            credentials: {
              email: { label: "Email", type: "text" },
              password: { label: "Password", type: "text" },
            },
            
            async authorize(credentials: any) { //credentials: any

            {
              await connectDB();
              try {
                
                const user = await User.findOne({ correo: credentials.email });
                if (user && user.contrasena === credentials.password) {
                    // La contraseña coincide, puedes devolver el usuario
                   // console.log(user);
                    return user;
                } else {
                    // La contraseña no coincide
                    return null;
                }
              } catch (err: any) {
                throw new Error(err);
              }}  
            },
          })
    ],
    callbacks: {
        
        async signIn({user, account}: { user: any, account: any }) {
            if (account?.provider === 'credentials') {
                //console.log(user);
                return true;
            }
            if (account && account.provider === 'google') {
                const {name, email} = user;
                try {
                    const res = await fetch('http://localhost:3000/api/usuarios', { //http://localhost:3000/api/usuarios
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            nombre: name,
                            correo: email,
                            role:  "usuario",
                        }),
                    });
                    if (res.ok) {
                        console.log(user)
                        return true;
                    }
                } catch (error) {
                    console.error(error);
                    return false;
                }
            }
            return true;
        },
         jwt({ token, user }: { token: any, user: any }) {
            // Persist the OAuth access_token to the token right after signin
            if (user) {
              token.role = user.role
            }
            //console.log(token);
            return token;
          },
           session({ session, token}: { token: any, session: any }) { //, user 
            // Send properties to the client, like an access_token from a provider.
            //session.accessToken = token.accessToken
            session.user.role = token.role
            //console.log(session);
            return session;
          }
        
        
    }
};
const handler = NextAuth(authOptions);
export {handler as GET, handler as POST};

And the route.js (this in a file called usuarios, here you insert users into the database)

import { connectDB } from "@/libs/mongodb";
import  Usuarios from "@/models/usuarios";
import { NextResponse } from "next/server";

//Función GET para obtener todos los usuarios
export async function GET() {
    await connectDB();
    const usuarios = await Usuarios.find({});
    return NextResponse.json({ usuarios });
}


export async function POST(request) {
    await connectDB();
    const data = await request.json();
    const userExists = await Usuarios.findOne({ correo: data.correo });
    if (!userExists) {
        const usuarios = await Usuarios.create(data);
        return NextResponse.json({ usuarios });
    } else{
        //Si el usuario ya existe, no hace nada
        return NextResponse.json({ message: "Usuario ya existe" });
    }
}

export async function DELETE(request) {
    const id = request.nextUrl.searchParams.get("id");
    await connectDB();
    await Usuarios.findByIdAndDelete(id);
    return NextResponse.json({ message: "Usuario eliminado" });
}

Hey there @isafranco13 , thank you for posting! :+1:

Let me please replay generically, providing known-to-me scenarios so you can possibly find an analogy to your stack.

Generally speaking, the sign-in after sign-up is required only if specifically set this way.

With the Auth0-hosted Universal Login page, a user should be automatically logged in after the sign-up by default.
With the customer-hosted Login page implementing the Auth0’s Lock library, configuring Lock with the option loginAfterSignUp:true should ensure the behavior.

Another scenario is when you are registering a user from your backend. Then you could log the user in via the Resource Owner Password grant and get the user tokens.

Also, it could be a good idea to review if there are Action scripts in your Auth0 tenant that may result in requiring the login after the signup.

Hope this helps! Happy to open the topic to a broader audience as well!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.