Adding Google Authentication in Next.js 14 with App Router: A Beginner-Friendly Guide
Sourav Mishra
Posted on November 11, 2024
Hey, you! Are you trying to add Google Authentication in a Next.js app but drowning in confusing tutorials? I feel you. As someone who has struggled with setting up authentication from scratch without Firebase or NextAuth “magic” plugins, I’m here to say: it doesn’t have to be a nightmare.
So, today, we’re diving into setting up Google Authentication in a Next.js 14 app. And we’ll make sure we don’t skip the basics, from setting up Next.js itself to adding Tailwind CSS for some smooth, beautiful styling. Ready? Let’s go!
Prerequisites
To make sure we’re all on the same page, you’ll need:
- Google Cloud Console account, which we’ll use to set up the OAuth credentials.
- Basic JavaScript skills (don’t worry, I’ll keep this beginner-friendly).
- Next.js 14 installed and ready to go.
Let’s get started with the setup and then bring Google Authentication in as the cherry on top. 😎
Step 1: Set Up a New Next.js 14 App
First things first, we need a Next.js project. To create one, run the following command in your terminal:
npx create-next-app@latest my-google-auth-app
During setup, when asked if you want to add Tailwind CSS, say YES! If you’re working on an app these days without Tailwind, you’re missing out on some of the cleanest, most responsive styling out there. The beauty here is that Next.js will handle most of the Tailwind setup for you, so you’re up and running with minimal pain.
Step 2: Set Up Google Cloud OAuth Credentials
For Google Authentication, we’ll need to create some credentials on Google Cloud. Follow along to get this set up (no worries, it’s simpler than it sounds).
- Go to Google Cloud Console and start a new project if you don’t have one already. (And yes, if you’re wondering why you need to jump through these hoops just to let users sign in—welcome to the world of cloud authentication. You’ll survive, I promise. Need more hand-holding through this? Just comment for a deeper dive!)
- Navigate to APIs & Services > Credentials and click on Create Credentials.
- Select OAuth 2.0 Client ID and set the application type to Web application.
- In Authorized redirect URIs, enter
http://localhost:3000/api/auth/callback
.
Google will now give you a Client ID and Client Secret. Keep these somewhere safe (or at least open in another tab). We’ll be needing them soon.
Step 3: Configure Environment Variables
With our Google credentials in hand, we’ll store these securely using environment variables. In your Next.js project, create a .env.local
file and add the following:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
NEXTAUTH_SECRET=super-secret-key
Make sure to replace your-google-client-id
and your-google-client-secret
with the actual values you got from Google Cloud. Do not commit these to GitHub unless you want the whole internet freeloading on your Google project. (Seriously, don’t.)
About the NEXTAUTH_SECRET
Alright, let’s talk about the NEXTAUTH_SECRET
. This is like the lock on your app’s front door, keeping user sessions secure. It’s a key that NextAuth uses to sign and encrypt session cookies, which means users’ login info stays private.
To create this secret key, you can run a quick command in your terminal. If you’re on macOS or Linux, here’s a one-liner to generate a strong, random key:
openssl rand -base64 32
Take the output and add it to your .env.local
file under NEXTAUTH_SECRET
. With this key in place, your authentication is way more secure, keeping things locked up nice and tight. Here’s how it’ll look in .env.local
:
NEXTAUTH_SECRET=your-super-secure-random-key
And yes, just like with the Google client ID and secret, don’t push this to GitHub—leaking it would be like handing out the keys to your app’s front door!
Step 4: Set Up NextAuth with Google Provider
To handle authentication flow from scratch, let’s use next-auth
. Install it with this command:
npm install next-auth
Then, create a new file: app/api/auth/[...nextauth]/route.js
. This will handle the API routes for our authentication.
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
secret: process.env.NEXTAUTH_SECRET,
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
With this setup, NextAuth will automatically handle all the tricky OAuth flows. You’ll be redirected to Google for login, and back to your app once authenticated.
Step 5: Create Sign-In and Sign-Out Functions
Authentication is set up, but we need some buttons to actually sign in and out! Here’s where Tailwind CSS shines, letting us add beautiful buttons with minimal CSS fuss.
In your lib
folder, create lib/auth.js
:
import { signIn, signOut } from 'next-auth/react';
export const handleSignIn = () => signIn('google');
export const handleSignOut = () => signOut();
Step 6: Add Sign-In and Sign-Out Buttons
Now, let’s add the actual UI. Go to app/page.js
and add the following code:
"use client"
import { handleSignIn, handleSignOut } from '../lib/auth';
import { useSession } from 'next-auth/react';
export default function HomePage() {
const { data: session } = useSession();
return (
<main className="flex items-center justify-center min-h-screen bg-gray-100">
{session ? (
<div>
<h2 className="text-lg font-medium text-gray-700">
Welcome, {session.user.name}!
</h2>
<button
onClick={handleSignOut}
className="px-4 py-2 mt-4 text-white bg-red-500 rounded-lg hover:bg-red-600"
>
Sign Out
</button>
</div>
) : (
<button
onClick={handleSignIn}
className="px-6 py-3 text-white bg-blue-600 rounded-lg hover:bg-blue-700"
>
Sign in with Google
</button>
)}
</main>
);
}
In this code, if the user is signed in, they see a welcome message and a Sign Out button. If not, they see a Sign in with Google button. Tailwind classes keep the styling easy and look neat.
Step 7: Test Your Google Authentication
With everything in place, let’s run your Next.js app:
npm run dev
Go to http://localhost:3000
. You should see a Sign in with Google button. Click it, and if everything’s working, you’ll see Google’s login screen. Authenticate, and Next.js will redirect you back to your app, displaying your Google account info.
You Did It! 🎉
Setting up Google Authentication in a Next.js 14 app isn’t all sunshine and rainbows, but with this guide, it’s as close as we can get! You now have a solid, from-scratch setup that you can reuse and build upon.
Authentication can seem scary, but once you break it down step-by-step (and throw in a little dark humor to keep things light), it’s totally manageable. So, next time someone complains about Google login being too complicated, you’ll know exactly what to do.
Happy coding!
Oh, and if you want a tool that’ll keep you awake and in sync during meetings, check out my latest project: Meetman. It’s a real-time meeting chat and collaboration tool that uses Google Meet captions to transcribe meetings—perfect for those times when you just might be zoning out. Go on, give it a spin!
Posted on November 11, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 11, 2024