When we build a full stack app, we need a way for users to login and stay logged in.
This is called authentication.
In this blog we will understand how to use NextAuth in Next.js in a very simple way ?
? What is NextAuth
NextAuth is a library that helps us:
✔ Login users
✔ Manage sessions
✔ Protect pages
? Example
User enters email and password
App checks database
If correct → user is logged in ✅
? Step 1 Install NextAuth
Run this command:
npm install next-auth@4
? Step 2 Add Secret Key
Create or open .env file
NEXTAUTH_SECRET=mySuperSecretKey123
? This is used to secure login sessions
? Step 3 Add TypeScript Support
Create file:
next-auth.d.ts
Add:
declare module "next-auth"
interface Session
user:
id: string;
& DefaultSession["user"];
? Now we can use:
session.user.id
⚙️ Step 4 Create Auth Configuration
Create file:
lib/auth.ts
import CredentialsProvider from "next-auth/providers/credentials";
import connectToDatabase from "./db";
import User from "@/models/User";
import bcrypt from "bcryptjs";
export const authOptions =
providers: [
CredentialsProvider(
name: "Credentials",
credentials:
email: label: "Email", type: "text" ,
password: label: "Password", type: "password" ,
,
async authorize(credentials)
if (!credentials?.email ,
),
],
callbacks:
async jwt( token, user : token: any; user?: any )
if (user)
token.id = user.id;
return token;
,
async session( session, token : session: any; token: any )
if (session.user)
session.user.id = token.id as string;
return session;
,
,
pages:
signIn: "/login",
error: "/login",
,
session:
strategy: "jwt" as const,
maxAge: 30 * 24 * 60 * 60,
,
secret: process.env.NEXTAUTH_SECRET,
;
This file contains all login logic.
? Step 5 Credentials Provider
CredentialsProvider({
name: "Credentials",
? This tells NextAuth:
? “I will login users using email and password”
? Step 6 Authorize Function (Main Logic)
async authorize(credentials)
? This runs when user tries to login
? Example Input
"email": "[email protected]",
"password": "123456"
? What happens inside authorize
1️⃣ Check input
if (!credentials?.email || !credentials?.password)
? If missing → error
2️⃣ Connect database
await connectToDatabase();
? Connects to MongoDB
3️⃣ Find user
const user = await User.findOne( email: credentials.email );
? Check if user exists
4️⃣ If user not found
throw new Error("No user found")
5️⃣ Compare password
bcrypt.compare(credentials.password, user.password)
? Checks password safely ?
6️⃣ If correct
return
id: user._id.toString(),
email: user.email,
;
? Login success ?
? Step 7 JWT Callback
async jwt( token, user )
? Runs after login
token.id = user.id;
? Saves user id in token
? Step 8 Session Callback
async session( session, token )
session.user.id = token.id;
? Now you can access:
session.user.id
? Step 9 Custom Pages
pages:
signIn: "/login",
error: "/login",
? Redirects user to login page
⏳ Step 10 Session Setup
session:
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60,
? User stays logged in for 30 days
? Step 11 Create API Route
Path:
app/api/auth/[...nextauth]/route.ts
Code:
import authOptions from "@/lib/auth";
import NextAuth from "next-auth/next";
const handler = NextAuth(authOptions);
export handler as GET, handler as POST ;
? This handles all auth requests
? Step 12 Middleware (Protect Routes)
Create file:
middleware.ts
import withAuth from "next-auth/middleware";
import NextResponse from "next/server";
export default withAuth(
f
Tags:
#0
Want to run a more efficient business?
Mewayz gives you CRM, HR, Accounting, Projects & eCommerce — all in one workspace. 14-day free trial, no credit card needed.
Try Mewayz Free →