Learn how to implement a Next.js login page with Social Login (OAuth), in this tutorial.
Vincent
Created: December 17, 2024
Updated: December 17, 2024
Our mission is to make the Internet a safer place, and the new login standard passkeys provides a superior solution to achieve that. That's why we want to help you understand passkeys and its characteristics better.
Next.js is a powerful framework that allows developers to build fast and user-friendly web applications. One of the most critical aspects of any web application is user authentication.
In this guide, we'll walk you through the process of implementing a login page in Next.js, with Social Login (OAuth).
If you want to see the complete code and check out other authenciation methods (OTP, passkeys, authenticator app), use our Next.js login page repository on GitHub. There you will find information regarding:
Recent Articles
♟️
Enterprise Passkeys Guide: Part 5 – Testing Passkey Implementations
♟️
Enterprise Passkeys Guide: Part 4 – Integrating Passkeys Into an Enterprise Stack
♟️
Enterprise Passkeys Guide: Part 3 – Product, Design & Strategy Development
🔑
Use Windows 11 Without Windows Hello / Microsoft Account
♟️
Australian Cyber Security Bill 2024: Impact on Authentication
Before we jump into the One-Time Password (OTP) authentication, we need to perform some general project setup steps.
Subscribe to our Passkeys Substack for the latest news, insights and strategies.
SubscribeTo follow this guide, we require some basic understanding of
Open your terminal and run the following command to create a new Next.js project:
In the installation guide steps, we select the following:
Navigate to your project directory:
To verify that your Next.js project is set up correctly, start the development server:
Open your browser and navigate to http://localhost:3000
. You should see the default Next.js welcome page.
Create a .env.local
file in the root of your project to store environment variables. Add your variables here:
Become part of our Passkeys Community for updates and support.
JoinUsing OAuth for third-party authentication is a very popular and user-friendly solution. In this section, we'll explore how to integrate Google authentication into a Next.js application using NextAuth.js.
We chose NextAuth.js for Google authentication because it's easy to integrate and offers robust security features. NextAuth.js simplifies adding Google OAuth, providing a seamless and secure login experience. It handles the complex parts of authentication, so we can focus on building our app. Plus, it's highly customizable, making it a perfect fit for our needs.
Google social login interface
The following steps covers the implementation of the Google authentication:
SignInButton
Component
5.2 Creating LogoutButton
Component
5.3 Creating ClientProvider
ComponentIn this section, we'll detail how to set up Google-based authentication (Google social login) for your Next.js project. We'll break down the specific files and structure. Let's start with an overview of the relevant directory structure and the key files involved:
Key Files and Their Roles:
.env.local
: In this file will store the environment variables which are your Google client ID GOOGLE_CLIENT_ID
and secret GOOGLE_CLIENT_SECRET
src/pages/api/auth/[...nextauth].ts
: This file sets up NextAuth.js for handling authentication. It includes configuration for Google as an authentication provider.src/components/ClientProvider.tsx
: A wrapper component that provides session management using NextAuth.js. It ensures that session data is available throughout your application.src/app/layout.tsx
: The root layout for your application, which wraps all pages with the ClientProvider to manage session state globally.src/components/SignInButton.tsx
: A component that renders a button for signing in with Google. It handles the sign-in process when clicked.src/components/LogoutButton.tsx
: A component that renders a logout button. It handles signing the user out and redirecting them appropriately.src/app/googleLogin/page.tsx
: The main page for handling Google login. It displays different content based on whether the user is signed in or not.http://localhost:3000/api/auth/callback/google
for local development.
.env.local
file and add the following environment variables:First, install the necessary dependencies:
You can install the dependencies using the following command:
In this section, we will configure NextAuth.js to handle Google authentication in our Next.js application. We will walk through the specific file used for this configuration, its location, purpose, and explain the main concepts involved. Additionally, we’ll discuss the reason behind the file naming convention [...nextauth].
Good to know: Reason for the Naming Convention [...nextauth]
The file is named [...nextauth].ts to leverage Next.js's dynamic routing feature. The square brackets [ ] denote a dynamic route segment, and the three dots ... indicate a catch-all route. This means that any API route starting with /api/auth/ (e.g., /api/auth/signin, /api/auth/signout, /api/auth/callback) will be handled by this file. This naming convention provides a flexible way to manage all authentication-related routes in a single file.
src/pages/api/auth/[...nextauth].ts
in your project directoryNextAuth
: The core module for handling authentication in Next.js.GoogleProvider
: A provider module for handling Google OAuth authentication.GoogleProvider
module. The clientId
and clientSecret
are fetched from environment variables to ensure they are not hardcoded and remain secure.session
function called during the authentication process. The session
function is called whenever a session is checked or created. It modifies the session object to include the user's name and email from the token.Here’s the complete code of the [...nextauth].ts
file:
In this section, we'll create the essential components needed for handling authentication in our Next.js application. These components include a sign-in button for Google authentication and a logout button for signing out. We'll also create a client provider to manage session state across the application.
Here are the components we'll create:
SignInButton.tsx
LogoutButton.tsx
ClientProvider.tsx
These components will be placed in the src/components
directory. Each of these components serves a specific purpose in the authentication flow.
src/components/SignInButton.tsx
signIn
function: From next-auth/react, it handles the sign-in process with Google.signIn
function with Google as the provider and includes the prompt: "select_account" parameter to ensure the account chooser appears.Here’s the complete code of the SignInButton.tsx
file:
src/components/LogoutButton.tsx
signOut
function: From next-auth/react
, it handles the sign-out process.signOut
function and redirects the user to the /googleLogin
page after signing out.Here’s the complete code of the LogoutButton.tsx
file:
src/components/ClientProvider.tsx
SessionProvider
to manage session state globally.next-auth/react
, it wraps the children components to provide session management.Here’s the complete code of the ClientProvider.tsx
file:
In this section, we'll configure the root layout of your Next.js application to ensure that session state is managed globally. This involves using the ClientProvider
component, which wraps the entire application and provides session management using NextAuth.js.
src/app/layout.tsx
ClientProvider
, enabling global session management.<ClientProvider>
: Wraps the children components with the ClientProvider
to manage session state globally. This ensures that session information is accessible across all pages and components in your application.Here’s the complete code of the layout.tsx
file:
In this section, we will focus on how to handle user sign-in and sign-out actions on the main login page. We will use the previously created SignInButton
and LogoutButton
components and ensure they are integrated seamlessly with our authentication flow.
src/app/googleLogin/page.tsx
next-auth/react
that provides session information.
useSession
hook fetches the current session data.LogoutButton
.SignInButton
.Here’s the complete code of the page.tsx
file:
By following these steps, you can test the Google authentication flow in your Next.js application. Ensure that each step works correctly:
http://localhost:3000/googleLogin
http://localhost:3000/googleLogin
. You should see the Google Sign-In button.Google social login interface
Sign in with Google
button. This action should redirect you to Google's authentication page.4. After signing in, you should be redirected back to your application. If the sign-in was successful, you should see a welcome message along with the Logout button.
By following these steps, you will have successfully set up Google authentication in your Next.js application using NextAuth.js. This setup includes creating necessary components, configuring authentication providers, and managing session states.
Event though we just looked at how to roll out OAuth authencication, which is not the safest auth method, building a secure and user-friendly authentication system is crucial to protect user data and provide a great first impression of your app. Authentication is often the first interaction a user has with your product and the first thing they will complain about if something goes wrong. Besides the detailed steps laid out above, we also have some additional best practices for Next.js authentication and login pages:
By following these practices, you'll keep your application robust against common threats and ensure a safe environment for your users. Secure authentication not only protects your users but also builds trust and credibility for your application.
In this Next.js login page guide, we explored various authentication methods to secure your Next.js applications. Here’s a recap of what we covered:
Choosing the right authentication method for your application depends on various factors, including security requirements, user convenience, and the nature of your application. Each method we covered has its strengths and can be used alone or in combination to provide a robust authentication system. Experiment with different methods, gather user feedback, and iterate on your implementation to achieve the best balance for your specific needs.
Table of Contents
Enjoyed this read?
🤝 Join our Passkeys Community
Share passkeys implementation tips and get support to free the world from passwords.
🚀 Subscribe to Substack
Get the latest news, strategies, and insights about passkeys sent straight to your inbox.
We provide UI components, SDKs and guides to help you add passkeys to your app in <1 hour
Start for free