Building a Next.js Navigation Bar with Authentication using NextAuth.js

Building a Next.js Navigation Bar with Authentication using NextAuth.js

In this tutorial, I will build you a responsive navigation bar for a Next.js application that incorporates user authentication using NextAuth.js. The navigation bar will adapt to different screen sizes, providing a seamless experience for both desktop and mobile users. We'll use the "next-auth/react" library to handle authentication, and Next.js components like "Link" and "Image" for navigation elements. Let's get started!

Prerequisites:

  • Basic knowledge of Next.js and React.

  • A working Next.js project set up.

Step 1: Set up NextAuth.js First, make sure you have NextAuth.js set up in your project to enable authentication. Refer to the NextAuth.js documentation to learn how to set it up for your specific authentication providers.

Step 2: Create the Nav Component Create a new file called "Nav.js" in your components directory and paste the following code:

Code Block 1: Importing Required Modules

"use client";

import Link from "next/link";
import Image from "next/image";
import { useEffect, useState } from "react";
import { signIn, signOut, useSession, getProviders } from "next-auth/react";

Explanation:

  • use client: This seems to be a custom comment that might be used by a tool or preprocessor in the development environment, but it doesn't have a direct impact on the code itself.

  • import Link from "next/link";: This imports the Link component from the Next.js library, which is used for client-side navigation between pages.

  • import Image from "next/image";: This imports the Image component from Next.js, used for image optimization and performance.

  • import { useEffect, useState } from "react";: These imports are standard React hooks for managing side effects and state in function components.

  • import { signIn, signOut, useSession, getProviders } from "next-auth/react";: These imports are provided by the next-auth/react package and are used to handle authentication with NextAuth.js.

Code Block 2: Nav Component

const Nav = () => {
  // ...
}

Explanation:

  • This defines a functional component called Nav that represents the navigation bar.

Code Block 3: State and Session Variables

const { data: session } = useSession();

const [providers, setProviders] = useState(null);
const [toggleDropdown, setToggleDropdown] = useState(false);

Explanation:

  • const { data: session } = useSession();: This line uses the useSession hook provided by NextAuth.js to get the current user session. The session variable will contain information about the authenticated user if they are signed in or null if they are not.

  • const [providers, setProviders] = useState(null);: This line initializes a state variable called providers with the initial value of null. This state variable will be used to store the authentication providers available for signing in.

  • const [toggleDropdown, setToggleDropdown] = useState(false);: This line initializes a state variable called toggleDropdown with the initial value of false. This variable will be used to control the visibility of the mobile navigation dropdown menu.

Code Block 4: Fetching Authentication Providers

useEffect(() => {
  (async () => {
    const res = await getProviders();
    setProviders(res);
  })();
}, []);

Explanation:

  • This useEffect hook is used to fetch the authentication providers when the component mounts (as indicated by the empty dependency array []).

  • async () => {...}: This is an asynchronous arrow function used to fetch the authentication providers.

  • const res = await getProviders();: This line uses the getProviders function provided by NextAuth.js to fetch the available authentication providers.

  • setProviders(res);: This sets the providers state variable with the fetched authentication providers.

Code Block 5: Navigation Markup

return (
  <nav className='flex-between w-full mb-16 pt-3'>
    {/* ... */}
  </nav>
);

Explanation:

  • This part of the component returns the JSX markup representing the navigation bar. The navigation bar will have the class names flex-between, w-full, mb-16, and pt-3.

Code Block 6: Logo and Branding

<Link href='/'>
  <a className='flex gap-2 flex-center'>
    <Image
      src='/assets/images/logo.svg'
      alt='logo'
      width={30}
      height={30}
      className='object-contain'
    />
    <p className='logo_text'>Promptopia</p>
  </a>
</Link>

Explanation:

  • This part represents the logo and branding section of the navigation bar.

  • Link href='/': This uses the Link component to create a client-side link to the home page ('/') of the application.

  • <a className='flex gap-2 flex-center'>: This wraps the logo and brand text inside an anchor (<a>) tag with the class names flex, gap-2, and flex-center.

  • <Image ... />: This uses the Image component from Next.js to display the logo with optimized image loading. The src, alt, width, and height attributes define the image properties.

There you have it. We have successfully created a navbar in NextJs incorporated with Google auth. That's it for this blog. Follow for more!

Did you find this article valuable?

Support Anubhav Adhikari by becoming a sponsor. Any amount is appreciated!