Auth with Google

Below are three separate Markdown files based on the original content. You can name them intro.md, providers.md, and auth0.md to keep your documentation organized. Each file contains only the relevant sections of the guide.

intro.md

NextAuth + Prisma + 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 authentication

  • prisma (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 connection

  • GOOGLE_CLIENT_ID and GOOGLE_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.

providers.md

Google & Other Providers

Overview

NextAuth supports a wide range of OAuth providers, including but not limited to:

  • Google

  • GitHub

  • Facebook

  • Twitter

  • Apple

  • Auth0 (covered in more detail in a separate page)

This gives you the flexibility to let users sign in with the accounts they already have, simplifying onboarding. Below, we’ll focus on Google as an example, but the process is similar for most providers.

Setting Up Google OAuth

  1. Create or select a project, then enable the OAuth consent screen and OAuth credentials.

  2. Grab your Client ID and Client Secret.

  3. Add them to your .env file as GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:

GOOGLE_CLIENT_ID="your-google-client-id.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
  1. In your NextAuth configuration (where you define authOptions), add the Google provider:

import GoogleProvider from 'next-auth/providers/google'

providers: [
  GoogleProvider({
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  }),
  // ...other providers
]

That’s it! Now your users can sign in with their Google accounts.

Other Providers

Most providers require you to: 1. Create or configure an application in their developer portal. 2. Retrieve Client ID/Secret or keys. 3. Plug these credentials into your NextAuth config—similar to Google.

For a list of officially supported providers, check the NextAuth Providers docs.

Example Usage with getSession() and useSession()

  1. Server: Checking the Session

Here’s a minimal example of how you might use getSession() (or getServerSession()) in a Server Component (e.g., app/dashboard/page.tsx). This example assumes you’ve got a helper function that returns getServerSession(authOptions):

// app/dashboard/page.tsx (Server Component) import { getSession } from '@/path/to/your/auth-helper'

export default async function DashboardPage() { const session = await getSession()

if (!session) { // If no session, you could redirect to the sign-in page or throw an error return

You need to sign in to access the dashboard.

}

return (

Welcome, {session.user?.email}!

Only signed-in users can see this content.

) }

What’s happening here? • getSession() internally calls getServerSession(authOptions) from NextAuth. • If there’s no session, we show a friendly message (or redirect). • If the user is signed in, we display their email.

  1. Client: Displaying Sign-In State

Below is a Client Component example ("use client") showing how useSession() can display a “Sign In” button or user info:

"use client" import { signIn, signOut, useSession } from "next-auth/react"

export default function AuthStatus() { const { data: session, status } = useSession()

if (status === 'loading') { // Session data is loading, you can show a spinner here return

Loading...

}

if (!session) { // No session found, show a button to sign in return ( <button onClick={() => signIn("google")}> Sign In with Google ) }

// If we got here, the user has a session return (

Welcome, {session.user?.email}

<button onClick={() => signOut()}>Sign Out) }

Highlights: • useSession() returns session data if available, or null if not. • You can pass a provider to signIn() (like "google") for immediate OAuth flows. • signOut() kills the session in the database (assuming you’re using the database strategy) and logs the user out.

Last updated