OAuth 2.0 Login (Google) in Next.js

Modern web applications rarely require users to create custom username and password credentials from scratch. Instead, social authentication via providers like Google, GitHub, and Apple provides a frictionless user experience while outsourcing credential security to identity providers.

In the Next.js ecosystem, NextAuth.js (rebranded as Auth.js) is the definitive standard for handling authentication. This comprehensive tutorial walks through setting up Google OAuth 2.0 authentication in a Next.js App Router project, managing server and client sessions, and protecting private routes.

1. Installation and Dependencies

Initialize or open your Next.js project and install next-auth (v4 or Auth.js for App Router).

C
# Terminal installation command
npm install next-auth dotenv

2. Configuring Google Cloud OAuth Credentials

Before writing code, you must obtain a Google Client ID and Client Secret from the Google Cloud Console:

  • Navigate to the Google Cloud Console and create a new project.
  • Go to APIs & Services > OAuth consent screen, configure external user type, and save app details.
  • Go to Credentials > Create Credentials > OAuth client ID.
  • Select Web application and add your Authorized redirect URI: http://localhost:3000/api/auth/callback/google.
  • Copy your generated Client ID and Client Secret.
C
# .env.local configuration
GOOGLE_CLIENT_ID="your_google_client_id_here"
GOOGLE_CLIENT_SECRET="your_google_client_secret_here"
NEXTAUTH_SECRET="your_random_generated_secret_string"
NEXTAUTH_URL="http://localhost:3000"

3. Setting Up NextAuth Route Handler (App Router)

In Next.js App Router, configure your authentication endpoint inside app/api/auth/[...nextauth]/route.js.

C
// app/api/auth/[...nextauth]/route.js
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

const handler = NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        }),
    ],
    secret: process.env.NEXTAUTH_SECRET,
    pages: {
        signIn: '/login',
    },
});

export { handler as GET, handler as POST };

4. Implementing Login and Session State in UI Components

Wrap your application in a SessionProvider or use NextAuth helper functions (signIn, signOut, useSession) to manage authentication states on client and server components.

C
// components/AuthButton.jsx
'use client';

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

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

    if (status === "loading") {
        return <p>Loading authentication status...</p>;
    }

    if (session) {
        return (
            <div className="flex flex-col items-center gap-2">
                <p>Welcome, <span className="font-bold">{session.user.name}</span></p>
                <img src={session.user.image} alt="Avatar" className="w-10 h-10 rounded-full" />
                <button onClick={() => signOut()} className="bg-red-500 text-white px-4 py-2 rounded">
                    Sign Out
                </button>
            </div>
        );
    }

    return (
        <button onClick={() => signIn('google')} className="bg-blue-600 text-white px-4 py-2 rounded">
            Sign in with Google
        </button>
    );
}

Conclusion

Integrating Google OAuth 2.0 into Next.js using NextAuth.js simplifies secure user authentication. By combining API route handlers with client-side session hooks, developers can build robust, production-ready login workflows quickly.