NextAuth.js is a powerful authentication library for Next.js that supports multiple authentication methods, including email and password authentication.
Run the following command to install NextAuth.js:
npm install next-auth
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 };
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} ; }
'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> )} </> ); }
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.
)} }
Be the first to know about new updates and exclusive discounts. No spam, just great offers!
How about
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 Created & Crafted by SRBThemes.