How to automatically sign-in user in after they click a verify email link sent to their email inbox?

Once a user registers an account, the page prompts them to click the link in the email sent to them. How can I make that link automatically log them in? Is this possible, or would they still have to log in manually after verifying their email? One idea i had was to "pseudo" sign them in upon registration, and then them clicking on the verify link re-validates the registration page, giving them full access.
Is there a better way to do this?
16 Replies
sean
sean15mo ago
I would say there are a million ways to do this. You could do something like:
example.com/verify/SuperSecretAndUniqueCodeThatExpires
example.com/verify/SuperSecretAndUniqueCodeThatExpires
Then validate the super-secret token and return a cookie with the user session and finally redirect the user to the dashboard
machina
machina15mo ago
the only way I know how to return a cookie with the user session is with
await signIn("credentials", {
email,
password,
callbackUrl: "/dashboard",
});
await signIn("credentials", {
email,
password,
callbackUrl: "/dashboard",
});
is there a way to do this without their credentials?
sean
sean15mo ago
Oh gosh don't do that
machina
machina15mo ago
like in general or in this context
sean
sean15mo ago
First of all, you should never store a user's password Like never ever
machina
machina15mo ago
no yeah i only store it hashed and salted the signIn is just a nextauth function that i plug in the form info into
sean
sean15mo ago
Anyhow, you can create a session token with the credentials Maybe with JWT?
sean
sean15mo ago
JWT.IO
JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
sean
sean15mo ago
In JWT you should only put information that you need to identify the user. DO NOT put their password into it. Just use an ID and the token expiration and creation date Anyhow, I've never used next-auth, so they might have a different approach. Check out their docks
machina
machina15mo ago
ok so they click the link, the we look up the user associated with superSecretToken and make a JWT for that user, we send that JWT to the client's cookie jar, and then redirect them to a dashboard? circumventing the credential input process?
sean
sean15mo ago
Yes
machina
machina15mo ago
ok
sean
sean15mo ago
Also, when the user first registers their account you can return a cookie anyways and then handle if they are verified or not. (a lot of websites tell you to verify with a popup or something like that)
machina
machina15mo ago
have you used nextAuth.js by any chance?
sean
sean15mo ago
.
machina
machina15mo ago
Oh whoops haha Thanks
Want results from more Discord servers?
Add your server