Next.js  

How to Implement Google OAuth Login in Next.js

Introduction

Adding Google login to your Next.js application makes it easier for users to sign in without creating a new password. It also improves security and user experience. With modern Next.js features and libraries like NextAuth or Google Identity Services, setting up Google OAuth is simple and efficient.

This article explains how Google OAuth works, how to create credentials in Google Cloud, how to configure the Next.js backend, and how to build a login button on the frontend. Everything is written in simple, natural language, making it easy to follow, even if you are new to authentication.

What is Google OAuth Login?

Google OAuth allows users to log in using their Google account. Instead of storing passwords yourself, Google verifies the user's identity and sends your app the required information.

Benefits:

  • No need to build your own login system

  • More secure than manual login forms

  • Faster login experience

  • Works across devices and platforms

In Next.js, Google OAuth is commonly implemented using NextAuth.js, which handles the entire authentication process.

Step 1: Create Google OAuth Credentials

To get started, you must create a new OAuth project in Google Cloud.

Steps:

  1. Go to the Google Cloud Console

  2. Open the API & Services section

  3. Click Credentials

  4. Click Create Credentials → OAuth Client ID

  5. Choose Web Application

  6. Add your redirect URL

Example Redirect URL:

http://localhost:3000/api/auth/callback/google

Google will generate:

  • Client ID

  • Client Secret

Store these values; you will need them later.

Step 2: Install NextAuth.js in Your Next.js App

Open your project and install NextAuth.

npm install next-auth

This library handles authentication, sessions, and callbacks.

Step 3: Configure NextAuth with Google Provider

Create a new file:

src/app/api/auth/[...nextauth]/route.js

Add 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
});

export { handler as GET, handler as POST };

Explanation:

  • GoogleProvider handles Google OAuth

  • Uses environment variables for security

  • Exports GET and POST for API routing

Step 4: Add Environment Variables

Create a .env.local file and add:

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

Generate a secret using:

openssl rand -base64 32

Step 5: Create a Login Button (Frontend)

NextAuth provides built-in functions to handle login.

Example Login Button:

"use client";

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

export default function LoginButton() {
  return (
    <button onClick={() => signIn("google")}>Login with Google</button>
  );
}

When the user clicks the button, Google’s OAuth popup appears.

Step 6: Display User Information

NextAuth stores user session data. You can access it using the useSession() hook.

Example:

"use client";

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

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

  if (!session) return <p>You are not logged in</p>;

  return (
    <div>
      <p>Welcome, {session.user.name}</p>
      <img src={session.user.image} alt="Profile" />
      <button onClick={() => signOut()}>Logout</button>
    </div>
  );
}

This displays:

  • User name

  • Profile image

  • Logout button

Step 7: Protect Routes Using Middleware

You can restrict access to pages using middleware.

Create file:

src/middleware.js

Example:

export { default } from "next-auth/middleware";

export const config = {
  matcher: ["/dashboard", "/profile"]
};

This requires users to be logged in before visiting protected pages.

Best Practices for Google OAuth in Next.js

1. Always Use Environment Variables

Never expose your Client ID or Secret in frontend code.

2. Use HTTPS in Production

Secure connections are required for OAuth redirects.

3. Keep Redirect URLs Consistent

Mismatched URLs cause login failures.

4. Add Error Handling

Use NextAuth callbacks to track login success or failure.

5. Avoid Using API Keys on the Client

Sensitive logic should remain server-side.

Common Errors and How to Fix Them

1. Redirect URI Mismatch

Make sure the URL in Google Cloud matches exactly.

2. Missing Environment Variables

Check for typos in .env.local.

3. Google Login Not Opening

Ensure you added:

"use client";

4. Session Not Working

Add NEXTAUTH_URL and a valid NEXTAUTH_SECRET.

Conclusion

Implementing Google OAuth login in a Next.js application is simple once you understand the flow. With the help of NextAuth.js, you can authenticate users securely without building your own login system. By following the steps in this guide—setting up Google credentials, configuring API routes, adding a login button, and protecting pages—you can create a reliable and modern authentication system for your app.

This approach not only improves user experience but also ensures your application follows secure and scalable authentication practices.