Secure Your Next.js Application in 5 minutes !!

D
I'm a mobile/web developer 👨💻 who loves to build projects and share valuable tips for programmers
Follow me for Flutter, React/Next.js, and other awesome tech-related stuff 😉
Search for a command to run...

No comments yet. Be the first to comment.
Lessons from Code, Content, and Consistency

Reliability basics: Outbox pattern + why it matters

Introducing Kafka/Redpanda + move to event-driven workflow

Connect Orders ↔ Inventory (first working service-to-service flow)

Inventory service + gRPC + proto contracts




npm i next-auth
api/auth called [...nextauth].js
import NextAuth from "next-auth"
import Providers from "next-auth/providers" // contains all the provider
import NextAuth from "next-auth"
import Providers from "next-auth/providers"
export default NextAuth ({
// ...
})
export default NextAuth({
providers: [
Providers.GitHub({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
// You can add here multiple provider as per your requirement
],
});



.env.local file
//.env.local
GITHUB_CLIENT_ID=2ff72fc2ae451c063edc
GITHUB_CLIENT_SECRET=60e9dc019d9d172b10662a66350cbfb16ff0d189
http://localhost:3000/api/auth/signin in the browser, you'll see one button named Sign in with Github

http://localhost:3000/api/auth/signout in the browser URL and you will see - 

/api/auth/signin or /api/auth/signout URL manually ,right?signIn and signOut from next-auth/client packageimport {signIn, signOut} from "next-auth/client"
onClick. And also don't forget to pass href.function Navbar() {
const handleSignIn = (e) => {
e.preventDefault();
signIn();
};
const handleSignOut = (e) => {
e.preventDefault();
signOut();
};
return (
<nav>
<Link href="/">
<button>Home</button>
</Link>
<Link href="/dashboard">
<button>Dashboard</button>
</Link>
<Link href="/blog">
<button>Blog</button>
</Link>
<Link href="/api/auth/signin">
<button onClick={handleSignIn}>SignIn</button>
</Link>
<Link href="/api/auth/signout">
<button onClick={handleSignOut}>SignOut</button>
</Link>
</nav>
);
}
export default Navbar;

But if you see in the navbar, The SignIn button is still visible even if the user has signed in. And also the SignOut button is visible even if the user has not signed in.
useSession.null that means the user has not signed in and we can show signIn button and hide signOut button and vice-versa.useSession hookimport { signIn, signOut, useSession } from "next-auth/client";
And now conditionally render buttons
function Navbar() {
const [session, loading] = useSession();
return (
<nav>
<Link href="/">
<button>Home</button>
</Link>
<Link href="/dashboard">
<button>Dashboard</button>
</Link>
<Link href="/blog">
<button>Blog</button>
</Link>
{!loading && !session && (
<Link href="/api/auth/signin">
<button onClick={handleSignIn}>SignIn</button>
</Link>
)}
{session && (
<Link href="/api/auth/signout">
<button onClick={handleSignOut}>SignOut</button>
</Link>
)}
</nav>
);
}
export default Navbar;

getSession.null if the user has not signed in, otherwise, return an object.import { getSession, signIn } from "next-auth/client";
import { useEffect, useState } from "react";
function Dashboard() {
const [loading, setLoading] = useState(true);
useEffect(() => {
const checkIsSignedIn = async () => {
await getSession().then((session) => {
if (!session) {
// Not Signed In
signIn();
} else {
// Signed In
setLoading(false);
}
});
};
checkIsSignedIn();
}, []);
if (loading) {
return (
<div className={styles.dashboard}>
<h2>Loading</h2>
</div>
);
}
return (
<div className={styles.dashboard}>
<h1>Dashboard page</h1>
</div>
);
}
export default Dashboard;

getSession hook to do this - import { getSession } from "next-auth/client";
import styles from "../styles/Blog.module.css";
function Blog({ data }) {
return (
<div className={styles.blog}>
<h1>{data}</h1>
</div>
);
}
export default Blog;
export async function getServerSideProps(context) {
const session = await getSession(context); // pass the context
if (!session) {
// redirecting to signIn page if not signed In
return {
redirect: {
destination: "/api/auth/signin?callbackUrl=http://localhost:3000/blog",
permanent: false,
},
};
}
return {
props: {
data: "Welcome to Blog page",
},
};
}

getSession() hook.getSession() hook.import { getSession } from "next-auth/client";
const userInfo = async (req, res) => {
const session = await getSession({ req });
if (!session) {
res.status(401).json({ error: "User not authenticated" });
} else {
res.status(200).json({ user: session.user });
}
};
export default userInfo;

/api/userInfo without signIn then you'll get a message - User not authenticated, otherwise a user data if signed in
