Securing Your SaaS: Implementing Google OAuth and Protected Routes in Next.js
Karl Gusta
Instructor & Founder
Authentication is the gatekeeper of your SaaS. It is the first interaction a user has with your product, and it is also the most critical point of failure. If your login process is clunky, users will bounce. If it is insecure, your business is over before it begins.
In the modern web, users no longer want to manage a separate password for every small tool they use. They want a one-click experience. This lesson focuses on implementing a professional, secure, and frictionless authentication flow using Google OAuth and Auth.js (formerly NextAuth) within the Next.js ecosystem.
The Problem: The High Cost of Custom Authentication
Building a custom authentication system from scratch is a trap for many developers. It feels like a core skill, but in a production SaaS environment, it is often a liability.
When you build your own auth, you are responsible for:
- Password Hashing: Using secure algorithms like bcrypt or argon2.
- Session Management: Handling cookies, CSRF tokens, and session timeouts.
- Security Updates: Patching vulnerabilities as they are discovered.
- Account Recovery: Building "forgot password" flows and email verification.
This takes weeks of development time that could be spent on your actual product features. Furthermore, a single mistake in your security logic can lead to a devastating data breach.

The Shift: Leveraging Trusted Identity Providers
The modern standard for secure authentication Next.js is to offload the heavy lifting to trusted identity providers like Google, GitHub, or Apple.
By using OAuth, you shift the security burden. You don't store passwords; you store a cryptographically signed "token" that proves the user is who they say they are. This provides:
- Trust: Users trust Google to keep their credentials safe.
- Conversion: A single button click is faster than filling out a five-field form.
- Security: You get features like Multi-Factor Authentication (MFA) for free because Google handles it.
In the Zero to SaaS framework, we treat authentication as a utility, not a feature we build from scratch.
Deep Dive: The OAuth and Session Workflow
To implement a professional auth flow, we follow a specific sequence: Provider Configuration, Shared Session Context, and Route Protection.
1. Setting Up the Google Cloud Console
Before you write code, you need to register your app with Google. You will receive a GOOGLE_CLIENT_ID and a GOOGLE_CLIENT_SECRET.
You must set your "Authorized redirect URIs" correctly. For local development, this is usually http://localhost:3000/api/auth/callback/google.
2. Configuring Auth.js (NextAuth)
We use Auth.js because it is built specifically for the Next.js App Router. It handles the complicated handshake between your app and Google automatically.
typescript// app/api/auth/[...nextauth]/route.ts import NextAuth from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { MongoDBAdapter } from "@auth/mongodb-adapter"; import clientPromise from "@/lib/mongodb"; export const { handlers, auth, signIn, signOut } = NextAuth({ adapter: MongoDBAdapter(clientPromise), providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], callbacks: { async session({ session, user }) { // Add the user ID to the session object so we can use it in queries session.user.id = user.id; return session; }, }, });
By using the MongoDBAdapter, Auth.js will automatically create a document in your database the first time a user logs in. This is where your authentication layer connects to your Database and Backend layer.
3. Protecting Routes with Middleware
You don't want to check if a user is logged in on every single page manually. Instead, use Next.js Middleware to protect entire folders (like /dashboard) globally.
typescript// middleware.ts export { auth as middleware } from "@/auth"; export const config = { matcher: ["/dashboard/:path*", "/settings/:path*"], };
With this simple file, any user trying to access the dashboard without being logged in will be redirected to the login page automatically.

Key Benefits and Learning Outcomes
Implementing OAuth correctly gives your SaaS a professional edge:
- Seamless Onboarding: Users can sign up and reach your dashboard in under 10 seconds.
- Unified Identity: You can easily pull the user's name and profile picture from Google to personalize their dashboard immediately.
- Backend Security: Your API routes can verify sessions server-side, ensuring that data is only served to the rightful owner.
- Database Sync: User data is automatically persisted to MongoDB upon the first login.
Common Mistakes
Watch out for these common auth hurdles:
- Exposing Client Secrets: Never commit your
GOOGLE_CLIENT_SECRETto GitHub. Always use environment variables. - Mismatched Redirect URIs: If your redirect URI in the Google Console doesn't match your app's URL exactly, the login will fail with a "Redirect URI mismatch" error.
- Missing
NEXTAUTH_SECRET: In production, Auth.js requires aNEXTAUTH_SECRETenvironment variable to encrypt your cookies. Without it, your sessions will not persist.
Pro Tips and Best Practices
Use the useSession Hook for UI Logic:
On the client side, use the useSession hook to conditionally show navigation items. For example, show a "Login" button if the user is signed out, and a "Dashboard" link if they are signed in.
Handle the "New User" Event:
Auth.js provides an events callback. You can use the createUser event to trigger a welcome email or set up default project data for the new user in your database.
Implement "Sign Out" Everywhere: Always provide a clear way for users to log out. It’s not just a feature; it's a security requirement for users on shared computers.

How This Fits Into the Zero to SaaS Journey
Authentication is the bridge between your landing page and your product. In the Zero to SaaS 14 Day Course, we implement this immediately after the database setup.
Once you have a secure way to identify users, you can move on to the next major pillar: Stripe Payments and Billing. After all, you need to know who a user is before you can charge them for a subscription.
Real-World Example: A Portfolio Builder SaaS
Imagine a tool where users build personal portfolios.
- Login: User signs in with Google.
- Session: Your app identifies them as User 123.
- Database: Your app fetches all "Portfolio" documents from MongoDB where
ownerId === "123". - UI: The user sees their specific projects and can edit them.
Without secure authentication, User 456 could potentially edit User 123's portfolio. Auth.js and Middleware prevent this by ensuring every request is tied to a verified identity.

Action Plan and What to Build Next
- Create a project in the Google Cloud Console and configure the OAuth screen.
- Install Auth.js in your Next.js project.
- Set up the MongoDB Adapter to sync users to your database.
- Create a
LoginButtoncomponent that triggers the Google provider. - Protect your
/dashboardfolder using Middleware.
After you have secured your app, your next step is to build the UI that authenticated users will actually use. Head over to our guide on Build SaaS Dashboard Next.js Tailwind to start designing your application's core interface.
Don't let authentication bugs slow down your launch. The Zero to SaaS Course includes a battle-tested authentication template that works out of the box. Stop worrying about security and start building features. Let's ship your SaaS together.