Next.js Discord

Discord Forum

Automatically Login after a user has signed

Unanswered
American Chinchilla posted this in #help-forum
Open in Discord
American ChinchillaOP
Since NextAuth does not have a signup flow with the credentials flow, I decided to create my own; The whole form process the signup flow correctly but after the correct creation of the user, it should also login him to the site without having to ask the credentials again (something automatic)
I tried looking at [this](https://stackoverflow.com/questions/68188861/next-auth-how-the-registration-is-handled-with-a-email-password-credential-p) post and at [this discussion](https://github.com/nextauthjs/next-auth/discussions/2285) too, to no avail really

So the question is, how can I programmatically login the user after his very signup process?

(I'll post the code below, since I have discord text limitation xd)

1 Reply

American ChinchillaOP
This is the code, removed of validation and some overhead complexity that isn't needed for this issue:
// Path: app/signup/page.js
'use client'
import React from 'react'
import { useFormState, useFormStatus } from 'react-dom'
import { authenticate } from '@root/app/lib/actions'
import http from 'axios'

const page = () => {
    const [errorMessage, dispatch] = useFormState(authenticate, undefined)
    const [data, setData] = React.useState({})

    const onSubmit = async (e) => {
        e.preventDefault()
        const response = await http.post('/api/signup', data)
        
        // If response is corect, I return true and dispatch should fire keeping the same data from the form
        return true
    }    

    // If dispatch doesn't run after onSubmit has been validated (and true returned)
    // How can I login the user?
    return <div>
        <form
            action={dispatch}
            onSubmit={onSubmit}
        >
            <input type="text" name="first_name" value={data.first_name} />
            <input type="text" name="last_name" value={data.last_name} />
            <input type="text" name="username" value={data.username}/>
            <input type="password" name="password" value={data.password}/>
            <input type="email" name="email" value={data.email}/>
            <input type="submit" name="submit"/>
            {errorMessage && <p className='text-[#f3f3f3] text-sm leading-snug mt-2 mb-2 text-center'>{errorMessage}</p>}
        </form>
    </div>
}

export default page


In case more details were required I will post more and update with everything needed. Thanks for having read this far