Next JS Authentication

MAHBUBUL ALAMMAHBUBUL ALAM
3 min read

We will guide step by step next js authentication. Lets start from creating project

Step 1: Create a Next JS project

run this command and create a next js project.

npx create-next-app@latest

Step 2: Create Some Pages

for authentication implementation create some pages like:

src/app/login/page.ts
src/app/register.ts
src/app/dashboard/page.ts

Step 3: Install Next Auth and Basic Setup

Follow official documentation of next Auth.

  • 1st install next auth package

      npm install next-auth
    
  • Create a folder and files like this: src/utils/authOptions and write this code:

      import { NextAuthOptions } from "next-auth";
      import GithubProvider from "next-auth/providers/github";
      import GoogleProvider from "next-auth/providers/google";
    
      export const authOptions: NextAuthOptions = {
        providers: [
          GithubProvider({
            clientId: process.env.GITHUB_ID as string,
            clientSecret: process.env.GITHUB_SECRET as string,
          }),
          GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID as string,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
          }),
        ],
        pages: {
          signIn: "/login",
        },
        secret: process.env.NEXTAUTH_SECRET,
      };
    

    now create a file in this folder directory src/app/app/api/auth/[...nextauth]/route.ts and write this code in route.ts file:

      import { authOptions } from "@/utils/authOptions";
      import NextAuth from "next-auth";
    
      const handler = NextAuth(authOptions);
    
      export { handler as GET, handler as POST };
    
    • Last things you need to setup github and google clientId and clientSecret

      go to this links and create OAuth account generate this :
      Github
      Google

      • After get this clientId and clientSecret you need to add this in .env file. you can creatre .env file in you propject root directory. And code will be like this.
        GITHUB_ID=Ov23liN3Yin12w
        GITHUB_SECRET=e08bf545c4debc6dec1d3b51394cc7
        GOOGLE_CLIENT_ID=178739961571-h676j2crvlhehar.apps.googleusercontent.com
        GOOGLE_CLIENT_SECRET=GOCSPX-UQPxDqVd-chbI92v7
        BACKEND_URL=http://localhost:5000/api/v1
        NEXTAUTH_SECRET=abcd

Step 4: Implement social Login

in you Google Login button add code like this

<button onClick={() => signIn("google", {callbackUrl: "http://localhost:3000/dashboard" })}>
Google Login
</button>
  • Now we can access our use in our dashboard page . wite like this code:

      // import this 
      import { authOptions } from "@/utils/authOptions";
      import { getServerSession } from "next-auth";
    
       const session = await getServerSession(authOptions);
    
        console.log(session);
    

    Example:

      import { authOptions } from "@/utils/authOptions";
      import { getServerSession } from "next-auth";
      import Image from "next/image";
    
      const DashboardPage = async () => {
        const session = await getServerSession(authOptions);
    
        console.log(session);
    
        return (
          session && (
            <div>
              <h1 className="text-4xl text-center mt-10">
                Welcome To Dashboard Page
              </h1>
              <div className=" text-center text-xl text-blue-700 py-5">
                Email: {session?.user?.email}
              </div>
              <div className=" text-center text-xl text-blue-700 py-5">
                Email: {session?.user?.name}
              </div>
              <div className=" text-center text-xl text-blue-700 py-5">
                <Image
                  className="mx-auto rounded-full"
                  src={session?.user?.image as string}
                  alt="github profile image"
                  height={200}
                  width={200}
                />
              </div>
            </div>
          )
        );
      };
      export default DashboardPage;
    

    Step 5: Protect Route

  • Now you need to protected any route make a file like: src/middleware.ts and write this code:

      export { default } from "next-auth/middleware";
    
      export const config = { matcher: ["/dashboard"] };
    

    you can add multiple route to protected . In matcher: ["/dashboard"] array to add

       matcher: ["/dashboard", "/user"]
    
0
Subscribe to my newsletter

Read articles from MAHBUBUL ALAM directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MAHBUBUL ALAM
MAHBUBUL ALAM

Hi, I am Full Stack Developer. I can build web application, android application, desktop application. My core programming language is JavaScript.