Next.js Full Course Level2

1مُقدمة المُستوى الثانى
2Design Signin & Register pages with bootstrapnpm i bootstrap
import "bootstrap/dist/css/bootstrap.min.css";

For JavaScript:


 useEffect(() => {
   require("bootstrap/dist/js/bootstrap.bundle.min.js");
 }, []);

Download files

3Task Solution

Download files

4هنعمل إيه ؟
5⭐ Example for submitting a form in registration page

server-components VS Client Components

"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";


 const [name, setname] = useState(null);
 const [email, setemail] = useState(null);
 const [password, setpassword] = useState(null);
 const [isLoading, setisLoading] = useState(false);
 const [error, seterror] = useState(null);

 const router = useRouter();

 const handleSubmit = async (eo) => {
   eo.preventDefault();
   setisLoading(true);
   seterror(null);

   if (!name || !email  || !password) {
     seterror("All input must be filled");
     setisLoading(false);
     return;
   }

   // CHECK if email already exist
   // Go to api/userExist/route.js
   const resUserExist = await fetch("api/userExist", {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify({
       email,
     }),
   });

   const isUserExistObj = await resUserExist.json();
   console.log(isUserExistObj);

   if (isUserExistObj.user) {
     seterror("User Already exist");
     setisLoading(false);
     return;
   }

   // send data to DB
   // Go to api/register/route.js
   const response = await fetch("api/register", {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify({
       name,
       email,
       password,
     }),
   });

   const dataFromBackend = await response.json();
   console.log(dataFromBackend);
   if (response.ok) {
     eo.target.reset();
     router.push("/signin");
   } else {
     setisLoading(false);
     seterror("faild to create acoount, Please try again");
   }

   setisLoading(false);
 };

Download files

6app>api>FOLDER NAME>route.js For POST request

JavaScript fetch

route.js

Download files

7Connecting MongoDB to Next.js

👉 mongodb.com

👉 npm i mongoose


const mongoose = require("mongoose");
 
export const connectMongoDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URL);
    console.log("connected to MongoDB");
  } catch (error) {
    console.log("ERROR WITH CONNECTING  MongoDB", error);
  }
};

Download files

8Store data in mongodb with with next.js

👉 1- Defining schema & Creating a model


 const mongoose = require("mongoose");
 const Schema = mongoose.Schema;
 const models = mongoose.models;

 // define the Schema (the structure of the article)
 const productSchema = new Schema({
   title: String,
   price: Number,
   description: String,
   productImg: String,
 });

 // Create a model based on that schema
 const ProductModal = models.Product || mongoose.model("Product", productSchema);

 // export the model
 module.exports = ProductModal;

👉 2- Model.create({})

Model.

Download files

9Check if email already exists in Database

Download files

10Show Error message

Download files

11Bootstrap Spinner && react-toastify

npm i react-toastify

Download files

12Hashing password with bcrypt.js

npm i bcrypt

 
import bcrypt from "bcrypt";
 
const salt = await bcrypt.genSalt();
const hashedPassword = await bcrypt.hash(objFromFrontend.password, salt);

Download files

Authentication for Next.js (NextAuth.js)

13⭐ Example for submitting a form in signin page

npm install next-auth

👉 in sign-in page:

 
 import { signIn } from "next-auth/react";
 import { useRouter } from "next/navigation";
 
 
 const [email, setemail] = useState(null);
 const [password, setpassword] = useState(null);
 const [error, seterror] = useState(null);
 const [isLoading, setisLoading] = useState(false);

 const router = useRouter();

 const handleSubmit = async (eo) => {
   setisLoading(true);
   eo.preventDefault();
   seterror(null);

   if (!email || !password) {
     seterror("All input must be filled");
     return;
   }

   // sign in with email & password
   // Go to api/auth/[...nextauth]/route.js
   const res = await signIn("credentials", {
     email,
     password,
     redirect: false,
   });
   console.log(res);

   if (res.error) {
     setisLoading(false);
     seterror("errorrrrrrr");
     return;
   }

   router.replace("/");
   setisLoading(false);
   // check if email not exist == return null
 };

👉 in app/auth/[...nextauth]/route.js

 
 import NextAuth from "next-auth";
 
 export const authOptions = {
  providers: [],
 };
 
 
 const handler = NextAuth(authOptions);
 export { handler as GET, handler as POST };

Download files

14Sign-in with CredentialsProvider(email & password)

Sign-in with Credentials

Download files

15Password Matching using bcrypt.js
 
async authorize(credentials, req, res) {
  await connectMongoDB();
  const user = await UserModal.findOne({email: credentials.email});
 
 if (user) {
  // الترتيب مهم جداً
  // compare(credentials.password, user.password);
   const match = await bcrypt.compare(credentials.password, user.password);
   if (match) {return user;} else {return null;}
 } else {
   return null;
 }
},

Download files

16Using useSession()to get user info

👉 Using <SessionProvider />at the top level of your application:

1- in AuthProvider.js

 
"use client";
import { SessionProvider } from "next-auth/react";
 
const AuthProvider = ({ children }) => {
  return <SessionProvider>{children}</SessionProvider>;
};
 
export default AuthProvider;

2- in layout.js

 
   <AuthProvider>{children}</AuthProvider>

3- use useSession() to get user info

 
  const { data: session, status } = useSession();

Download files

17Task Solution

Download files

18Use middleware.jsto protect your pages.

Next.js Middleware

Download files

19Strong Password

Password must be at least 8 characters with 1 uppercase, 1 lowercase, 1 special character and 1 numeric.

Download files

😡
انت مشغل الـ AdBlock !!

ياريت تقفله لوسمحت 😊 😊

تنبيه هام ✋

إذا كانت الإعلانات مزعجة بالنسبة لك، فيُمكنك التبرع ب50$ وسيتم إيقاف الإعلانات لمدة شهر لجميع زوار الموقع 🧡 ويُمكنك التواصل معنا عن طريق صفحة الفيس بوك