46
loading...
This website collects cookies to deliver better user experience
npm i next-auth mongodb bycryptjs
.env.local
file for more refined and secure code.pages/api
folder using the NodeJS environment. It will also follow the same folder-structured route.pages/api/auth/signup.js
. We also need to make sure that only the POST method is accepted and nothing else.password: await hash(password, 12)
//hash(plain text, no. of salting rounds)
import { MongoClient } from 'mongodb';
import { hash } from 'bcryptjs';
async function handler(req, res) {
//Only POST mothod is accepted
if (req.method === 'POST') {
//Getting email and password from body
const { email, password } = req.body;
//Validate
if (!email || !email.includes('@') || !password) {
res.status(422).json({ message: 'Invalid Data' });
return;
}
//Connect with database
const client = await MongoClient.connect(
`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_CLUSTER}.n4tnm.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
const db = client.db();
//Check existing
const checkExisting = await db
.collection('users')
.findOne({ email: email });
//Send error response if duplicate user is found
if (checkExisting) {
res.status(422).json({ message: 'User already exists' });
client.close();
return;
}
//Hash password
const status = await db.collection('users').insertOne({
email,
password: await hash(password, 12),
});
//Send success response
res.status(201).json({ message: 'User created', ...status });
//Close DB connection
client.close();
} else {
//Response for other than POST method
res.status(500).json({ message: 'Route not valid' });
}
}
export default handler;
import { signIn } from 'next-auth/client';
//...
const onFormSubmit = async (e) => {
e.preventDefault();
//Getting value from useRef()
const email = emailRef.current.value;
const password = passwordRef.current.value;
//Validation
if (!email || !email.includes('@') || !password) {
alert('Invalid details');
return;
}
//POST form values
const res = await fetch('/api/auth/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
}),
});
//Await for data for any desirable next steps
const data = await res.json();
console.log(data);
};
//...
The NextAuth.js client library makes it easy to interact with sessions from React applications.
NextAuth.js exposes a REST API which is used by the NextAuth.js client.
To add NextAuth.js to a project create a file called [...nextauth].js
in pages/api/auth
.
All requests to /api/auth/*
(signin, callback, signout, etc) will automatically be handed by NextAuth.js.
[...nextauth].js
:import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { MongoClient } from 'mongodb';
import { compare } from 'bcryptjs';
export default NextAuth({
//Configure JWT
session: {
jwt: true,
},
//Specify Provider
providers: [
Providers.Credentials({
async authorize(credentials) {
//Connect to DB
const client = await MongoClient.connect(
`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@${process.env.MONGO_CLUSTER}.n4tnm.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
//Get all the users
const users = await client.db().collection('users');
//Find user with the email
const result = await users.findOne({
email: credentials.email,
});
//Not found - send error res
if (!result) {
client.close();
throw new Error('No user found with the email');
}
//Check hased password with DB password
const checkPassword = await compare(credentials.passowrd, result.passowrd);
//Incorrect password - send response
if (!checkPassword) {
client.close();
throw new Error('Password doesnt match');
}
//Else send success response
client.close();
return { email: result.email };
},
}),
],
});