Next.js Social Login
Social login (also called social sign-in or social authentication) allows users to authenticate using their existing accounts from platforms like Google, GitHub, Facebook, or Twitter. This provides a streamlined user experience by eliminating the need to create and remember another username and password.
In this tutorial, we'll learn how to implement social login in a Next.js application using NextAuth.js, a complete authentication solution for Next.js apps.
Why Use Social Login?
Before we dive into the implementation, let's understand the benefits:
- Improved User Experience: Users don't need to fill out registration forms or remember additional passwords
- Higher Conversion Rates: Reduces friction during signup, potentially leading to more registered users
- Enhanced Security: Leverages security measures already implemented by major platforms
- Access to User Data: With user permission, you can access profile data from social providers
Prerequisites
To follow along with this tutorial, you'll need:
- Basic knowledge of Next.js and React
- Node.js installed on your system
- A Next.js project set up (version 13+ recommended)
Setting Up NextAuth.js
NextAuth.js is the most popular authentication library for Next.js. Let's start by installing it:
npm install next-auth
# or
yarn add next-auth
Creating API Route for Authentication
For Next.js 13+ with App Router:
- Create a new file at
app/api/auth/[...nextauth]/route.js
:
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import GitHubProvider from 'next-auth/providers/github';
const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
// Additional configuration options
pages: {
signIn: '/auth/signin', // Custom sign-in page (optional)
},
callbacks: {
async session({ session, token }) {
// Send properties to the client
session.user.id = token.sub;
return session;
},
},
});
export { handler as GET, handler as POST };
For Next.js with Pages Router:
// pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import GitHubProvider from 'next-auth/providers/github';
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
GitHubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
// Additional configuration options
});
Environment Variables
Create a .env.local
file in the root of your project to store your credentials:
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_nextauth_secret
# 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
The NEXTAUTH_SECRET
is used to encrypt cookies and tokens. You can generate a secure random string using:
openssl rand -base64 32
Obtaining OAuth Credentials
To implement social login, you need to register your application with the providers you want to support. Let's go through the process for the most common ones:
Google OAuth Setup
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Navigate to "APIs & Services" > "Credentials"
- Click "Create Credentials" and select "OAuth client ID"
- Configure the consent screen if prompted
- Select "Web application" as the application type
- Add your application's domain to "Authorized JavaScript origins"
- Add your redirect URL (typically
http://localhost:3000/api/auth/callback/google
for development) - Copy the Client ID and Client Secret to your environment variables
GitHub OAuth Setup
- Go to GitHub Developer Settings
- Click "New OAuth App"
- Fill in the application name and homepage URL
- Set the authorization callback URL to
http://localhost:3000/api/auth/callback/github
- Click "Register application"
- Copy the Client ID and generate a Client Secret
- Add them to your environment variables
Creating a Sign-In Component
Now let's create a component to handle user authentication:
// components/SignInButtons.jsx
"use client"; // If using the App Router
import { signIn, signOut, useSession } from 'next-auth/react';
export default function SignInButtons() {
const { data: session } = useSession();
if (session && session.user) {
return (
<div className="flex flex-col items-center gap-4">
<p>Signed in as {session.user.email}</p>
<img
src={session.user.image}
alt={session.user.name}
className="rounded-full w-12 h-12"
/>
<button
className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
onClick={() => signOut()}
>
Sign out
</button>
</div>
);
}
return (
<div className="flex flex-col gap-4">
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded flex items-center gap-2"
onClick={() => signIn('google')}
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
{/* Google icon SVG */}
<path fill="#FFFFFF" d="M12.545,10.239v3.821h5.445c-0.712,2.315-2.647,3.972-5.445,3.972c-3.332,0-6.033-2.701-6.033-6.032 s2.701-6.032,6.033-6.032c1.498,0,2.866,0.549,3.921,1.453l2.814-2.814C17.503,2.988,15.139,2,12.545,2 C7.021,2,2.543,6.477,2.543,12s4.478,10,10.002,10c8.396,0,10.249-7.85,9.426-11.748L12.545,10.239z"/>
</svg>
Sign in with Google
</button>
<button
className="bg-gray-800 hover:bg-gray-900 text-white font-bold py-2 px-4 rounded flex items-center gap-2"
onClick={() => signIn('github')}
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
{/* GitHub icon SVG */}
<path fill="#FFFFFF" d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
</svg>
Sign in with GitHub
</button>
</div>
);
}