Skip to main content

14.2 - NextAuth Overview and Session Information

NextAuth

NextAuth is a popular authentication library for Next.js applications. It provides a flexible and easy-to-use solution for adding authentication to your Next.js app, supporting various authentication providers and session management.

Overview

NextAuth integrates seamlessly with Next.js and supports various authentication strategies, including email, credentials, OAuth providers (like Google and GitHub), and more. It handles the complexity of managing user sessions and provides simple methods to access and utilize session information.

Basic Configuration

Create a [...nextauth].ts or [...nextauth].js file inside the pages/api/auth directory to configure NextAuth. Here’s an example configuration for using Google as an OAuth provider:

// pages/api/auth/[...nextauth].ts
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,
}),
],
// Add any additional configuration options here
});

In this configuration:

  • GoogleProvider: Sets up Google as an OAuth provider, using your client ID and secret from Google.

Using Session Information

Once NextAuth is set up, you can access session information in your application. Here's how you can work with session data:

Accessing Session Data

Use the useSession hook from NextAuth to access session information in your components:

// pages/index.tsx
import { useSession, signIn, signOut } from "next-auth/react";

const HomePage = () => {
const { data: session } = useSession();

if (session) {
return (
<div>
<h1>Welcome, {session.user.name}!</h1>
<button onClick={() => signOut()}>Sign Out</button>
</div>
);
}

return (
<div>
<h1>Not signed in</h1>
<button onClick={() => signIn()}>Sign In with Google</button>
</div>
);
};

export default HomePage;

In this example:

  • useSession: Retrieves the current session data. If the user is signed in, their name is displayed, and they have the option to sign out. If not signed in, a sign-in button is shown.

Protecting Routes

To protect routes and ensure only authenticated users can access them, use the getSession function on the server side:

// pages/protected.tsx
import { getSession } from "next-auth/react";

const ProtectedPage = ({ session }) => {
if (!session) {
return <div>Access Denied</div>;
}

return <div>Welcome to the protected page, {session.user.name}!</div>;
};

export async function getServerSideProps(context) {
const session = await getSession(context);

return {
props: {
session,
},
};
}

export default ProtectedPage;

In this example:

  • getSession: Retrieves the session data on the server side. If the session does not exist, the page shows an "Access Denied" message. Otherwise, it displays the protected content.