Build a Google Login App with Next.js and NextAuth.js

Authentication is a key part of any modern web application — and Google login is one of the easiest ways to let users sign in securely.
In this tutorial, you’ll learn how to set up Google Authentication in a Next.js app using NextAuth.js, step-by-step.


Step 1: Install Node.js

Before we start, make sure Node.js is installed on your computer.

👉 Download it from https://nodejs.org

After installation, verify it by running:

node -v
npm -v

Step 2: Create a New Next.js App

Open your terminal and navigate to the folder where you want to create your app.
Then run this command:

npx create-next-app@latest google-login-app

When prompted:

? Would you like to use the recommended Next.js defaults?
> Yes, use recommended defaults - TypeScript, ESLint, Tailwind CSS, App Router, Turbopack

Press Enter.

Then go into your new project folder:

cd google-login-app

Step 3: Install NextAuth.js

NextAuth.js is a powerful authentication library for Next.js.

Install it with:

npm install next-auth

Step 4: Create Environment Variables

In your project root, create a new file named .env.local
and add the following variables:

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_random_secret

Step 5: Generate a Secure Secret Key

NextAuth uses a secret key to encrypt tokens.

If you’re on Windows, install OpenSSL (search “download OpenSSL for Windows” and install from one of the top results).

Then open the OpenSSL command prompt and run:

openssl rand -base64 32

It will generate a secret like:

RhPNs1yl+CNKr3nEKDHW4kvHflUnzW+H3HJeupdPbaA=

Paste this secret into your .env.local file:

NEXTAUTH_SECRET=RhPNs1yl+CNKr3nEKDHW4kvHflUnzW+H3HJeupdPbaA=

Step 6: Setup Google OAuth Credentials

Now go to Google Cloud Console.

  1. Click the top-left menu → APIs & Services → Credentials
  2. Click “Create Credentials” → OAuth client ID
  3. Choose Application type: Web application
  4. Name it (for example: NextAuth Google Login)
  5. Add the following URLs:

Authorized JavaScript origins:

http://localhost:3000

Authorized redirect URIs:

http://localhost:3000/api/auth/callback/google
  1. Click Create, then copy your Client ID and Client Secret.

Paste them into your .env.local file:

GOOGLE_CLIENT_ID=your_client_id_here
GOOGLE_CLIENT_SECRET=your_client_secret_here

Step 7: Configure NextAuth

Create this file:

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

Paste the following code:

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: '/signin', // optional custom page
  },
});

export { handler as GET, handler as POST };

Explanation:

  • NextAuth is the main authentication engine.
  • GoogleProvider enables Google login.
  • clientId and clientSecret come from Google Cloud.
  • secret is for internal security (encryption).
  • pages.signIn lets you add a custom login page later.

Step 8: Wrap the App with SessionProvider

In your layout file (e.g. app/layout.tsx), use:

"use client";

import { SessionProvider } from "next-auth/react";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>{children}</SessionProvider>
      </body>
    </html>
  );
}

Explanation:

  • "use client" → runs this component in the browser.
  • SessionProvider → keeps user login info available across all pages.

Step 9: Create the Home Page

Edit your app/page.tsx (or create a new one):

"use client";

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

export default function HomePage() {
  const { data: session } = useSession();

  if (session) {
    return (
      <main className="p-10 text-center">
        <h1 className="text-2xl font-bold mb-4">
          Welcome, {session.user?.name}! 👋
        </h1>
        <img
          src={session.user?.image!}
          alt="User Avatar"
          className="w-20 h-20 rounded-full mx-auto mb-4"
        />
        <button
          onClick={() => signOut()}
          className="px-4 py-2 bg-red-500 text-white rounded-lg"
        >
          Sign Out
        </button>
      </main>
    );
  }

  return (
    <main className="p-10 text-center">
      <h1 className="text-2xl font-bold mb-6">Next.js + Google Login 🔐</h1>
      <button
        onClick={() => signIn("google")}
        className="px-4 py-2 bg-blue-600 text-white rounded-lg"
      >
        Sign in with Google
      </button>
    </main>
  );
}

Explanation:

  • useSession() → checks if the user is logged in.
  • If logged in → show welcome message, image, and Sign Out button.
  • If not logged in → show “Sign in with Google” button.
  • signIn("google") triggers the Google login popup.
  • signOut() logs out the user.

Step 10: Run the App

Start your development server:

npm run dev

Then open http://localhost:3000

Try clicking “Sign in with Google”, choose your account — and boom
You’ll see your name, photo, and sign-out button!


Conclusion

You’ve just built a Google Login System in Next.js using NextAuth.js!

✅ Secure OAuth login
✅ Environment variable protection
✅ Session management
✅ Simple UI with TailwindCSS


Summary

FeatureDescription
NextAuthHandles authentication logic
GoogleProviderEnables Google login
.env.localStores sensitive keys securely
SessionProviderMakes login info available everywhere
useSession()Checks login status
signIn() / signOut()Handles login/logout actions

✨ That’s it! You now have a working Next.js + Google Authentication app.
You can easily extend this with custom dashboards, user profiles, or protected routes.