Setting up NextAuth.js

NextAuth.js is a powerful authentication library for Next.js that supports multiple authentication methods, including email and password authentication.

1. Install NextAuth

Run the following command to install NextAuth.js:

npm install next-auth
2. Configure NextAuth

Create an authentication handler in src/app/api/auth/[...nextauth]/route.js:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions = {
    providers: [
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                email: { label: "Email", type: "text" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials) {
                if (!credentials?.email || !credentials?.password) {
                    throw new Error('Invalid credentials');
                }
                return {
                    id: user.id.toString(),
                    name: user?.name || null,
                    email: user?.email || null,
                    image: user?.image || null,
                };
            }
        })
    ],
    pages: {
        signIn: "/auth/signin",
        error: '/auth/error'
    }
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
3. Add Authentication Provider

Wrap your app with the SessionProvider in src/app/layout.jsx:

'use client';

import { SessionProvider } from "next-auth/react";

export default function RootLayout({ children }) {
    return {children};
}
4. Use Authentication Hooks
'use client';                  
 import { useSession, signIn, signOut } from "next-auth/react";
                        
 export default function AuthStatus() {
    const { data: session } = useSession();
    return (
        <>
            {session ? (
                <>
                    <p>Signed in as {session.user?.email}</p>
                    <button onClick={() => signOut()}>Sign out</button>
                </>
            ) : (
                <button onClick={() => signIn()}>Sign in</button>
            )}
        </>
    );
}
             
5. Protecting Routes

Protect pages by checking authentication status:

import { getServerSession } from "next-auth";
import { useSession } from 'next-auth/react';

export default async function Dashboard() {
    const { data: session, status } = useSession();
    {session ? (
        <>
            

Welcome, {session.user.name}!

Email: {session.user.email}

</> ) : (

You are not logged in.

)} }
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.