Authentication
Authentication with NextAuth, Prisma, and the New App Router
Introduction
This project configures NextAuth.js to store user sessions via Prisma in a relational database (because sometimes you need a safe place for all those cookies and tokens). The new Next.js App Router is utilized for a cleaner approach to rendering on both the client and the server. If you like the old Pages Router, that’s fine too, but the future is here and it’s, well, new.
Why Prisma for Sessions?
Prisma takes the guesswork out of database interactions. Instead of cobbling together SQL queries in every corner of your code, you define a schema that NextAuth can hook into. This way, session data (and user data) is stored reliably in your own database, rather than ephemeral memory or a single giant cookie that might vanish if a strong breeze hits your browser.
The General Setup
You’ll need to install the usual suspects:
next-auth
for authenticationprisma
(and the Prisma client) for database interactions@auth/prisma-adapter
(the official NextAuth-Prisma adapter)
Once those are in place, you configure NextAuth to point at Prisma as its session storage mechanism. That means no more fuss with JWT-based session strategies—database-backed sessions keep you covered.
Environment Variables
Keep your credentials private by placing them in a .env
file or your hosting provider’s environment settings:
DATABASE_URL
for your Prisma connectionGOOGLE_CLIENT_ID
andGOOGLE_CLIENT_SECRET
for Google OAuth (if you’re using it)NEXTAUTH_SECRET
for production security
Pro Tip: Don’t push these secrets to a public repo—unless you really want random people logging in as you.
The New App Router
Next.js introduced a fancy new approach to routing and rendering. Rather than relying on the standard pages
directory for your API endpoints, you can define server-side, client-side, and shared components in the app
directory.
Server Components / Actions: Perfect for querying or mutating user data (like checking who is logged in) without shipping all that logic to the client.
Client Components: Great when you need immediate user interactions, such as a “Sign In” or “Sign Out” button that triggers NextAuth’s client methods.
Getting the Session
To check if someone is logged in on the server, you can call a helper method (e.g., getSession()
) that wraps NextAuth’s getServerSession
. No need to bring all your NextAuth config into every single route—just point to an authOptions
object that sets up your providers, your Prisma adapter, and your session strategy.
On the client side, import the NextAuth React hook useSession()
to see who’s there. If useSession()
returns null
, that means no one’s logged in; if it returns a user, you know exactly who’s behind that keyboard.
Last updated