Simplifying OAuth Using NextAuth in NextJS


As developers, we often face challenges when integrating OAuth. With various providers like Google, Facebook, and GitHub, each having its own set of methods and requirements, handling OAuth can become overwhelming. Thankfully, NextAuth.js provides a streamlined way to manage authentication in Next.js, making OAuth integration easier and quicker.
In this guide, we’ll focus on how to integrate Google OAuth with NextAuth.js in a few simple steps.
Step 1: Install NextAuth
Before integrating Google OAuth, let’s first install the NextAuth library.
npm install next-auth
This will install the required files to make the OAuth Work
Step 2: Set Up a Google OAuth Client
Coming to the bit complex task
To use Google as an OAuth provider, you’ll need a Client ID and Client Secret. Here’s how you can get them:
Go to the Google Developer Console.
Create a new project (or select an existing one).
Navigate to API & Services → Credentials → Create Credentials → OAuth 2.0 Client IDs.
Fill in the required details, including the Authorized redirect URIs:
For development, it’s usually:http://localhost:3000/api/auth/callback/google
Google will now provide you with a Client ID and Client Secret.
Step 3: Configure NextAuth.js
Create an API route in your Next.js app to handle authentication using Google. In the root of your Next.js project, navigate to pages/api/auth/[...nextauth].js
and add the following snippets:
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,
}),
],
})
Why and what is […nextAuth].js You asked? lets understand Dynamic Routing in NextJS quickly
In Next.js, the pages/api/auth/[...nextauth].js
file is used to set up a dynamic API route that handles all authentication logic. Here’s why this file and structure are important:
1. Dynamic Routes in Next.js
The [...]
syntax in Next.js is a way to create catch-all routes, meaning that any request with a path that starts with /api/auth/
(like /api/auth/signin
, /api/auth/callback
, etc.) will be handled by this file.
For example:
/api/auth/signin
will handle the sign-in process./api/auth/callback/google
will process the OAuth callback from Google./api/auth/signout
will handle the sign-out process.
This catch-all structure makes it easier to manage multiple actions in one place rather than creating separate API routes for each functionality.
2. Why We Use pages/api/auth/[...nextauth].js
In a Next.js application, API routes allow us to create server-side logic. NextAuth.js needs a backend server to manage things like:
OAuth redirection (sending the user to Google for sign-in)
Handling OAuth responses (processing the information Google sends back)
Session management (managing user sessions after login)
By setting up the pages/api/auth/[...nextauth].js
file, you are effectively providing NextAuth a single API endpoint to handle all authentication tasks. The [...nextauth]
part ensures that any sub-route (like /callback
or /signin
) is also handled by this API route.
3. Why This Centralized API Route Is Useful
Simplifies Code: Instead of manually creating API routes for signing in, signing out, and handling callbacks, NextAuth handles all of that through this one centralized route.
Flexible: It works with multiple providers (like Google, GitHub, etc.) and multiple authentication methods (OAuth, credentials-based, etc.).
Automatic Routing: NextAuth automatically handles different stages of authentication, from redirection to callback processing, without needing extra configuration.
Step 4: Set Up Environment Variables
For security, it’s good practice to store sensitive credentials like your Client ID and Client Secret in environment variables. In your .env.local
file, add the following:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
Make sure to restart your development server after updating the .env.local
file.
Step 5: Add Sign-In and Sign-Out Buttons
To allow users to sign in with Google, you can add the following snippets to any component or page in your app:
"use client"; // This tells Next.js this component must be client-side
import { signIn, signOut, useSession } from "next-auth/react";
export const Appbar = () => {
const session = useSession();
return (
<div className="flex justify-between">
<div>My Blogs</div>
<div>
{session.data?.user ? (
<button className="m-2 p-2 bg-red-300" onClick={() => signOut()}>
Sign Out
</button>
) : (
<button className="m-2 p-2 bg-blue-300" onClick={() => signIn()}>
Sign In
</button>
)}
</div>
</div>
);
};
useSession
: A hook that gives you access to the current user's session data and authentication status. It helps you determine if a user is logged in or not and provides their session details.
Here’s a detailed explanation:
The useSession
hook returns an object with two main properties:
data (session): This contains the user’s session data if they are authenticated.
status: This is a string that indicates the current state of the session, which can be
"loading"
,"authenticated"
, or"unauthenticated"
.
data: session
This is the actual session object, which holds information about the user when they are authenticated. If a user is logged in, this object will typically contain:
user.name
: The name of the user.user.email
: The user's email address.user.image
: The user's profile image.Additional session info: Depending on the provider, you might also have access to things like OAuth token
status
This tells you the current status of the session:
"loading"
: When NextAuth is determining whether the user is authenticated or not (usually right after the page loads)."authenticated"
: If the user is successfully logged in."unauthenticated"
: If the user is not logged in or has logged out.
You can use status
to conditionally render UI elements based on whether the session data is still loading, the user is authenticated, or unauthenticated.
signIn
: A function to trigger the sign-in process using a specific provider (like Google). It redirects the user to the OAuth sign-in page.
signOut
: A function that signs the user out and ends their session.
In addition to setting up the API route for handling authentication, you also need to wrap your application in a provider that allows NextAuth to manage the authentication state across your app.
Step 7: Wrap Your Application in the SessionProvider
NextAuth uses a React Context to manage and provide the authentication state (session) to all components in your app. To access this session data, you need to wrap your entire application with SessionProvider
in your custom _app.js
file.
Why do we need the SessionProvider
?
The
SessionProvider
ensures that the session data (like whether a user is authenticated, their name, email, etc.) is available to every part of your app.It also handles client-side session management and automatically keeps the session updated as users log in or log out.
Where do we add it?
You’ll add the SessionProvider
in your _app.js
file, which is the entry point for all your pages and components in Next.js.
<html lang="en">
<SessionProvider>
<body className={inter.className}>{children}</body>
</SessionProvider>
</html>
Wrapping It Up
And there you have it — Google OAuth integration in Next.js made simple, thanks to NextAuth.js! No more sweating over complex OAuth flows or pulling your hair out trying to juggle multiple authentication strategies. You’re now a certified OAuth ninja!
So go ahead, take a deep breath, pat yourself on the back, and know that you’ve just made the world of authentication a little bit less scary. Who knows? Maybe your next big challenge will be integrating all the OAuth providers — because why stop at Google, right? 😉
Remember, the only limit is your imagination — and maybe the occasional API rate limit. 😅
Happy coding, and may your tokens always be fresh!
Subscribe to my newsletter
Read articles from NonStop io Technologies directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

NonStop io Technologies
NonStop io Technologies
Product Development as an Expertise Since 2015 Founded in August 2015, we are a USA-based Bespoke Engineering Studio providing Product Development as an Expertise. With 80+ satisfied clients worldwide, we serve startups and enterprises across San Francisco, Seattle, New York, London, Pune, Bangalore, Tokyo and other prominent technology hubs.