MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Authentication with NextAuth / Auth.js & JWT Session Management0%
Study Materials
Next.js 15Progress 0%
1.1Next.js 15 Overview & App Router vs Pages Router Architecture1.2Core File Conventions: page.tsx, layout.tsx, template.tsx & not-found.tsx1.3Dynamic Routes ([id]), Catch-All Routes ([...slug]) & Route Groups ((group))1.4Streaming UI with loading.tsx and Suspense Boundaries
4.1API Route Handlers (route.ts): Building RESTful Microservices4.2Middleware.ts: Route Protection, Redirects, Cookies & Geolocation4.3Authentication with NextAuth / Auth.js & JWT Session Management4.4Metadata API: Dynamic SEO, OpenGraph Tags & Sitemap Generation4.5Production Optimization, Dockerization & Vercel Cloud Deployment
HomeTutorialsNext.js 15Authentication with NextAuth / Auth.js & JWT Session Management
Metadata API: Dynamic SEO, OpenGraph Tags & Sitemap Generation

Authentication with NextAuth / Auth.js & JWT Session Management

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Securing user identity across Server Components, Client Components, and API Route Handlers is essential for modern applications. Auth.js (formerly NextAuth.js) is the complete, open-source authentication solution for Next.js, supporting OAuth social logins (Google, GitHub), Credentials login, database adapters, and stateless JWT sessions.


1. Setting Up Auth.js in Next.js 15

Install the core package:

1npm install next-auth@beta

Create the centralized configuration file:

1// auth.ts
2import NextAuth from 'next-auth';
3import GitHub from 'next-auth/providers/github';
4import Google from 'next-auth/providers/google';
5import Credentials from 'next-auth/providers/credentials';
6import bcrypt from 'bcrypt';
7import dbConnect from '@/lib/dbConnect';
8import User from '@/models/User';
9 
10export const { handlers, signIn, signOut, auth } = NextAuth({
11 providers: [
12 GitHub({
13 clientId: process.env.AUTH_GITHUB_ID,
14 clientSecret: process.env.AUTH_GITHUB_SECRET
15 }),
16 Google({
17 clientId: process.env.AUTH_GOOGLE_ID,
18 clientSecret: process.env.AUTH_GOOGLE_SECRET
19 }),
20 Credentials({
21 credentials: {
22 email: { label: 'Email', type: 'email' },
23 password: { label: 'Password', type: 'password' }
24 },
25 authorize: async (credentials) => {
26 await dbConnect();
27 const user = await User.findOne({ email: credentials.email }).select('+password');
28 if (!user) return null;
29 
30 const isMatch = await bcrypt.compare(credentials.password as string, user.password);
31 if (!isMatch) return null;
32 
33 return { id: user._id.toString(), name: user.name, email: user.email, role: user.role };
34 }
35 })
36 ],
37 callbacks: {
38 jwt({ token, user }) {
39 if (user) {
40 token.id = user.id;
41 token.role = (user as any).role;
42 }
43 return token;
44 },
45 session({ session, token }) {
46 if (session.user) {
47 (session.user as any).id = token.id;
48 (session.user as any).role = token.role;
49 }
50 return session;
51 }
52 },
53 session: { strategy: 'jwt' }
54});

2. Exposing Route Handlers

Wire up the authentication endpoints in the App Router:

1// app/api/auth/[...nextauth]/route.ts
2import { handlers } from '@/auth';
3export const { GET, POST } = handlers;

3. Protecting Server Components & Pages

In Server Components, reading the active user session is a clean, synchronous one-liner with zero client-side waterfall:

1// app/dashboard/page.tsx
2import { auth } from '@/auth';
3import { redirect } from 'next/navigation';
4 
5export default async function DashboardPage() {
6 const session = await auth(); // Inspect session directly on the server!
7 
8 if (!session?.user) {
9 redirect('/api/auth/signin');
10 }
11 
12 return (
13 <div className="p-8">
14 <h1 className="text-2xl font-bold">Welcome back, {session.user.name}!</h1>
15 <p>Role: {(session.user as any).role}</p>
16 </div>
17 );
18}

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
How do you access the active authenticated user session inside an async React Server Component using Auth.js?
Question 2
Which session strategy stores user session state securely inside an encrypted HTTP-Only cookie without requiring a database query on every request?
Question 3
Which callback in Auth.js is used to inject custom claims (such as a user's role or organization ID) into the client session object?
Question 4
What is the role of app/api/auth/[...nextauth]/route.ts?
Question 5
Why is useSession() restricted strictly to Client Components marked with 'use client'?

Next Lesson

Metadata API: Dynamic SEO, OpenGraph Tags & Sitemap Generation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Middleware.ts: Route Protection, Redirects, Cookies & GeolocationMetadata API: Dynamic SEO, OpenGraph Tags & Sitemap Generation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Next.js 15 with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext