How to Add Google Authentication in a Next.js App Using NextAuth.js 🚀
Feb 18, 2025
|
7
min read
To add Google authentication to your Next.js project, you can use NextAuth.js, which simplifies OAuth integration. Here's how you can do it:
Steps to Add Google Authentication in Next.js
1. Install Dependencies
Run the following command in your Next.js project:
2. Set Up Google OAuth Credentials
Go to the Google Cloud Console
Navigate to APIs & Services → Credentials
Click Create Credentials → OAuth 2.0 Client IDs
Set up the following:
Application type: Web application
Authorized JavaScript origins:
http://localhost:3000(or your production URL)Authorized Redirect URIs:
http://localhost:3000/api/auth/callback/google
Click Create, then copy the Client ID and Client Secret.
3. Configure NextAuth.js
Create a file:
📌 pages/api/auth/[...nextauth].js
4. Add Environment Variables
Create a .env.local file in your project root and add:
5. Implement Login Button
You can now use NextAuth in your components to handle login/logout.
📌 Example: components/LoginButton.js
6. Wrap App with Session Provider
📌 If using Next.js App Router (app/layout.js or app/layout.tsx):
📌 If using Pages Router (_app.js or _app.tsx):
7. Test Authentication
Run your app:
Go to http://localhost:3000, click the login button, and authenticate with Google.
Bonus: Protect Pages (Middleware)
To restrict access to certain pages: 📌 middleware.js
This ensures only authenticated users can access protected pages.
Conclusion
With this setup, your Next.js app now supports Google authentication with NextAuth.js. You can further extend it with custom callbacks, user roles, and database storage.
