Authentication helps confirm who you are when using a website or app. It keeps your information safe and private.
0
0
Why authentication matters in NextJS
Introduction
When users need to log in to access their personal dashboard.
When you want to protect sensitive data like payment details.
When you want to allow users to save their progress or preferences.
When you want to restrict certain pages to only registered users.
When you want to track user activity securely.
Syntax
NextJS
import { useSession, signIn, signOut } from 'next-auth/react'; function Component() { const { data: session } = useSession(); if (session) { return ( <> <p>Welcome, {session.user.name}!</p> <button onClick={() => signOut()}>Sign out</button> </> ); } return <button onClick={() => signIn()}>Sign in</button>; }
This example uses next-auth, a popular authentication library for Next.js.
useSession hook checks if the user is logged in or not.
Examples
Shows a greeting if the user is signed in, otherwise asks to sign in.
NextJS
import { useSession } from 'next-auth/react'; function Greeting() { const { data: session } = useSession(); return <p>{session ? `Hello, ${session.user.email}` : 'Please sign in'}</p>; }
Button to sign in using GitHub as the provider.
NextJS
import { signIn } from 'next-auth/react'; export default function SignInButton() { return <button onClick={() => signIn('github')}>Sign in with GitHub</button>; }
Sample Program
This component shows a welcome message and sign out button if the user is logged in. Otherwise, it shows a sign in button.
NextJS
import { useSession, signIn, signOut } from 'next-auth/react'; export default function AuthExample() { const { data: session } = useSession(); if (session) { return ( <main> <h1>Welcome, {session.user.name}!</h1> <p>You are signed in.</p> <button onClick={() => signOut()}>Sign out</button> </main> ); } return ( <main> <h1>You are not signed in.</h1> <button onClick={() => signIn()}>Sign in</button> </main> ); }
OutputSuccess
Important Notes
Always protect sensitive pages by checking authentication on the server or client.
Use secure cookies and HTTPS to keep user data safe.
Make sure to handle loading states when checking if a user is signed in.
Summary
Authentication confirms who a user is and protects their data.
Next.js apps use libraries like next-auth to handle authentication easily.
Always check if a user is signed in before showing private content.