Chapter 2: Auth.js Initialization, Google Developer Console Application, and Environment Variable Configuration
The theory lesson is over—time to get your hands dirty! In commercial development, the hardest part of implementing third-party login is often not "writing code" but "navigating the complex and frequently updated developer backends of tech giants (like Google, Facebook, Line)."
In this chapter, we will meticulously guide you step-by-step through the Google Cloud Console. We won't just tell you "how to do it" but will also explain in detail "why these fields need to be filled out," ensuring that even if Google's interface changes in the future, you'll still understand the core logic at a glance.
🛠️ Step 1: Project Installation and Dependency Preparation
First, ensure you already have a Next.js 14+ (App Router) project set up.
Open your terminal and run the following command in the project root directory:
# Install the latest version of Auth.js (currently marked as beta to support the latest App Router features)
npm install next-auth@beta
This will install the core authentication package. Note that even though it's labeled as beta, it's already very stable in production and is highly recommended by Vercel.
Generate an Unbreakable Auth Secret
Auth.js requires a "secret key" to encrypt all Session Cookies and JWTs with high strength. Without this key—or if the key is too simple (e.g., 123456)—hackers can easily forge login credentials.
Enter this magical command in your terminal:
npx auth secret
This small utility will automatically generate a 32-byte random hash for you and add it to the .env.local file in your project root directory.
Open your .env.local, and you should see a line like this:
AUTH_SECRET="Jk9z8H/yT7xM4+qR1pW2vN6bL3jX5cD8eF0gA9hI4Kk="
⚠️ Commercial Security Warning:
ThisAUTH_SECRETis your website's "Great Wall of Defense." Never commit.env.localto GitHub (ensure.gitignoreis working). If this key leaks, hackers can directly issue admin-privileged tokens on their own machines and log into your system!
🌐 Step 2: Navigating the Google Cloud Console to Apply for Credentials
This is where countless beginners get stuck for days. Google's backend is designed for the most complex enterprises in the universe, so the interface is overwhelming. Follow these steps closely:
1. Create a GCP Project (Google Cloud Project)
- Go to the Google Cloud Console and log in with your Google account.
- Click the project dropdown in the top-left corner, then click "New Project."
- Enter the project name:
VibeTutor-Auth-System(you can customize this), then click "Create." - Wait for the small bell icon in the top-right to confirm creation, then make sure to select your newly created project.
2. Configure the OAuth Consent Screen
Google takes privacy seriously. When users click to log in, Google must display a popup saying: "VibeTutor wants to access your data! Do you agree?" We’re now designing this popup.
- From the left-hand menu, navigate to "APIs & Services" > "OAuth Consent Screen."
- User Type: Select "External."
(Note: "Internal" is only for employees within a Google Workspace enterprise domain.) - Click "Create."
Now, fill in the details:
- App name: Enter
VibeTutor Knowledge Payment Platform. This will be shown to end users. - User support email: Enter your email.
- App logo: (Optional) For commercial projects, uploading a logo is highly recommended to make the login page look professional and trustworthy.
- Authorized domains: Leave blank for local development. For production, add your official domain (e.g.,
vibe-tutor.com). - Developer contact information: Enter your email.
Next, the Scopes step:
Scopes define how much user data you’re requesting.
By default, we only need .../auth/userinfo.email and .../auth/userinfo.profile. Click "Save and Continue."
Finally, the Test users step:
While the app is in "Testing" status, only emails added here can log in successfully!
👉 Make sure to add your own and your client’s Gmail accounts here. Otherwise, you’ll get an Access Denied error during testing.
3. Create OAuth Client ID and Secret
Now that the UI is set up, let’s get the most important keys (Client ID & Client Secret).
- Click "Credentials" in the left-hand menu.
- Click "+ CREATE CREDENTIALS" at the top, then select "OAuth client ID."
- Application type: Choose "Web application."
- Name it:
VibeTutor Next.js Web Client.
Next, the two most critical and error-prone URL settings:
【Authorized JavaScript origins】
This defines where your website is hosted. Google only allows login requests from these URLs.
- Click "Add URI" and enter:
http://localhost:3000
【Authorized redirect URIs】
Recall the flowchart from Chapter 1: After users log in via Google, Google sends the "Authorization Code" back to your server. Google needs to know where to send it, or hackers could redirect it to their own servers.
This is the Callback URL.
- Click "Add URI" and enter Auth.js’s strict path:
👉http://localhost:3000/api/auth/callback/google
🚨 Common Debugging Traps:
localhostmust start withhttp://—neverhttps://(unless you have a local certificate).- The URL must not end with a slash
/.- When deploying to Vercel later, you must return here and add
https://vibe-tutor.com, or production login will fail!
After configuring, click "Create." A popup will display your Client ID and Client Secret.
Copy them.
💻 Step 3: Environment Variable Configuration and NextAuth Core Setup
Back to your code editor. Open .env.local and paste the two keys you just obtained from Google:
AUTH_SECRET="Jk9z8H/yT7xM4+qR1pW2vN6bL3jX5cD8eF0gA9hI4Kk="
# Google OAuth Credentials
AUTH_GOOGLE_ID="123456789-abcde.apps.googleusercontent.com"
AUTH_GOOGLE_SECRET="GOCSPX-xxxxxx_yyyyyy_zzzzzz"
Write the auth.ts Core Configuration File
In your Next.js project’s src directory (or the root directory if you’re not using src), create a file named auth.ts. This is where Auth.js v5 centralizes its configuration.
// src/auth.ts
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
export const {
handlers, // Handles GET/POST routes
signIn, // Login method
signOut, // Logout method
auth // Universal function to get current session state
} = NextAuth({
// Configure all third-party providers you want to support
providers: [
GoogleProvider({
clientId: process.env.AUTH_GOOGLE_ID,
clientSecret: process.env.AUTH_GOOGLE_SECRET,
// Optional: Force account selection every time
// authorization: { params: { prompt: "consent" } },
}),
],
// Advanced settings (covered in later chapters)
// pages: { signIn: '/login' }
})
🧠 Architecture Deep Dive:
Why create thisauth.tsfile? In Auth.js v4, configurations were written in API Routes, making it hard to reuse settings in Server Components. v5 extracts all configurations, producing three magic functions—signIn,signOut, andauth—that can be called anywhere in your project (frontend components, backend APIs, middleware).
Create the API Route (Route Handler)
When Google sends data back, our Next.js needs an "endpoint" to receive it.
Create this folder structure and file: src/app/api/auth/[...nextauth]/route.ts.
Note:
[...nextauth]is Next.js’s catch-all dynamic route syntax. This means all requests to/api/auth/signin,/api/auth/callback/google,/api/auth/signoutwill be intercepted by this file.
Add this code to the file:
// src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth"
// Directly use the handlers from auth.ts for GET and POST routes
export const { GET, POST } = handlers
Yes, it’s just these two lines! No need to write fetch or switch-case logic for routing. Auth.js has already encapsulated all the complex OAuth flows and token validation behind these two lines.
🎉 Step 4: Testing and Debugging
Ready to witness the magic?
- Run
npm run devin your terminal to start the dev server. - Open your browser and manually enter:
👉http://localhost:3000/api/auth/signin
You’ll see a minimalist login page auto-generated by Auth.js, with a white "Sign in with Google" button.
Take a deep breath and click it.
If everything is set up correctly:
- You’ll be redirected to Google’s account selection page.
- The URL bar will show a long Google authorization URL with
client_id=.... - After selecting your Google account, the page will flicker and redirect back to
http://localhost:3000.
🚨 Common Errors and Ultimate Rescue Guide
In the real world, only about 10% of people succeed on their first try. If you see red errors, refer to these solutions:
Error 1: Error: redirect_uri_mismatch (shown on Google’s page)
- Cause: Your
localhosthas a weird port, or you mistyped the Callback URL in Google Console. - Fix: Go back to Google Cloud Console’s "Credentials" page and double-check that the "Authorized redirect URI" exactly matches
http://localhost:3000/api/auth/callback/google. Wait 5 minutes for Google’s servers to sync.
Error 2: Access Denied (403) (shown on Google’s page)
- Cause: Your OAuth app is in "Testing" status, and the Gmail account you’re using to log in is not in the "Test users" list.
- Fix: Return to the OAuth consent screen settings and add your email to the Test users list.
Error 3: Page crashes after clicking the button, Terminal shows MissingSecret
- Cause: Your
.env.localdoesn’t haveAUTH_SECRET, or you modified environment variables without restarting the Next.js server. - Fix: Verify
.env.localis correct, then pressCtrl+Cto stop the server and rerunnpm run dev.
Chapter Summary
Congratulations! You’ve conquered the most troublesome part of third-party login—"creating developer credentials"—and successfully integrated Auth.js into your Next.js project with Google login.
But Google login alone isn’t enough. For commercial development in Taiwan, the next client request will always be: "I want Line login."
In the next chapter, we’ll explore the even more closed and challenging Line Developers backend and learn how to elegantly support multiple third-party logins in the same system.