Technology

Technology

How to Add Google Authentication in a Next.js App Using NextAuth.js 🚀

Feb 18, 2025

|

7

min read

To add Google authentication to your Next.js project, you can use NextAuth.js, which simplifies OAuth integration. Here's how you can do it:

Steps to Add Google Authentication in Next.js

1. Install Dependencies

Run the following command in your Next.js project:

npm

2. Set Up Google OAuth Credentials

  1. Go to the Google Cloud Console

  2. Navigate to APIs & Services → Credentials

  3. Click Create Credentials → OAuth 2.0 Client IDs

  4. Set up the following:

    • Application type: Web application

    • Authorized JavaScript origins: http://localhost:3000 (or your production URL)

    • Authorized Redirect URIs: http://localhost:3000/api/auth/callback/google

  5. Click Create, then copy the Client ID and Client Secret.

3. Configure NextAuth.js

Create a file:
📌 pages/api/auth/[...nextauth].js

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET, // Used for session encryption
  callbacks: {
    async session({ session, token }) {
      session.user.id = token.sub; // Attach user ID to session
      return session;
    },
  },
});

4. Add Environment Variables

Create a .env.local file in your project root and add:


5. Implement Login Button

You can now use NextAuth in your components to handle login/logout.

📌 Example: components/LoginButton.js

"use client"; // If using App Router (Next.js 13+)

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

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

  return (
    <div>
      {session ? (
        <>
          <p>Welcome, {session.user.name}</p>
          <button onClick={() => signOut()}>Sign Out</button>
        </>
      ) : (
        <button onClick={() => signIn("google")}>Sign in with Google</button>
      )}
    </div>
  );
}

6. Wrap App with Session Provider

📌 If using Next.js App Router (app/layout.js or app/layout.tsx):

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

export default function RootLayout({ children }) {
  return <SessionProvider>{children}</SessionProvider>;
}

📌 If using Pages Router (_app.js or _app.tsx):

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

function MyApp({ Component, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

export default MyApp;

7. Test Authentication

Run your app:

npm

Go to http://localhost:3000, click the login button, and authenticate with Google.

Bonus: Protect Pages (Middleware)

To restrict access to certain pages: 📌 middleware.js

import { withAuth } from "next-auth/middleware";

export default withAuth({
  pages: {
    signIn: "/auth/login", // Custom login page
  },
});

This ensures only authenticated users can access protected pages.

Conclusion

With this setup, your Next.js app now supports Google authentication with NextAuth.js. You can further extend it with custom callbacks, user roles, and database storage.

Subscribe To Out Newsletter

Subscribe To Out Newsletter

Get the latest tech insights delivered directly to your inbox!

Subscribe To Out Newsletter

Share It On:

© 2024 Digital Frontier Digest.

Designed & Developed By Digital Frontier Digest

© 2024 Digital Frontier Digest.

Designed & Developed By Digital Frontier Digest

© 2024 Digital Frontier Digest.

Designed & Developed By Digital Frontier Digest