case scenario -
implementing next-auth in nextjs web app .
first step - install next-auth library
npm install next-auth
second step - adding next-auth login api
src/pages/api/auth/[...nextauth].ts
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcryptjs";
import db from "@/lib/db";
export default NextAuth({
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const [rows] = await db.query("SELECT * FROM users WHERE email = ?", [credentials?.email]);
const user = (rows as any)[0];
if (!user) return null;
const isValid = user.password_hash
? await compare(credentials!.password, user.password_hash)
: credentials!.password === user.password;
if (!isValid) return null;
if (user.role !== 'admin') return null;
return { id: user.id, name: user.name, email: user.email, role: user.role };
},
}),
],
session: {
strategy: "jwt",
},
pages: {
signIn: "/admin", // or "/login" depending on your UI
},
secret: process.env.NEXTAUTH_SECRET,
});
.env.local
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-strong-secret-key
next step -
_app.tsx
import { SessionProvider } from "next-auth/react";
import type { AppProps } from "next/app";
import "../globals.css";
import Layout from "@/components/Layout";
export default function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
return (
);
}
login page -
import { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/router';
import styles from './Login.module.css';
export default function AdminLogin() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const router = useRouter();
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const res = await signIn('credentials', {
redirect: false,
email,
password,
});
if (res?.error) {
setError('Invalid credentials');
setLoading(false);
} else {
router.push('/admin/dashboard');
}
}
return (
Admin Login
Email
<input
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="admin@example.com"
/>
Password
<input
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Your password"
/>
{loading ? 'Logging in...' : 'Login'}
);
}