Implementing Authentication in Next.js with NextAuth.js
Introduction
Authentication is an essential part of web applications, ensuring that users can securely access their accounts. In this guide, we’ll walk through implementing authentication in Next.js using NextAuth.js, a powerful authentication library that simplifies user login with various providers like Google, GitHub, and email/password.
If you're a beginner, don’t worry! We'll break everything down into simple steps with examples so you can easily follow along.
Why Use NextAuth.js?
NextAuth.js is a flexible and easy-to-set-up authentication library for Next.js. It provides:
- Multiple authentication providers (Google, GitHub, Facebook, Twitter, Credentials, etc.)
- Built-in session handling
- Secure JWT-based authentication
- Custom authentication options
Instead of building an authentication system from scratch, NextAuth.js handles most of the heavy lifting for you!
Step-by-Step Guide to Setting Up Authentication
1. Setting Up a Next.js Project
First, ensure you have Node.js installed. Then, create a new Next.js project by running:
npx create-next-app@latest nextauth-demo
cd nextauth-demo
Next, install NextAuth.js:
npm install next-auth
2. Creating the NextAuth API Route
Create a new file at pages/api/auth/[...nextauth].js:
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,
}),
],
});
This code tells NextAuth.js to use Google authentication as a provider.
3. Setting Up Environment Variables
Create a .env.local file in the root of your project and add:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
NEXTAUTH_URL=http://localhost:3000
Replace your-google-client-id and your-google-client-secret with values from your Google Cloud Console.
4. Creating the Login Page
Create a new file pages/login.js:
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";
export default function Login() {
const { data: session } = useSession();
const router = useRouter();
useEffect(() => {
if (session) {
router.push("/dashboard");
}
}, [session]);
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>Login</h1>
<button onClick={() => signIn("google")}>Sign in with Google</button>
</div>
);
}
5. Adding Sign-in and Sign-out Buttons
Modify your pages/index.js file:
import { signIn, signOut, useSession } from "next-auth/react";
export default function Home() {
const { data: session } = useSession();
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
{session ? (
<>
<p>Welcome, {session.user.name}!</p>
<img src={session.user.image} alt={session.user.name} width={50} />
<button onClick={() => signOut()}>Sign out</button>
</>
) : (
<button onClick={() => signIn("google")}>Sign in with Google</button>
)}
</div>
);
}
6. Protecting Pages with Authentication
Create a new protected page, pages/dashboard.js:
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";
export default function Dashboard() {
const { data: session, status } = useSession();
const router = useRouter();
useEffect(() => {
if (status === "unauthenticated") router.push("/login");
}, [session, status]);
if (status === "loading") return <p>Loading...</p>;
return <h1>Welcome to your Dashboard, {session?.user?.name}!</h1>;
}
Final Thoughts
Congratulations! 🎉 You’ve successfully implemented authentication in Next.js using NextAuth.js. Now, your users can log in with Google securely.
If you found this guide helpful, share it with fellow developers and stay tuned for more beginner-friendly Next.js tutorials! 🚀

Comments
Post a Comment