OAuth Authentication Introduction - Implementing Google Login with Next.js

intermediate | 45 min read | 2025.12.01

What You’ll Learn in This Tutorial

✓ How OAuth works
✓ NextAuth.js setup
✓ Google provider configuration
✓ Session management
✓ Protected routes

Step 1: Setup

npx create-next-app@latest oauth-demo --typescript
cd oauth-demo
npm install next-auth

Step 2: Getting Google Credentials

1. Google Cloud Console (console.cloud.google.com)
2. Create a new project
3. APIs & Services → Credentials
4. Create OAuth 2.0 Client ID
5. Authorized redirect URI: http://localhost:3000/api/auth/callback/google

Step 3: NextAuth Configuration

// app/api/auth/[...nextauth]/route.ts
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!,
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      session.user.id = token.sub;
      return session;
    },
  },
});

export { handler as GET, handler as POST };

Step 4: Environment Variables

# .env.local
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-key

Step 5: SessionProvider

// app/providers.tsx
'use client';
import { SessionProvider } from 'next-auth/react';

export function Providers({ children }: { children: React.ReactNode }) {
  return <SessionProvider>{children}</SessionProvider>;
}

// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

Step 6: Login Button

// components/AuthButton.tsx
'use client';
import { signIn, signOut, useSession } from 'next-auth/react';

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

  if (session) {
    return (
      <div>
        <p>Welcome, {session.user?.name}</p>
        <button onClick={() => signOut()}>Sign out</button>
      </div>
    );
  }

  return <button onClick={() => signIn('google')}>Sign in with Google</button>;
}

Step 7: Protected Page

// app/dashboard/page.tsx
import { getServerSession } from 'next-auth';
import { redirect } from 'next/navigation';

export default async function Dashboard() {
  const session = await getServerSession();

  if (!session) {
    redirect('/api/auth/signin');
  }

  return <h1>Welcome, {session.user?.name}</h1>;
}

Summary

NextAuth.js makes it easy to implement OAuth authentication. In addition to Google, it supports many providers including GitHub and Twitter.

← Back to list