1 year ago
#319213
Peter Kellner
How to have NextJS Auth example automatically login after sign-up
The example in the NextJS repository uses cookie storage and iron-session in order to maintain auth during a user's logged in session. The example code is at this URL:
https://github.com/vercel/next.js/tree/canary/examples/with-passport
Unfortunately, it forces the user to first signup for a new account, then login with those credentials instead of automatically logging the user in when a successful signup is made.
It uses the NextJS API Routes, and the Passport Local strategy for authentication. I'm pasting the code below for both the sign up and the login routes.
I found some other SO posts that talked about how to use the authenticate method in login inside the signup method, but I believe that requires middleware that I don't understand. I can't just paste in the code from login into signup.
My question is, I want to have signup
automatically create the cookie and then redirect to some other page in a logged in state.
/pages/api/signup.js
import { createUser } from '../../lib/user'
export default async function signup(req, res) {
try {
await createUser(req.body)
res.status(200).send({ done: true })
// WANTING TO ADD SOME CODE POSSIBLY HERE TO AUTO LOGIN
} catch (error) {
console.error(error)
res.status(500).end(error.message)
}
}
/pages/api/login.js
import passport from 'passport'
import nextConnect from 'next-connect'
import { localStrategy } from '../../lib/password-local'
import { setLoginSession } from '../../lib/auth'
const authenticate = (method, req, res) =>
new Promise((resolve, reject) => {
passport.authenticate(method, { session: false }, (error, token) => {
if (error) {
reject(error)
} else {
resolve(token)
}
})(req, res)
})
passport.use(localStrategy)
export default nextConnect()
.use(passport.initialize())
.post(async (req, res) => {
try {
const user = await authenticate("local", req, res);
// session is the payload to save in the token, it may contain basic info about the user
const session = { ...user };
await setLoginSession(res, session);
res.status(200).send({ done: true });
} catch (error) {
console.error(error);
res.status(401).send(error.message);
}
});
reactjs
authentication
next.js
passport.js
passport-local
0 Answers
Your Answer