Skeptic Dev Logo

Menu

Sidebar for navigation

auth
next.js

How to Auth: NextAuth for Next.js

NextAuth is supposed to make auth easy in Next.js but if you've been struggling with it just like me, this guide is for you. Dive this tutorial on integrating NextAuth into your Next.js app using the app router (Next.js 14+). Without wasting further time, let's learn how to secure your Next.js app.

R
Ryo StylesAuthor
March 11, 2025
NextAuth Illustration
NextAuth Illustration

We're going to use JWT based session with MongoDB where the user data is saved on MongoDB while the auth strategy is JWT based.

Step 1: Create a Next.js 14+ App

Choose TypeScript, App Router, and say "yes" to all the boring stuff.

Step 2: Install Dependencies

  • mongoose: To store the user data in MongoDB.

  • @next-auth/mongoose-adapter: Glue between NextAuth and MongoDB.

  • bcrypt: For hashing passwords (even if you’re using Google login, it’s polite to have).

Step 3: Set Up MongoDB Connection

Create lib/dbConnect.ts:

Add MONGODB_URI to .env.local:

Step 4: Create a Google OAuth App

  • Visit Google Cloud Console.

  • Create a project > APIs & Services > Credentials.

  • Create an OAuth Client ID.

  • Add http://localhost:3000/api/auth/callback/google to "Authorized redirect URIs".

  • Grab Client ID and Client Secret. Add to .env.local:

Step 5: Set Up NextAuth with Mongoose

Create app/api/auth/[...nextauth]/route.ts:

Step 6: Protect Routes with Middleware

Create middleware.ts:

Step 7: Create a Login Page

Create app/login/page.tsx:

Step 8: Protect API Routes

Create app/api/protected/route.ts:

Step 9: Test Like a Pro

  1. Visit /login > Click Google login.

  2. Check MongoDB—your user should be there!

  3. Visit /dashboard (protected) or /api/protected (API route).

  4. Log out by visiting /api/auth/signout.

Troubleshooting Tips

  • 404 on Login? Double-check your NextAuth route path.

  • JWT not persisting? Ensure NEXTAUTH_SECRET is set.

  • Google login fails? Check redirect URIs in Google Cloud.