Next.js course · Module 7: Authentication and Authorization

Connecting providers (Google, GitHub, Facebook)

15 min read ·
In this lesson6

In previous lessons, we covered the basics of authentication in Next.js applications and various authorization strategies. Now we will focus on the practical implementation of authentication with popular external providers - Google, GitHub, and Facebook. This method is extremely popular because it offers users a fast and convenient login without the need to create a new account and remember another password.

Why add external authentication providers?

Signing in with Google, GitHub, or Facebook accounts brings several important benefits for both users and us - application developers:

  1. Better user experience - faster and more convenient login process, without the need to invent and remember new login credentials
  2. Higher registration rate - fewer abandoned registrations thanks to the simplified process
  3. Greater security - providers like Google or Facebook use advanced account protection mechanisms
  4. Additional information - ability to obtain additional data about the user (with their consent), such as profile picture or contact information
  5. Multi-factor authentication - many providers already offer built-in 2FA/MFA mechanisms

So let's proceed to the practical implementation of login with these popular providers in a Next.js application.

OAuth configuration for providers

Before we start coding, we need to create appropriate OAuth applications at each provider to obtain the necessary keys.

Google OAuth

  1. Go to Google Cloud Console
  2. Create a new project or select an existing one
  3. Go to "APIs & Services" > "Credentials"
  4. Click "Create Credentials" > "OAuth client ID"
  5. Select the application type (Web application)
  6. Add a name and allowed redirect URIs:
    • http://localhost:3000/api/auth/callback/google (for the development environment)
    • https://your-domain.com/api/auth/callback/google (for production)
  7. Save the Client ID and the Client Secret

GitHub OAuth

  1. Log in to GitHub
  2. Go to Settings > Developer settings > OAuth Apps
  3. Click "New OAuth App"
  4. Fill out the form:
    • Application name: the name of your application
    • Homepage URL: e.g. http://localhost:3000
    • Authorization callback URL: http://localhost:3000/api/auth/callback/github
  5. Register the application
  6. Generate a new Client Secret and save it together with the Client ID

Facebook OAuth

  1. Go to Facebook Developers
  2. Create a new application (select "For Everything Else" as the type)
  3. In the application panel, add "Facebook Login" and select "Web"
  4. In the settings, add the allowed domains:
    • localhost (for the development environment)
    • your-domain.com (for production)
  5. In the authentication settings, add the OAuth redirect:
    • http://localhost:3000/api/auth/callback/facebook
  6. Save the App ID and App Secret

Implementing authentication with NextAuth/Auth.js

Now that we have the OAuth keys, we can proceed to implement authentication in our Next.js application. We will use the NextAuth.js library (now also known as Auth.js).

1. Environment variables configuration

First, let’s add our OAuth keys to the .env.local file:

# Basic NextAuth.js configuration
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_secret_key_for_encryption

# Google Provider
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret

# GitHub Provider
GITHUB_ID=your_github_client_id
GITHUB_SECRET=your_github_client_secret

# Facebook Provider
FACEBOOK_CLIENT_ID=your_facebook_app_id
FACEBOOK_CLIENT_SECRET=your_facebook_app_secret

2. Provider configuration in NextAuth

Now let's create or update the NextAuth.js configuration file:

// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github";
import FacebookProvider from "next-auth/providers/facebook";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      // We can define what profile data we want to receive
      profile(profile) {
        return {
          id: profile.sub,
          name: profile.name,
          email: profile.email,
          image: profile.picture,
          // We can add additional fields specific to our application
          emailVerified: profile.email_verified,
        };
      },
    }),
    GitHubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
      profile(profile) {
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          email: profile.email,
          image: profile.avatar_url,
          // Additional field specific to GitHub
          username: profile.login,
        };
      },
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID!,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET!,
      profile(profile) {
        return {
          id: profile.id,
          name: profile.name,
          email: profile.email,
          image: profile.picture.data.url,
        };
      },
    }),
    // We can also add email/password authentication
    // for users who prefer traditional login
  ],
  callbacks: {
    async session({ session, user }) {
      // Add user ID to the session to easily identify the user
      if (session.user) {
        session.user.id = user.id;
      }
      return session;
    },
    async jwt({ token, user, account, profile }) {
      // If we have a user (e.g. during login), add their ID to the token
      if (user) {
        token.uid = user.id;
      }
      // We can also add information about the authentication provider
      if (account) {
        token.provider = account.provider;
      }
      return token;
    },
  },
  pages: {
    signIn: '/auth/login',  // Custom login page
    signOut: '/auth/logout', // Custom logout page
    error: '/auth/error',    // Authentication error page
  },
  session: {
    strategy: 'database',  // We use the database to store sessions
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  debug: process.env.NODE_ENV === 'development',
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

3. Creating a user interface for login

Now let's create a friendly login interface that will offer all configured authentication methods:

// app/auth/login/page.tsx
'use client';

import { signIn, useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/dashboard';
  const { status } = useSession();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  // If the user is already logged in, redirect them
  useEffect(() => {
    if (status === 'authenticated') {
      router.push(callbackUrl);
    }
  }, [status, router, callbackUrl]);

  // Email/password login handling (if configured)
  const handleEmailLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    try {
      const result = await signIn('credentials', {
        redirect: false,
        email,
        password,
      });

      if (result?.error) {
        setError('Invalid email or password');
      } else {
        router.push(callbackUrl);
      }
    } catch (error) {
      setError('An error occurred during login');
    } finally {
      setIsLoading(false);
    }
  };

  if (status === 'loading') {
    return (
      <div className="flex justify-center items-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500" />
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-lg">
      <h1 className="text-2xl font-bold mb-6 text-center">Log in to the application</h1>

      {error && (
        <div className="mb-4 p-3 bg-red-100 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="space-y-4 mb-6">
        <button
          onClick={() => signIn('google', { callbackUrl })}
          className="w-full flex items-center justify-center gap-3 p-3 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
          disabled={isLoading}
        >
          <svg viewBox="0 0 24 24" width="20" height="20">
            {/* Logo Google */}
            <path
              d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
              fill="#4285F4"
            />
            <path
              d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
              fill="#34A853"
            />
            <path
              d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
              fill="#FBBC05"
            />
            <path
              d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
              fill="#EA4335"
            />
          </svg>
          Continue with Google
        </button>

        <button
          onClick={() => signIn('github', { callbackUrl })}
          className="w-full flex items-center justify-center gap-3 p-3 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
          disabled={isLoading}
        >
          <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
            {/* Logo GitHub */}
            <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
          </svg>
          Continue with GitHub
        </button>

        <button
          onClick={() => signIn('facebook', { callbackUrl })}
          className="w-full flex items-center justify-center gap-3 p-3 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
          disabled={isLoading}
        >
          <svg viewBox="0 0 24 24" width="20" height="20" fill="#1877F2">
            {/* Logo Facebook */}
            <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
          </svg>
          Continue with Facebook
        </button>
      </div>

      {/* Optional: email/password login form */}
      <div className="relative my-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-gray-300"></div>
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="px-2 bg-white text-gray-500">
            or use email
          </span>
        </div>
      </div>

      <form onSubmit={handleEmailLogin} className="space-y-4">
        <div>
          <label htmlFor="email" className="block text-sm font-medium mb-1">
            Email
          </label>
          <input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </div>

        <div>
          <label htmlFor="password" className="block text-sm font-medium mb-1">
            Password
          </label>
          <input
            id="password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </div>

        <button
          type="submit"
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          disabled={isLoading}
        >
          {isLoading ? 'Logging in...' : 'Log in'}
        </button>
      </form>

      <div className="mt-6 text-center">
        <p className="text-sm text-gray-600">
          Don't have an account yet?{' '}
          <a href="/auth/register" className="text-blue-600 hover:underline">
            Sign up
          </a>
        </p>
      </div>
    </div>
  );
}

4. Preparing the Prisma database schema

If we are using the Prisma adapter, we must provide an appropriate database schema:

// prisma/schema.prisma
datasource db {
  provider = "postgresql" // or another database provider
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  // Additional fields specific to your application
  username      String?   @unique
  role          String?   @default("user")
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

5. Creating a SessionProvider for the entire application

For authentication to work properly across the entire application, let's add SessionProvider in the main layout:

// app/providers.tsx
'use client';

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

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

// app/layout.tsx
import { Providers } from "./providers";
import "./globals.css";

export const metadata = {
  title: "My Application",
  description: "Description of my application",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

6. Adding a navigation component with authentication state support

Now let's create a navigation component that will show different options depending on whether the user is logged in:

// components/Navigation.tsx
'use client';

import { signOut, useSession } from 'next-auth/react';
import Link from 'next/link';
import Image from 'next/image';

export default function Navigation() {
  const { data: session, status } = useSession();
  const isLoading = status === 'loading';

  return (
    <nav className="bg-white shadow-sm">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16">
          <div className="flex items-center">
            <Link href="/" className="shrink-0 flex items-center">
              <span className="text-xl font-bold">MyApp</span>
            </Link>
            <div className="hidden sm:ml-6 sm:flex sm:space-x-8">
              <Link
                href="/"
                className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
              >
                Home page
              </Link>
              <Link
                href="/features"
                className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
              >
                Features
              </Link>
              <Link
                href="/pricing"
                className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
              >
                Pricing
              </Link>
            </div>
          </div>

          <div className="flex items-center">
            {isLoading ? (
              <div className="h-8 w-8 animate-pulse rounded-full bg-gray-200" />
            ) : session ? (
              <div className="relative ml-3">
                <div className="flex items-center space-x-4">
                  <Link
                    href="/dashboard"
                    className="text-sm font-medium text-gray-700 hover:text-gray-800"
                  >
                    Dashboard
                  </Link>

                  <div className="flex items-center space-x-2">
                    {session.user?.image ? (
                      <Image
                        className="h-8 w-8 rounded-full"
                        src={session.user.image}
                        alt={session.user.name || "Avatar"}
                        width={32}
                        height={32}
                      />
                    ) : (
                      <div className="h-8 w-8 rounded-full bg-blue-600 flex items-center justify-center text-white text-sm">
                        {session.user?.name?.charAt(0) || "U"}
                      </div>
                    )}

                    <span className="text-sm font-medium text-gray-700">
                      {session.user?.name || session.user?.email?.split('@')[0]}
                    </span>
                  </div>

                  <button
                    onClick={() => signOut({ callbackUrl: '/' })}
                    className="text-sm font-medium text-gray-700 hover:text-gray-800"
                  >
                    Log out
                  </button>
                </div>
              </div>
            ) : (
              <div className="space-x-4">
                <Link
                  href="/auth/login"
                  className="text-gray-700 hover:text-gray-900 font-medium"
                >
                  Log in
                </Link>
                <Link
                  href="/auth/register"
                  className="bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 font-medium"
                >
                  Sign up
                </Link>
              </div>
            )}
          </div>
        </div>
      </div>
    </nav>
  );
}

7. Creating a Dashboard page accessible only to logged-in users

Let's create a Dashboard page that will be accessible only to logged-in users:

// app/dashboard/page.tsx
import { getServerSession } from "next-auth/next";
import { redirect } from "next/navigation";
import { authOptions } from "../api/auth/[...nextauth]/route";

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

  if (!session) {
    redirect("/auth/login?callbackUrl=/dashboard");
  }

  return (
    <div className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
      <div className="px-4 py-6 sm:px-0">
        <h1 className="text-2xl font-bold mb-4">Dashboard</h1>

        <div className="bg-white shadow overflow-hidden sm:rounded-lg">
          <div className="px-4 py-5 sm:px-6">
            <h3 className="text-lg leading-6 font-medium text-gray-900">
              Profile information
            </h3>
            <p className="mt-1 max-w-2xl text-sm text-gray-500">
              Your account details and settings.
            </p>
          </div>
          <div className="border-t border-gray-200">
            <dl>
              <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                <dt className="text-sm font-medium text-gray-500">Full name</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                  {session.user?.name || "Not provided"}
                </dd>
              </div>
              <div className="bg-white px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                <dt className="text-sm font-medium text-gray-500">Address email</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                  {session.user?.email}
                </dd>
              </div>
              <div className="bg-gray-50 px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
                <dt className="text-sm font-medium text-gray-500">Login method</dt>
                <dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
                  {/* This field requires extending the token with provider information */}
                  External authentication provider
                </dd>
              </div>
            </dl>
          </div>
        </div>
      </div>
    </div>
  );
}

8. Creating middleware for path protection

Let's secure specific paths in our application using Next.js middleware:

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(request: NextRequest) {
  const token = await getToken({ req: request });

  const isAuthPage = request.nextUrl.pathname.startsWith('/auth');

  if (isAuthPage) {
    if (token) {
      return NextResponse.redirect(new URL('/dashboard', request.url));
    }
    return NextResponse.next();
  }

  if (!token) {
    const url = new URL('/auth/login', request.url);
    url.searchParams.set('callbackUrl', request.nextUrl.pathname);
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}

// Specify paths for which the middleware should apply
export const config = {
  matcher: [
    '/dashboard/:path*',
    '/profile/:path*',
    '/settings/:path*',
    '/auth/:path*'
  ],
};

Advanced configuration

Modifying user profile data

We can modify profile data from external providers before saving them to our database:

GoogleProvider({
  clientId: process.env.GOOGLE_CLIENT_ID!,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
  profile(profile) {
    // Transforming profile data
    return {
      id: profile.sub,
      name: profile.name,
      email: profile.email,
      image: profile.picture,
      // Additional fields specific to the application
      role: profile.email.endsWith('@yourcompany.com') ? 'admin' : 'user',
      emailVerified: profile.email_verified ? new Date() : null,
    };
  },
});

Linking accounts from different providers

NextAuth.js automatically handles linking accounts from different providers if they use the same email address. If we want to customize this, we can modify the function linkAccount in the callbacks:

callbacks: {
  // ...other callbacks
  async linkAccount({ user, account, profile }) {
    // Here we can perform custom account linking logic
    console.log(`Linking account: ${account.provider} for user ${user.id}`);
    return true;
  },
}

Adding custom logic to the authentication process

We can add additional steps in the authentication process using the callback signIn:

callbacks: {
  // ...other callbacks
  async signIn({ user, account, profile, email, credentials }) {
    // Check if the user can log in
    // For example: check if the email is in the company domain
    const allowedDomains = ['yourcompany.com', 'partner.com'];
    const emailDomain = user.email?.split('@')[1];

    if (emailDomain && !allowedDomains.includes(emailDomain)) {
      return false; // Deny access
    }

    // We can also update user data on each login
    if (user.id) {
      await prisma.user.update({
        where: { id: user.id },
        data: { lastLogin: new Date() }
      });
    }

    return true; // Allow access
  },
}

Error handling authentication

Let's create a custom authentication error page:

// app/auth/error/page.tsx
'use client';

import { useSearchParams } from "next/navigation";
import Link from "next/link";

export default function AuthErrorPage() {
  const searchParams = useSearchParams();
  const error = searchParams.get('error');

  let errorMessage = "An error occurred during authentication attempt.";
  let errorDescription = "Please try again or contact administration.";

  // Map error codes to user-friendly messages
  switch (error) {
    case "Configuration":
      errorMessage = "A server configuration error occurred.";
      errorDescription = "Contact the system administrator.";
      break;
    case "AccessDenied":
      errorMessage = "Access denied.";
      errorDescription = "You do not have sufficient permissions to sign in.";
      break;
    case "Verification":
      errorMessage = "The verification link has expired or is invalid.";
      errorDescription = "Try sending the verification link again.";
      break;
    case "OAuthSignin":
    case "OAuthCallback":
    case "OAuthCreateAccount":
    case "EmailCreateAccount":
    case "Callback":
      errorMessage = "An error occurred during communication with the authentication provider.";
      errorDescription = "Try again in a moment or choose a different login method.";
      break;
    case "OAuthAccountNotLinked":
      errorMessage = "An account with this email address already exists.";
      errorDescription = "Log in using the method you used previously.";
      break;
    case "EmailSignin":
      errorMessage = "Unable to send email with login link.";
      errorDescription = "Check that the provided email address is correct.";
      break;
    case "CredentialsSignin":
      errorMessage = "Invalid login credentials.";
      errorDescription = "Check that the provided email and password are correct.";
      break;
    case "SessionRequired":
      errorMessage = "Login required.";
      errorDescription = "Log in, to access this page.";
      break;
    default:
      // Default message already set
      break;
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            {errorMessage}
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            {errorDescription}
          </p>
        </div>
        <div className="flex flex-col items-center space-y-4">
          <Link
            href="/auth/login"
            className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
          >
            Back to login page
          </Link>
          <Link
            href="/"
            className="text-sm text-blue-600 hover:text-blue-500"
          >
            Back to home page
          </Link>
        </div>
      </div>
    </div>
  );
}

Summary

In this module, we discussed in detail how to implement authentication with popular external providers (Google, GitHub, Facebook) in a Next.js application. We learned:

  1. The application registration process at OAuth providers and obtaining keys
  2. Configuration of NextAuth.js / Auth.js with different providers
  3. Creating a user interface for login and registration
  4. Securing routes using middleware
  5. Customizing the authentication process to our needs
  6. Error handling authentication

Thanks to this implementation, our Next.js application gains a professional, multi-platform authentication system that improves the user experience while strengthening the security of our application.

In the next module, we will deal in detail with user sessions and token management, which will allow us to better understand how authentication mechanisms work after user login.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Demo: OAuth Providers - Google, GitHub, Facebook
interface OAuthProvider {
  id: string;
  name: string;
  icon: string;
  color: string;
  scopes: string[];
  requiredEnvVars: string[];
}

const providers: OAuthProvider[] = [
  { id: 'google', name: 'Google', icon: 'G', color: '#4285f4', scopes: ['openid', 'profile', 'email'], requiredEnvVars: ['GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET'] },
  { id: 'github', name: 'GitHub', icon: 'GH', color: '#333', scopes: ['read:user', 'user:email'], requiredEnvVars: ['GITHUB_ID', 'GITHUB_SECRET'] },
  { id: 'facebook', name: 'Facebook', icon: 'FB', color: '#1877f2', scopes: ['public_profile', 'email'], requiredEnvVars: ['FACEBOOK_CLIENT_ID', 'FACEBOOK_CLIENT_SECRET'] },
];

type FlowStep = 'idle' | 'redirect' | 'callback' | 'token' | 'profile' | 'done';

function OAuthFlowDemo() {
  const [selectedProvider, setSelectedProvider] = useState<OAuthProvider | null>(null);
  const [currentStep, setCurrentStep] = useState<FlowStep>('idle');
  const [flowLog, setFlowLog] = useState<string[]>([]);

  const steps: { step: FlowStep; label: string; desc: string }[] = [
    { step: 'redirect', label: '1. Redirect', desc: 'Redirect to the provider' },
    { step: 'callback', label: '2. Callback', desc: 'Provider returns the code' },
    { step: 'token', label: '3. Token', desc: 'Exchange the code for a token' },
    { step: 'profile', label: '4. Profile', desc: 'Fetch the profile' },
    { step: 'done', label: '5. Done', desc: 'Session created' },
  ];

  const simulateFlow = async (provider: OAuthProvider) => {
    setSelectedProvider(provider);
    setFlowLog([]);
    setCurrentStep('idle');

    const addLog = (msg: string) => setFlowLog(prev => [...prev, msg]);

    await new Promise(r => setTimeout(r, 400));
    setCurrentStep('redirect');
    addLog('[Client] Clicked "Log in with ' + provider.name + '"');

    await new Promise(r => setTimeout(r, 1000));
    setCurrentStep('callback');
    addLog('[' + provider.name + '] User approved access');
    addLog('[Callback] GET /api/auth/callback?code=abc123');

    await new Promise(r => setTimeout(r, 800));
    setCurrentStep('token');
    addLog('[Server] Exchanging authorization code for access_token');

    await new Promise(r => setTimeout(r, 800));
    setCurrentStep('profile');
    addLog('[Server] Fetching user profile from ' + provider.name);

    await new Promise(r => setTimeout(r, 600));
    setCurrentStep('done');
    addLog('[Server] Session created, user logged in');
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>OAuth Providers Flow</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Visualization of the OAuth login process</p>

      <div style={{ display: 'flex', gap: '16px', marginBottom: '32px', flexWrap: 'wrap' }}>
        {providers.map(p => (
          <button key={p.id} onClick={() => simulateFlow(p)} style={{
            padding: '16px 24px', borderRadius: '12px', border: '2px solid',
            borderColor: selectedProvider?.id === p.id ? p.color : '#333',
            background: selectedProvider?.id === p.id ? p.color + '20' : '#1a1a2e',
            color: '#fff', cursor: 'pointer', fontSize: '16px',
          }}>
            <div style={{ fontSize: '20px', fontWeight: 'bold' }}>{p.icon}</div>
            <div style={{ marginTop: '4px' }}>{p.name}</div>
          </button>
        ))}
      </div>

      {selectedProvider && (
        <>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '24px', flexWrap: 'wrap' }}>
            {steps.map(s => {
              const stepIdx = steps.findIndex(x => x.step === currentStep);
              const thisIdx = steps.findIndex(x => x.step === s.step);
              return (
                <div key={s.step} style={{
                  padding: '8px 16px', borderRadius: '8px', fontSize: '13px',
                  background: currentStep === s.step ? '#64ffda20' : thisIdx < stepIdx ? '#1a3a2e' : '#1a1a2e',
                  border: currentStep === s.step ? '1px solid #64ffda' : '1px solid #333',
                  color: currentStep === s.step ? '#64ffda' : '#8892b0',
                }}>
                  <strong>{s.label}</strong>
                  <div style={{ fontSize: '11px', marginTop: '2px' }}>{s.desc}</div>
                </div>
              );
            })}
          </div>

          <div style={{ background: '#1a1a2e', borderRadius: '8px', padding: '16px', border: '1px solid #333', maxHeight: '250px', overflow: 'auto' }}>
            <h3 style={{ color: '#64ffda', margin: '0 0 12px 0', fontSize: '14px' }}>Flow Log:</h3>
            {flowLog.map((log, i) => (
              <div key={i} style={{ fontSize: '13px', padding: '4px 0', borderBottom: '1px solid #222', color: log.includes('[Server]') ? '#f59e0b' : log.includes('[Client]') ? '#64ffda' : '#8892b0' }}>
                {log}
              </div>
            ))}
          </div>

          <div style={{ marginTop: '16px', background: '#1a1a2e', padding: '12px', borderRadius: '8px', border: '1px solid #333' }}>
            <strong style={{ color: '#f59e0b' }}>Required .env variables:</strong>
            <div style={{ marginTop: '8px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
              {selectedProvider.requiredEnvVars.map(v => (
                <code key={v} style={{ background: '#0f0f23', padding: '4px 8px', borderRadius: '4px', fontSize: '13px', color: '#64ffda' }}>{v}</code>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

export default OAuthFlowDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Session-based authentication stores session data:

  2. 2. Token-based authentication uses:

Hands-on tasks in the game

  • Code editor

    Create the [...nextauth].ts file with a basic providers, session, and callbacks configuration

  • Vertical ordering

    Arrange the elements in the correct order: import 'client-only' → export function →

  • Click in order

    Arrange the getServerSession import syntax from NextAuth

  • Code editor

    Configure the Google provider in NextAuth with the appropriate client ID, secret, and scopes

  1. QuestionSession-based authentication stores session data:
  2. QuestionToken-based authentication uses:
  3. Coding taskPractice: Create [...nextauth].ts with basic configuration
  4. Put in orderOrder: import 'client-only' → export function → ...
  5. Click in orderOrder: import → { → getServerSession
  6. Coding taskPractice: Configure Google provider in NextAuth with

Useful articles