Integration

NextAuth.js provides authentication for Next.js applications, supporting various providers. It simplifies user management, session handling, and integrates seamlessly with Next.js features for secure authentication.

prisma/schema.prisma

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Account {
  ......
}

model Session {
  .....
}

model User {
  ......
}

model VerificationToken {
  .......
}

pages/api/auth/[...nextauth].js

Your custom credentials and provider configurations are defined in the pages/api/auth/[...nextauth].js file, allowing for tailored authentication logic in your Next.js application.

export const authOptions = {
    adapter: PrismaAdapter(prisma),
    providers: [
        GoogleProvider({
           .... 
        }),
        FacebookProvider({
           ......
        }),
        GithubProvider({
           .....
        }),
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                email: { label: "Email", type: "text" },
                password: { label: "Password", type: "password" },
            },
            async authorize(credentials) {
               //your custom credentials
                return user;
            },
        }),
    ],
    session: {
        strategy: "jwt",
    },
    secret: process.env.NEXTAUTH_SECRET,
    debug: process.env.NODE_ENV === "development",
    pages: {
        signIn: "signin page path", // Customize sign-in page path
        error: "error page path",
    },
};

export default NextAuth(authOptions);

src/pages/api/signup/index.js

All signup and signin functionalities are implemented in the src/pages/api/signup/index.js file, providing the necessary API routes for user authentication in your application.

import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@src/lib/db"; // Ensure this points to your prisma instance
import { isValidEmail, isStrongPassword } from "@src/lib/validation"; // Implement your validation functions

export default async function POST(request: Request) {
    const { name, email, password } = await request.json();

    if (!name || !email || !password || !isValidEmail(email)) {
        return NextResponse.json(
           .....        
	);
    }

    if (!isStrongPassword(password)) {
        return NextResponse.json(
          ...
        );
    }

    const existingUser = await prisma.user.findUnique({
        where: { email: email.toLowerCase() },
    });

    if (existingUser) {
        return NextResponse.json(
           ...
        );
    }

    const hashedPassword = await bcrypt.hash(password, 12);

    const user = await prisma.user.create({
      ...
    });

    return NextResponse.json(
        ....
    );
}

pages/auth/signup.jsx

import { useState } from "react";
import { useRouter } from "next/router";

export default function SignupPage() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const router = useRouter();

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        const response = await fetch("/api/auth/signup", {
            ...
        });

        const data = await response.json();
        if (data.success) {
           ....
        } else {
            ...
        }
    };

    return (
        <div>
            <h1>Sign Up</h1>
            <form onSubmit={handleSubmit}>
              ....
                <button type="submit">Sign Up</button>
            </form>
        </div>
    );
}

pages/auth/signin.jsx

import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/router";

export default function LoginPage() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const router = useRouter();

    const handleSubmit = async (e: React.FormEvent) => {
       .....
    };

    return (
        <div>
            <h1>Login</h1>
            <form onSubmit={handleSubmit}>
               .....
                <button type="submit">Login</button>
            </form>
        </div>
    );
}

.env

Ensure you set the necessary environment variables in your .env.local file:

FACEBOOK_CLIENT_SECRET="your-facebook-client-secret"
GITHUB_ID="your-github-client-id"
GITHUB_SECRET="your-github-client-secret"
NEXTAUTH_SECRET="your-nextauth-secret"

This guide covers everything you need to know to make sure Tailwind generates all of the CSS needed for your project.

Receive the latest updates directly in your inbox!

Be the first to know about new updates and exclusive discounts. No spam, just great offers!

How about

A Custom Project?

With over 7 years of experienced team, we specialize in delivering custom projects for startups, blue-chip companies, and government agencies. We have successfully completed over 250+ projects, providing tailored solutions that meet the unique needs of each client.

Hire Us
Domiex Admin & Dashboards
230+

Total Pages

5+

Layouts

11+

Application

We provide quick support withing one business day to all of our customers.

© Domiex Created & Crafted by SRBThemes.